Skip to main content

Posts

Showing posts with the label php

PHP code for finding distinct elements common to all rows of a matrix in O(n) time complexity

<?php class Matrix{ /** •@param 2D array $matrix • •Prints distinct elements common to all rows of the matrix */ public static function getDistinctElementsCommonToAllRows($matrix){ // A hash map to store count of elements $hashmap = array(); $selectedHash = array(); $rows = count($matrix); $cols = count($matrix[0]); for ($i = 0; $i < $rows; $i++) { // Increment the count of first // element of the row if(array_key_exists($matrix[$i][0],$hashmap)){ $hashmap[$matrix[$i][0]] = $i+1; } // Starting from the second element // of the current row for ($j = 1; $j < $cols; $j++) { ...

Write a function that checks if a given word stored in a doubly linked list is a palindrome.

<?php class Node { public $value; public $next = null; // next node public $prev = null; // previous node public function __construct($value) { $this->value = $value; } } class Palindrome { /** •@param string $word •@return bool */ public static function isPalindrome($head, $tail){ if ($head == null) return true; while ($head != $tail){ if ($head->value != $tail->value) return false; $head = $head->next; $tail = $tail->prev; } return true; } } $head = new Node(1); $firstNode = new Node(2); $secondNode = new Node(3); $tail = new Node(4); $head->next = $firstNode; $firstNode->prev = $head; $firstNode->next = $secondNode;...

PHP code for finding Longest Repeated Substrings (LRS)

<?php Class LRS{ /** •@param array $texts •Prints longest repeated substrings for each text */ public static function getAllLRS($texts){ $stringArr = array(); foreach($texts as $string){ $stringArr[] = self::LongestRepeatedSubstring($string); } return $stringArr; } public function LongestRepeatedSubstring($string){ if ($string == null) return null; $string_length = strlen($string); $substrings = array(); for ($i=0; $i < $string_length; $i++){ $substrings[$i] = substr($string, $i); } sort($substrings); $result = ""; for ($i = 0; $i < $string_length - 1; $i++){ $lcs = self::LongestCommonString($substrings[$i], $substrings[$i ...

PHP code for Implementing LRU cache.

<?php interface LRUCache{ /** •@param string $key •@param string $value •@return bool $result • •Stores value against the key in the cache */ public function insertIntoCache($key,$value); /** •@param string $key •@return string $value •Gets the value of a key from the cache */ public function getFromCache($key); /** Purge the entire cache */ public function purgeCache(); /** •@return int $count •Gets the number of successful cache hits so far */ public function allCacheHits(); /** •@return int $count •Gets the number of unsuccessful cache hits so far **/ public function allCacheMissed(); } class Cache implements LRUCache{ // int the max number of elements the cache supports private $capaci...

PHP code to find the diameter of tree in O(n) time complexity

<?php class BinaryNode{ public $value = null; // node value public $left = null; // left child public $right = null; // right child public function __construct($value) { $this->value = $value; } } class BinaryTreeDiameter{ //find the diameter and print its value public function findDiameterOfTree($root){ //Checking node is empty or not if($root === null){ return 0; } // Compute the depth of each subtree $lDepth = $this->findDiameterOfTree($root->left); $rDepth = $this->findDiameterOfTree($root->right); // Return the greater one. if ($lDepth > $rDepth) return $lDepth+1; else return $rDepth+1; } //find the diameter and print its ...

Object Cloning in PHP

In simple words 'object cloning' can be defined as copying the object property and assigning to a different object. But when we copy an object then it only owns the reference, not the value. In PHP this is done by two method- 1) By using clone Keyword- In this, a shallow copy of the object is made. It means the internal object of the objectA is not cloned to the internal object of objectB. class CloneableClass { private $_internalObject ; public function __construct () { // instantiate the internal member $this -> _internalObject = new stdClass (); } } $objectA = new CloneableClass (); $objectB = clone $objectA ; 2) By using __clone() method- if your object holds a reference to another object which it uses and when you replicate the parent object you want to create a new instance of this other object so that the replica has its own separate copy. In this the magic method __clone() is...

Magic Function in PHP (__sleep() and __wakeup() )

There are many magic methods in PHP like  __construct(), __destruct(), __callback(), __get(), __set(), __sleep(), __wake() and many more. But we will be takingon  on  __sleep() and  __wake(). __sleep() : serialize() checks if your class has a function with the magic name __sleep(). If so, that function is executed prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn't return anything then NULL is serialized and E_NOTICE is issued. serialize() is used for the representation of the storage class for storing the value. Serializing   an object means converting it to a byte stream representation that can be stored in a file. The use of __sleep()  to commit the pending task. If a bulk data is being inserted then at that time __sleep can be used. it will not release the object unless the work is not completed....

PHP function to get MAC and IP address

PHP function to obtain the machine MAC and IP address. By this function, you will be able to get the physical address of the machine. function getMAC(){ ob_start(); system('ipconfig /all'); $mycom=ob_get_contents(); ob_clean(); $findme = "Physical"; $pmac = strpos($mycom, $findme); $mac=substr($mycom,($pmac+36),17); return $mac; } function getIP(){ $ip=$_SERVER['REMOTE_ADDR']; if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip=$_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; } $ips = explode(",", $ip); $ipss=$ips[0]; return $ipss; }

PHP function for checking IMEI

Luhn algorithm for IMEI Check public function __checkIMEI($imei){ if(strlen($imei)==15){ $imeia=($imei[1]*2); if(strlen($imeia)==2){$imeia=str_split($imeia,1); $imeia=$imeia[0]+$imeia[1]; } $imeib=($imei[3]*2); if(strlen($imeib)==2){$imeib=str_split($imeib,1); $imeib=$imeib[0]+$imeib[1]; } $imeic=($imei[5]*2); if(strlen($imeic)==2){$imeic=str_split($imeic,1); $imeic=$imeic[0]+$imeic[1]; } $imeid=($imei[7]*2); if(strlen($imeid)==2){$imeid=str_split($imeid,1); $imeid=$imeid[0]+$imeid[1];} $imeie=($imei[9]*2); if(strlen($imeie)==2){$imeie=str_split($imeie,1); $imeie=$imeie[0]+$imeie[1]; } $imeif=($imei[11]*2); if(strlen($imeif)==2){$imeif=str_split($imeif,1); $imeif=$imeif[0]+$imeif[1]; } $imeig=($imei[13]*2); if(strlen($imeig)==2){$imeig=str_split($imeig,1); $imeig=$imeig[0]+$imeig[1]; } $IMEI= ($ime...

Code for Mail in PHP

PHP mail function and mail configuration in  XAMPP  and sending mail is done from sendmail through localhost. I hope it will help you. mail() function <? php $to = 'dubeynitish22@hotmail.com' ; $subject = 'Test' ; $message = 'Hello' ; $headers = 'From: webmaster@example.com' . "\r\n" . 'Reply-To: webmaster@example.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion ();   if (! mail ( $to , $subject , $message , $headers )){ echo "Error !!" ; } else { echo "Email Sent !!" ; } ?> 2. php.ini configuration (For SEND-MAIL) [ mail function ] ; For Win32 only . ; http : //php.net/smtp ; SMTP = localhost ; http : //php.net/smtp-port ; smtp_port = 25   ; For Win32 only . ; http : //php.net/sendmail-from ; sendmail_from = me@example . com   ; For Unix only . You may supply arguments as well ( default : "sendmail -t -i...

How to install LARAVEL5 with Xampp (Windows)

Hi,  Today I am with the installation guide of LARAVEL5 in windows. Step 1)  Requirements a) PHP >= 5.5.9 b) OpenSSL PHP Extension c) PDO PHP Extension d) Mbstring PHP Extension e) Tokenizer PHP Extension Step 2)  Install Xampp First of all, we need Xampp, so we can download it from the official page: Download Xampp Step 3)  INSTALL Composer If you've downloaded and installed Xampp, you need to install Composer.                 "Composer is a PHP package manager that is integrated with Laravel Framework.                  In Windows, we can install it easy going to the official page and download the installer." Composer Download page After installing it, open a Windows terminal and write composer. Step 4) Xampp Virtual Host    We will configure a Virtual Host in Xampp for a Laravel project, and in this example, we wa...

A perfect answer by someone, why FACEBOOK used PHP.

If someone like Mark Zuckerberg were creating Facebook today (2012 as I am writing this answer), sure, no doubt they would consider many other languages, frameworks, platforms, architectures. It's impossible to say whether they would still choose PHP today if they were starting out. Other social-network companies are starting today, and clearly, some fraction of them are still choosing PHP. They may choose PHP because it does the job they need to do, and they know they can hire developers who know it and can be productive with it. Facebook has obviously been very successful using PHP (even though at that time PHP 5.0.0 was still beta).  There's a strong argument to be made that  writing viable software has little to do with the choice of language .  One can find anecdotes of successful projects or disastrous projects using any language. According to the history described on the Wikipedia page for Facebook, Zuckerberg wrote the initial code for Facebook in October...

Program for Making a table of given row and column where column are filled vertically in increment like 1234....

<!--Program for Making a table of given row and column where the column is filled vertically in increment like 1234....--> <! DOCTYPE html > <html> <body> <?php $i = 8 ; $j = 10 ; for ( $row = 0 ; $row < $i ; $row ++) { echo "<table border='1' width='50%'><tr>" ; for ( $col = 0 ; $col < $j ; $col ++) { if ( $col == 0 ){ echo "<td>" .( $row + 1 ). "</td>" ; $c =( $row + 1 ); } else { echo "<td>" .( $c + $i ). "</td>" ; $c =( $c + $i ); } } echo "</tr></table>" ; } ?> </body> </html> #Output

Reducing Image File Size (Compression) using PHP GD

<!--Code snippets for Reducing of image size--> <?php header ( 'Content-Type: image/jpeg' ); function compress_image ( $source_url , $destination_url , $quality ) { $info = getimagesize ( $source_url ); if ( $info [ 'mime' ] == 'image/jpeg' ) $image = imagecreatefromjpeg ( $source_url ); elseif ( $info [ 'mime' ] == 'image/gif' ) $image = imagecreatefromgif ( $source_url ); elseif ( $info [ 'mime' ] == 'image/png' ) $image = imagecreatefrompng ( $source_url ); //save it var_dump ( $destination_url ); header ( 'Content-Type: image/jpeg' ); imagejpeg ( $image , $destination_url , $quality ); //return destination file url return $destination_url ; } $source_photo = 'http://localhost/test/uploads/image2.jpg' ; $dest_photo = $_SERVER [ 'DOCUMENT_ROOT' ]. '/test/uploads/image5.jpg' ; $d = compress_image ( $source_photo , $...

MongoDB for Windows

Download MongoDB from  https://www.mongodb.com/download-center#community MongoDB connection with PHP(XMPP) for windows 1) Install MongoDB. 2) open cmd with the administrator and where MongoDB is installed. when it is installed in C drive --- 3)type in cmd---C:\Program Files\MongoDB\Server\3.2\bin. 3)Make folder test in d Drive client location C:\Program Files\MongoDB\Server\3.2\bin\mongod --dbpath "d:\test\mongodb data 4) run client open another cmd with the administrator and run the mongo.exe 5) after that download the latest package from- https://s3.amazonaws.com/drivers.mongodb.org/php/index.html 6) then open c--> xampp-->php-->ext-->paste all extracted files. and change one file to 'php_mongo.dll' 7) open php_ini and write---- extension=php_mongo.dll 8) set the environment variable in control panel-->system setting->advnaced->set environment variable--paste the path of PHP and then restart the server and check in php ini file m...