Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Wednesday, 26 August 2020

PHP Program Reverse the String without Function

PHP Program Reverse the String without Function


 Write a PHP  function FirstReverse(str) take the str parameter being passed and return the string in reversed order. 

    For Example: if the input string is "Hello World and Coders" then your program should return the string sredoC dna dlroW olleH.

Solution:


function FirstReverse($str) {
    $result='';
    for($i=strlen($str)-1; $i>=0; $i--){
      $result = $result.$str[$i];
    }  
      return $result;

}



PHP Program Find Intersection between Two array

PHP Program Find Intersection between Two array

Create PHP  function FindIntersection(strArr) read the array of strings stored in strArr which will contain 2 element

 the first element will represent a list of comma-separated numbers sorted in ascending order.
 the second element will represent a second list of comma-separated numbers. 

Your function should return a comma-separated string containing the numbers that occur in elements of strArr in sorted order.
  If there is no intersection, return the string false.


Solution:

  function FindIntersection($strArr) {
    $return ='false';  
    $array1 = explode(',',$strArr[0]);
    $array1= array_map('trim',$array1);

    $array2 = explode(',',$strArr[1]);
    $array2= array_map('trim',$array2);

    $result= array_intersect($array1,$array2);
    if(!empty($result)){
      $return=implode(',',$result);  
    }

  return $return;

}
  

PHP Program Longest Word from the string

PHP Program Longest Word from the string

 Create PHP function LongestWord(sen) take the sen parameter being passed and return the largest word in the string.

If there are two or more words that are the same length, return the first word from the string with that length. 

Ignore punctuation and assume sen will not be empty.




Solution: 


function LongestWord($sen) {
    $return = '';

    //Convert string into Array
    $strArrayList = explode(' ', $sen);
    $finalArray = array();

    ///////Filter the words///////////
    foreach($strArrayList as $str){
        $str = preg_replace("#[[:punct:]]#", "", $str);
        $finalArray[] = $str;
    }
    ///////Filter the words///////////
    
    /////////// Get the First word  from the string with that length////////
    foreach($finalArray as $word){
        if(strlen($word)> strlen($return)){
        $return = $word;
        }
    }
    /////////// Get the First word  from the string with that length////////
    
    
    return $return;

}


Tuesday, 25 August 2020

PHP Username Validation program

 

PHP Username Validation program

Creat function usernameValidation(str) take the str parameter being passed and determine if the string is a valid username according to the following rules:
  1. The username is between 4 and 25 characters.
  2. It must start with a letter.
  3. It can only contain letters, numbers, and the underscore character.
  4. It cannot end with an underscore character.
If the username is valid then your program should return the string true, otherwise return the string false

Solution:
function usernameValidation($str) {
    $return = true;
    
    ////////////////// 4 to 25 character////////////
    if ($return) {
        if (!(strlen($str) >= 4 && strlen($str) <= 25)) {
            $return = false;
        }
    }
    ////////////////// 4 to 25 character////////////
    
    ////////////////// Must start with Number ////////////
    if ($return) {
        $asciiCode = ord($str[0]);
        if (!(($asciiCode >= 97 && $asciiCode <= 122) || ($asciiCode >= 65 && $asciiCode <= 90))) {
            $return = false;
        }
    }
    ////////////////// Must start with Number ////////////
    
    ///////////// It can only contain letters, numbers, and the underscore character.///////////
    if ($return) {
        for ($i = 0; $i < strlen($str); $i++) {
            $asciiCode = ord($str[$i]);
            if (!( ($asciiCode >= 97 && $asciiCode <= 122) || ($asciiCode >= 65 && $asciiCode <= 90) || ($asciiCode >= 48 && $asciiCode <= 57) || ($asciiCode == 95))) {
                $return = false;
                break;
            }
        }
    }
    ///////////// It can only contain letters, numbers, and the underscore character.///////////
    
    ///////////It cannot end with an underscore character.///////////
    if ($return) {
        $asciiCode = ord($str[$i - 1]);
        if ($asciiCode == 95) {
            $return = false;
        }
    }
    ///////////It cannot end with an underscore character.///////////
    
    return $return ? 'true' : 'false';
}

Sunday, 29 March 2020

General error: 1364 Field city_id doesn't have a default value


I have upgraded the MySQL from 5.5 to 5.6 and then getting below type of errors.
General error: 1364 Field 'city_id' doesn't have a default value

(I was not getting such type of error, it must come after upgrading my MySQL Version from 5.5 to 5.6)

Solution: It have 3 Solutions

  1. In Your Code (PHP), always set a default value (if no value) before save.
    $objSaveData->saveData(
        array(
            'id'=>111,
            'name'=>'New user',
            'city_id'=>0, //default value
        );
    );
    
  2. Create fields with default values set in datatable. It could be empty string, which is fine for MySQL server running in strict mode.
    like below:
    ALTER TABLE `users` CHANGE `city_id` `city_id` INT(10) UNSIGNED NOT NULL DEFAULT '0';
    
  3. Disable MySQL Strict Mode (Most appropriate)
    Disable it by setting your own SQL_MODE in the my.cnf file, then restart MySQL.

    Look for the following line:
    sql-mode = "STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
    Change it to:
    sql-mode="" 
    Restart the MySQL Service.



Saturday, 21 December 2019

What are special characters? and how to remove special characters?

What are special characters? and how to remove special characters?

Question: What are special characters?
Special characters are selected punctuation characters present on standard US keyboard.


Question: Provide list of special characters?
Character Name
Space
 ! Exclamation
" Double quote
# Number sign (hash)
$ Dollar sign
 % Percent
& Ampersand
' Single quote
( Left parenthesis
) Right parenthesis
* Asterisk
+ Plus
, Comma
- Minus
. Full stop
/ Slash
 : Colon
 ; Semicolon
< Less than
= Equal sign
> Greater than
 ? Question mark
@ At sign
[ Left bracket
\ Backslash
] Right bracket
^ Caret
_ Underscore
` Grave accent (backtick)
{ Left brace
| Vertical bar
} Right brace
~ Tilde



Question: How to remove special characters from string including space?
$string='test !@#ing';
echo preg_replace('/[^A-Za-z0-9\-]/', '', $string);



Question: How to remove special characters from string except space?
$string='test !@#ing';
echo preg_replace('/[^A-Za-z0-9\-\s]/', '', $string);



Question: How to replace special characters with hyphen?
$string='test !@#ing';
echo preg_replace('/[^A-Za-z0-9\-\s]/', '-', $string);



Question: How to replace multiple hyphen with single hyphen?
$string='test-----ing';
echo preg_replace('/-+/', '-',$string);



Question: How to remove special characters from array?
$array=array('test !@#ing','sdalkjsad','#$#33');
function cleanData($string){
return preg_replace('/[^A-Za-z0-9\-]/', '', $string);
}
$array = array_map('cleanData',$array);
print_r($array);



Question: How to remove all special characters from javascript?
var stringToReplace='test !@#ing';
stringToReplace=stringToReplace.replace(/[^\w\s]/gi, '')



Saturday, 14 December 2019

How to add number of days to a date in PHP?

How to add number of days to a date?


Program Example
$Date = "2020-09-19";
echo date('Y-m-d', strtotime($Date. ' + 1 days'));
echo date('Y-m-d', strtotime($Date. ' + 2 days'));

Output
2020-09-18
2020-09-19



Question: How to add number of days to a current date?
echo date('Y-m-d', strtotime("+10 days"));

It would add 10 days to the current date.


Question: How to subtract number of days to a current date?
echo date('Y-m-d', strtotime("-10 days"));

It would subtract 10 days to the current date.


Question: How to add number of days to a on given date?
$date = new DateTime('2016-12-14');
echo date('Y-m-d', ($date->getTimestamp()+ (3600*24*10) )); //3600 = 1 hour

It would add 10 days to the current date.


Question: How to subtract number of days to a given date?
$date = new DateTime('2016-12-14');
echo date('Y-m-d', ($date->getTimestamp()- (3600*24*10) )); //3600 = 1 hour

It would subtract 10 days to the current date.


Wednesday, 13 February 2019

PHP 7 interview Questions and Answers

PHP 7 interview Questions and Answers

Question: What is class Constants?
You can define constant as string OR expression within the class. but you can not define class as variable, or function.


Question: When will Autoloading function will be called once defined?
a) spl_autoload_register (autoload) will called when create object of class.
b) spl_autoload_register will called when extend by any class (using extends).
c) spl_autoload_register will called when implements an interface (using implements ).


Question: What is visibility? What are different type of visibility in class?
visibility means setting the access level of data member and member function.
Class methods must be declare as public, protected or private.
You can also declare with var which means public


Question: What is Static Keyword?
Declaring class property or methods as static makes them accessible without needing an instantiation of the class.
$this is not available inside the function.


Question: Tell me about Abstraction in PHP?
  1. Classes defined as abstract may not be instantiated.
  2. Class that contains at least one abstract method must also be abstract.
  3. When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child.
  4. if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.



Question: Tell me about Interface in PHP?
  1. We use "interface" keyword to create class.
  2. All methods declared in an interface must be public.
  3. To implement an interface, the implements operator is used.
  4. We can include multiple interface while implementing



Question: Tell me about Traits in PHP?
Traits are a mechanism for code reuse in single inheritance languages such as PHP.
We can't create instance of a traits
We can create Traits as below
    
trait Hello {
        public function sayHello() {
            echo 'Hello ';
        }
    }
We can use multiple traits using comma like below
 use Hello, World;
When two traits have same function, it would conflict but we can fix using insteadof like below
A::bigTalk insteadof B;
We can set the visibility of function using "as" like below
use HelloWorld { sayHello as protected; }
We can use one trait from another using "use"
we can also define abstract,static, data members, method


Question: Tell me about Anonymous classes?
We can create a class without specifing the class-name. Following are example
$util->setLogger(new class {
    public function log($msg)
    {
        echo $msg;
    }
});


Question: What is Overloading in PHP?
Overloading in PHP provides means to dynamically create properties and methods.
These dynamic entities are processed via magic methods one can establish in a class for various action types.
example of magic functions __get(), __set(), __isset(), __unset(), __call(),__callStatic() etc


Wednesday, 24 October 2018

How to add formated text on video using php-ffmpeg?

How to add formated text on video using php-ffmpeg?

Question: What is drawtext on video?
Adding the single line text/multiple line text over the video.



Question: Can we change the font-size of text?
Yes, we can change the color, size, font family etc of text in videos.



Question: How to add text on videos?
ffmpeg -i myvideo.mp4 -vf drawtext="fontfile=OpenSans-Bold.ttf: text=this is text on videos: fontcolor=white: fontsize=120: box=1: boxcolor=black@0.5: boxborderw=5: x=(w-text_w)/2: y=(h-text_h)/2" -codec:a copy output_video.mp4

Note: OpenSans-Bold.ttf file must available (with parallel to video i.e myvideo.mp4)



Question: How to multiple line text on videos?
ffmpeg -i myvideo.mp4 -vf "[in]drawtext=fontfile=OpenSans-Bold.ttf: text=Arun kumar: fontcolor=white: fontsize=20: box=1: boxcolor=black@0.5: boxborderw=5: x=100: y=100 drawtext=fontfile=OpenSans-Bold.ttf: text='Kuldeep ': fontcolor=white: fontsize=20: box=1: boxcolor=black@0.5: boxborderw=5: x=100: y=400[output]" -codec:a copy output_video.mp4

Note: OpenSans-Bold.ttf file must available (with parallel to video i.e myvideo.mp4)




Question: How to add text in video with PHP?
  1. You must have installed PHP-FFMPEG
    php composer.phar require php-ffmpeg/php-ffmpeg
    If not, you can check https://www.web-technology-experts-notes.in/2017/10/how-to-install-ffmpeg-in-wamp-server-in-windows7.html
  2. To achieve this, you need to use the ffmpeg filters.
  3. require_once 'ffmpeglib/vendor/autoload.php';
    $ffmpeg = FFMpeg\FFMpeg::create();
    $format = new FFMpeg\Format\Video\X264();
     $format->setAudioCodec("aac");  
    $videoFile='myvideo.mp4';
    $captionStaticFilePath='';//directory path
    $captionStaticFilePath=$_SERVER['DOCUMENT_ROOT'].'/video/';
    
    /////////////// Debug ////////////////////////////
    /*$ffmpeg->getFFMpegDriver()->listen(new \Alchemy\BinaryDriver\Listeners\DebugListener());
    $ffmpeg->getFFMpegDriver()->on('debug', function ($message) {
        echo $message;
    });*/
    /////////////// Debug ////////////////////////////                
    
    /* Filter the text correctly*/ 
    $captionJSON=json_decode('["text=This is caption text: fontfile=OpenSans-Regular.ttf: x=384: y=10: fontcolor=#ffffff: fontsize=24px","text=This is clip 2 - Samik das: fontfile=OpenSans-Bold.ttf: x=404.08331298828125: y=34.91668701171875: fontcolor=#ffffff: fontsize=24px: fonttype=bold"]');
    $captionArray=array();
    if(!empty($captionJSON) && !empty($captionJSON)){
        foreach($captionJSON as $caption){
            //String to array
            $caption=str_replace(':', '&', $caption);
            parse_str($caption, $output);
            //pr($output);die;
    
            unset($output['fonttype']);
            $output['fontsize']=str_replace('px','',$output['fontsize']);
            $output['fontfile']=$captionStaticFilePath.$output['fontfile'];
    
            $output['x'] = (int)$output['x'];
            $output['y'] = (int)$output['y'];
    
            //Array to string
            $outputStr='';
            $counter=0;
            foreach($output as $i=>$v){
                if($counter){
                    $outputStr.= ': ';
                }
                $outputStr.= $i.'='.$v;
                $counter++;
            }
            //Update to array                            
            $captionArray[]=$outputStr;
        }
    }
    /* Filter the text correctly*/ 
    
    
    try{
        $video = $ffmpeg->open($captionStaticFilePath.$videoFile);
        $command='';
        if(!empty($captionArray)){
            $command='[in]';
            foreach($captionArray as $index=>$captionComand){
                if($index>0){
                    $command= $command.',';
                }
                $command= $command.'drawtext='.$captionComand;
            }
            $command.='[out]';
    
    
        }
    
        //nOW execute the command
        $video->filters()->custom($command);
        $captionFile='caption_'.$videoFile;
        //Save the video with caption
        $video->save($format, $captionStaticFilePath.$captionFile);
        die('done');
    }catch(Exception $e){
        echo $e->getMessage();die;
    }



Question: How to add debugging in php-ffmpeg?
Just add below code after the initialize the ffmpeg object.

$ffmpeg->getFFMpegDriver()->listen(new \Alchemy\BinaryDriver\Listeners\DebugListener());
$ffmpeg->getFFMpegDriver()->on('debug', function ($message) {
    echo $message;
});



Question: Share Few useful urls for drawtext?
https://www.ffmpeg.org/ffmpeg-all.html#fade
https://ffmpeg.org/ffmpeg-filters.html


Tuesday, 20 February 2018

php FFMpeg extract images from videos

php FFMpeg extract images from videos in every 10 or nth seconds

Question: From where download the PHP FFMpeg library?
Install the php FFMpeg with composer.
composer require php-ffmpeg/php-ffmpeg



Question: Check php FFMpeg installed properly or not?
require 'vendor/autoload.php';
$ffmpeg = FFMpeg\FFMpeg::create();
print_r($ffmpeg);

If it will print the object means FFMpeg is proper configure.


Question: How to extract image from video?
require_once 'ffmpeglib/vendor/autoload.php'; 
$folderPath='convert/';

#Create the required Object
$ffmpeg = FFMpeg\FFMpeg::create();
$video = $ffmpeg->open($folderPath.'video.mp4');

#extra the image at 10 seconds
$video
    ->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(10))
    ->save('frame_10.jpg');


#extra the image at 20 seconds
$video
    ->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(20))
    ->save('frame_20.jpg');


#extra the image at 30 seconds
$video
    ->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(30))
    ->save('frame_30.jpg');



Question: How to extract image in every 10 seconds from video?
    require_once 'ffmpeglib/vendor/autoload.php'; 
    $folderPath='convert/';

    ##Create the required Object
    $ffmpeg = FFMpeg\FFMpeg::create();
    $video = $ffmpeg->open($folderPath.'video.mp4');

    for($i=10; $i<=300; $i+=10){
        $video
            ->frame(FFMpeg\Coordinate\TimeCode::fromSeconds($i))
            ->save($folderPath.'frame_'.$i.'.jpg');            

    }



Question: How to set the binary file path in ffpeg?
$ffmpeg = FFMpeg\FFMpeg::create(array(
    'ffmpeg.binaries'  => '/opt/local/ffmpeg/bin/ffmpeg',
    'ffprobe.binaries' => '/opt/local/ffmpeg/bin/ffprobe',
    'timeout'          => 3600, // The timeout for the underlying process
    'ffmpeg.threads'   => 12,   // The number of threads that FFMpeg should use
));



Question: How to get the codec_name information of video?
$ffprobe    = \FFMpeg\FFProbe::create();
$codeAc=$ffprobe->streams($uploadingFileName[0])
        ->videos()
        ->first()
        ->get('codec_name');



Question: How to get the duration of video?
$ffprobe    = \FFMpeg\FFProbe::create();
$codeAc=$ffprobe->streams($uploadingFileName[0])->get('duration');        



Question: How to combine multiple video?
$staticFilePath='/videopath';
$video = $ffmpeg->open( $staticFilePath.'0.mp4');
        $video
        ->concat(array($staticFilePath.'0.mp4',$staticFilePath.'1.mp4',$staticFilePath.'2.mp4',$staticFilePath.'3.mp4'))    
        ->saveFromSameCodecs($staticFilePath.'final.mp4', TRUE);
//final.mp4 will be combined file



Question: How to combine multiple video from h265 to h264?
$staticFilePath='/videopath';
$video = $ffmpeg->open( $staticFilePath.'0.mp4');
$video
        ->concat($array($staticFilePath.'0.mp4',$staticFilePath.'1.mp4',$staticFilePath.'2.mp4',$staticFilePath.'3.mp4'))
        ->saveFromDifferentCodecs(new FFMpeg\Format\Video\X264,$staticFilePath.'final_264.mp4', true);  



Question: How to check file is video file OR Audio file?
$videoDataAvailable=$ffprobe->streams($videoFile)->videos();
if(count($videoDataAvailable)==0){
    echo 'AUDIO FILE';
}else{
    echo 'Video File FILE';
} 




Question: How to convert Mp4 to wav using php-ffmpeg?
 
require_once 'ffmpeglib/vendor/autoload.php'; 
$ffmpeg = FFMpeg\FFMpeg::create();
$format = new FFMpeg\Format\Audio\Wav();        
$videoFolderPath='folder';


$audioObj = $ffmpeg->open($videoFolderPath.'/myfile.mp4');    
$audioObj->save($format, $videoFolderPath.'/myfile.wav'); 





Question: How to convert Mp4 to mp3 using php-ffmpeg?
 
require_once 'ffmpeglib/vendor/autoload.php'; 
$ffmpeg = FFMpeg\FFMpeg::create();
$videoFolderPath='folder';

$mp3Format = new FFMpeg\Format\Audio\Mp3(); 
$audioObj = $ffmpeg->open($videoFolderPath.'/myfile.mp4');    
$audioObj->save($mp3Format, $videoFolderPath.'/myfile.mp3'); 






Tuesday, 6 February 2018

php is not recognized as an internal or external command wamp

Question: How to "Fix php is not recognized as an internal or external command wamp"?

Step 1
Click on Start Button => Right Click on Computer => Click on Properties

Window 7 go to the properties


Step 2
An Popup will appear => Click on "Advance System Setting" (Left Panel)


Step 3
Click on "Environment Variable"

Window 7 go to the System properties


Step 3
A popup will appear, Select PATH and click on "EDIT"
Window 7 Edit Environment Varaible



Step 4 Add you php.exe path at the end of input box like below:
;D:\wamp\bin\php\php5.5.12\

Window 7 Set php.exe path in environment variable


Friday, 6 October 2017

How to install ffmpeg in wamp server in Windows7

How to install ffmpeg in wamp server in Windows

Question: What are Simple steps to install ffmpeg in wamp server in Windows?
  1. Download FFmpeg for Windows
    https://ffmpeg.zeranoe.com/builds/
  2. Extract the downloaded Zip file.
  3. Copy bin/ffmpeg.exe, bin/ffplay.exe and bin/ffprobe.exe from downloaded and paste in C:\Windows\System32
  4. Create a folder with name ffmpegtest in path d:/wamp/www (Drive can be different as per wamp installation)
  5. Login to Command prompt and go to d:/wamp/www/ffmpegtest using cd command
  6. Execute following command (To download composer)
    php -r "readfile('https://getcomposer.org/installer');" | php
    

    It will download the composer.phar
  7. Execute following command to download PHP-FFMPEG library.
    php composer.phar require php-ffmpeg/php-ffmpeg
    
  8. Test the FFMPEG with php
    include "vendor/autoload.php";
    $ffmpeg = FFMpeg\FFMpeg::create();
    print_r($ffmpeg);
    
    When it print the object, means FFMPEG setup successfully.


Question: What can we do with ffmpeg?
-Cut the video
-Combine two or more videos into one
-Extract the one video portion from main video
-Resize the video
-Extract the audio from video
-Combine photo+audio into video
-Change the sample rate
-Watermarking on vi



Question: What is Bitrate?
Bitrate describes the rate at which bits are transferred in ffmpeg. Bitrate is commonly measured in bits per second (bps),kilobits per second (Kbps), or megabits per second (Mbps).


Question: What is Frame Rate?
the frame rate is the number of frames or images that are projected or displayed per second.


Question: What is demux?
A demux(er) is a module responsible for extracting the contents of a given file/stream format, for instance AVI, OGG, MPEG2, WAV, etc.


Question: How to convert .wav to .mp3?
include "vendor/autoload.php";
$ffmpeg = FFMpeg\FFMpeg::create();
$video = $ffmpeg->open( 'audiofile.wav' );
$audio_format = new FFMpeg\Format\Audio\Mp3();
// Extract the audio into a new file as mp3 and save in folder
$video->save($audio_format, 'audiofile.mp3');



Question: How to transcode a wav to flac?
include "vendor/autoload.php";
$ffmpeg = FFMpeg\FFMpeg::create();
$video = $ffmpeg->open( 'audiofile.wav' );
$audio_format = new FFMpeg\Format\Audio\Mp3();
$video->save($audio_format, 'audiofile.mp3');


Tuesday, 3 October 2017

How to create built in web server in PHP?

How to create built in web server in PHP

Question: In which PHP Version Built-in web server come?
PHP 5.4


Question: Can we run php without apache?
Yes, We can run the php independent.


Question: Can we test our application with Built-in web server feature?
Yes, We can.


Question: Can we test our application with Built-in web server feature?
Yes, We can use this feature to test our module.


Question: Can we go LIVE with Built-in web server ?
Not, Its recommended We should not go LIVE with this Built-In Web Server.


Question: How to check If built-in Web server is available in your PHP Build?
Way 1
print the phpinfo() in php. and Search for Built-in HTTP server , If found means It is available.

Way 2
in php command line, execute following command

php -h

Search -S (Run with built-in Web server), If found means It is available.


Question: How to run PHP Script with built-in Web Server?
Go to file Location and execute following command from command line.
php -S 0.0.0.0:8080 myfile.php



Question: What is use of -S?
It is used to specify the Ip Address with port with which bind.


Question: What is use of -t?

It is used to specify the target folder.


Question: How to detect the request by built-in Web Server?
if(php_sapi_name()=='cli-server'){
    echo "this is request by built-in Web Server";
}



Question: Give full working example of built-in Web Server?
  1. Create a file hello.php
  2. Login to command line
  3. Go to that particular folder in command line
  4. Execute following command.
    php -S 0.0.0.0:8080 hello.php
    



Tuesday, 19 September 2017

Standard PHP Library (SPL) with Basic details

Standard PHP Library (SPL) with Basic details

Question: What is full form of SPL?
Standard PHP Library.


Question: What is SPL?
It is collection of interfaces and Classes.


Question: Do we need to download library for SPL?
No, We need not to download external library.


Question: What does provide SPL?
SPL provides following Iterators, Interface and Functions.
  1. Set of standard Data Structure.
  2. a Iterators to traverse over objects
  3. Set of Interfaces
  4. Set of standard Exceptions
  5. SPL Functions
  6. SPL File Handling



Question: What classes are available in SPL data structure?
Doubly Linked Lists: It is a list of nodes linked in both directions to each other. Iterator operations, access to both end node, addition or removal of nodes.
http://php.net/manual/en/class.spldoublylinkedlist.php

Heaps: Heaps are tree-like structures that follow the General heap, each node is greater than or equal to its children.
http://php.net/manual/en/class.splheap.php

Arrays: Arrays are structures that store the data in a continuous way, accessible via indexes.
http://php.net/manual/en/class.splfixedarray.php

Map: A map is a datastructure holding key-value pairs. PHP arrays can be seen as maps from integers/strings to values.
http://php.net/manual/en/class.splobjectstorage.php



Question: What Iterators classes are available in SPL?
  1. AppendIterator
  2. ArrayIterator
  3. CachingIterator
  4. CallbackFilterIterator
  5. DirectoryIterator
  6. EmptyIterator
  7. FilesystemIterator
  8. FilterIterator
  9. GlobIterator
  10. InfiniteIterator
  11. IteratorIterator
  12. LimitIterator
  13. MultipleIterator
  14. NoRewindIterator
  15. ParentIterator
  16. RecursiveArrayIterator
  17. RecursiveCachingIterator
  18. RecursiveCallbackFilterIterator
  19. RecursiveDirectoryIterator
  20. RecursiveFilterIterator
  21. RecursiveIteratorIterator
  22. RecursiveRegexIterator
  23. RecursiveTreeIterator
  24. RegexIterator



Question: What Interfaces are available in SPL?
  1. Countable
  2. OuterIterator
  3. RecursiveIterator
  4. SeekableIterator
  5. SplObserver
  6. SplSubject



Question: What Exception classes are available in SPL?
  1. BadFunctionCallException
  2. BadMethodCallException
  3. DomainException
  4. InvalidArgumentException
  5. LengthException
  6. LogicException
  7. OutOfBoundsException
  8. OutOfRangeException
  9. OverflowException
  10. RangeException
  11. RuntimeException
  12. UnderflowException
  13. UnexpectedValueException



Question: What are the advantage of iterators?
  1. Laziness: the data is only fetched when you actually need it.
  2. Reduced memory usage: SPL iterators encapsulate the list and expose visibility to one element at a time making them far more efficient.



Question: Give an example of Iterating Arrayst?
  
$arr = array("One", "Two", "three", "Four", "Five", "Six");
$iter = new ArrayIterator($arr);
foreach ($iter as $key => $value) {
    echo $key . ":  " . $value ;
}

Output
  
0: One
1: Two
2: three
3: Four
4: Five
5: Six



Question: Give an example of Iterating Directory Listings?
  
$dir = new DirectoryIterator("/");
foreach ($dir as $item) {
    echo $item . "
";
}

Output
  
$RECYCLE.BIN
Backup
banner
blog backup
data
data.log.txt
desktop files
doremon
mm
mongodb



Question: Give an example of Iterating Directory Recursively?
  
$iter = new RecursiveDirectoryIterator("/");
foreach (new RecursiveIteratorIterator($iter) as $item) {
    echo $item . "
";
}



Wednesday, 28 December 2016

How to install redis on wamp server?

How to install redis on wamp server?

Question: What is Redis?
it is an open source advanced key-value database storage system like NoSQL.


Question: Why Redis is used?
Redis is used for caching to speed up application.


Question: How redis helpful in Optimization?
Redis operations can be executed on the server side and reduce the client's workload.


Question: What type of data can be stored in Redis server?
Redis store complex data structures like strings, hashes, lists, sets, sorted sets, bitmaps and hyperlogs as its key values.


Question: Why redis is fast?
Redis is inherently fast as it stores data in memory.


Question: How to install redis in wampserver?
  1. Download the redis
       A) Download Redis setup For 32 Bit System and Install
       B) Download Redis Setup for 64 Bit system and follow below steps.    
    1. Extract the zip file
    2. Place the unzip file in c:\redis
    3. Run redis-server.exe from c:\redis
    4. then Run redis-cli.exe from c:\redis
  2. Check out your php version and know whether thread safety is enabled or not(by using phpinfo()).
  3. Now we need to download the php_redis.dll. Download the php_redis.dll from PECL.
    Download as per PHP Version and thread based.
  4. Extract the zip file.
  5. Copy the php_redis.dll and paste to following folder in Wamp Server.
    wamp\bin\php\php5.x.xx\ext\
  6. Add the following line in your php.ini
    extension=php_redis.dll
  7. Re-start the wamp Server.
  8. Do phpinfo() and search redis. It will start displaying which means its Redis is installed
  9. Learn and Work with redis.



Question: How to check redis is installed Or Not?
try {
    $redis = new Redis();
    $redis->connect('localhost', 6379);
    $redis->set('name', 'Redis is Installed');
    echo $glueStatus = $redis->get('name');
    
} catch (Exception $ex) {
    echo $ex->getMessage();
}



Friday, 19 February 2016

How to detect Mobile Device in PHP? - Simplest way

How to detect Mobile Device in PHP - Simplest way

Question: What does this script do?
It simply detect the request and tells request comes from mobile browser (Mobile devices) OR Web Devices (Desktop, Laptop, Ipad).


Question: What are Server Requirements for this script?
PHP Must be installed.


Question: Why we do need this script?
Sometime we need to give the different response on the behalf of devices.
For Example:
We give 20 records for web browser.
We give 10 records for Mobile browser.


Question: Where we do need this script? Give Example?
We need this script where we change the response on the behalf of devices browser.
For Example:
  1. Different number of record in web and in mobile.
  2. In Responsive website, we hide the extra information which is not displayed in mobile devices. In this case we should also not fetch these details from the server.
  3. Display the different sizes of images on the behalf of device.
  4. If website is not compatiable to mobile devices, Give a good message to users.



Question: How to detect the mobile devices?
$useragent=$_SERVER['HTTP_USER_AGENT'];
$isMobile=0;
if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4))){
    $isMobile=1;
}

if($isMobile){
    /** Script For Mobile **/

    /** Script For Mobile **/
}else{
    /** Script For Web**/

    /** Script For Web**/
}



Saturday, 30 January 2016

What is Zend Engine in PHP

Zend Engine is used internally by PHP as a complier and runtime engine. PHP Scripts are loaded into memory and compiled into Zend opcodes. These opcodes are executed and the HTML generated is sent to the client.

What is Zend Engine



The Zend Engine is an open source scripting engine, commonly known for the important role it plays in the web automation language PHP. It was originally developed by Andi Gutmans and Zeev Suraski while they were students at the Technion - Israel Institute of Technology.

Monday, 22 June 2015

How to Upgrade PHP 5.3 to PHP 5.4 in WAMP Server in window 7


Adding addons  PHP 5.4 in WAMP Server is quite easy, just you need to follow the following (Works for me).

Please take the backup of code and database before Start.

Please make the backup of php.ini files. When we add addons in wamp server then, we can access the new PHP (php5.4) and old php (php5.x). Both are easily accessible.

Just to need to change the PHP Version like Below:

How to Upgrade PHP 5.3 to PHP 5.4 in WAMP Server in window 7

Let Suppose following:
1) Addin 5.4.42
2) Wamp Server drive is E:


Follow the following steps to upgrade your PHP version.

  1. Download PHP5.4 From http://windows.php.net/download/#php-5.4 (Download Thread Safe)
  2. Go to PHP Folder Location (i.e E:\wamp\bin\php)
  3. Create a new folder with name php5.4.42.
  4. Extract the download files and save in E:\wamp\bin\php\php5.4.42.
  5. Copy the following files from your old PHP directory to your new PHP directory ().
        php.ini
        phpForApache.ini
        wampserver.conf
    
  6. Open new copied php.ini file.
  7. Update the extension_dir path in file.
  8. Open new phpForApache.ini file.
  9. Update the extension_dir path in file.
  10. Reboot your system.
  11. Start wamp Server
  12. Go to wampserver =>PHP=>Version=>PHP 5.4.42
  13. Now running PHP5.4.42
    Note: you might need to Re-enable the PHP extension like CURL, Openssl etc

Monday, 25 May 2015

How can I upload file asynchronously in php?

How can I upload file asynchronously in php?

Following are simple 4 Steps to upload file asynchronously  in PHP.

Step #1
Add jQuery javascript file in your page - Need for Ajax call.


<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>


Step #2
Add Following Html, where you want to show the button to upload the file.






Step #3:
Add following javascript code which is responsible for uploading the file.
URL: /folder/upload-file.php
Description: Here you need to write the send the request to server.
$( document ).ready(function() {
    $(':button').click(function(){
        var formData = new FormData($('form')[0]);
        $.ajax({
            url: '/folder/upload-file.php', //Location of upload file 
            type: 'POST',
            xhr: function() {  // Custom XMLHttpRequest
                var myXhr = $.ajaxSettings.xhr();
                return myXhr;
            },

            beforeSend: function(data){},
            success: function(data){},
            error: function(data){},        
            data: formData,        
            cache: false,
            contentType: false,
            processData: false
        });
    });
});


Step #4
Add Following code in "/folder/upload-file.php" which will upload the file in Server.
$targetFile="/path/to/upload/file";//Location of srver
if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) {
        echo "success";
    } else {
        echo "failure";
    }





Wednesday, 25 February 2015

How to store array in Cookie and retrieve array from cookie

How to store array in Cookie and retrieve array from cookie

How to store array in Cookie
We need to json_encode the array then save the data with setcookie function.
$arrayData=array(
    'web technology experts',
    'web technology experts Notes',
    'web technology experts Notes  php technology'    
);
setcookie('cookieData', json_encode($arrayData));


How to Retrieve array in Cookie
As we have encoded the array above, So we need to json_decode the array before use.
$arrayData = json_decode($_COOKIE['cookieData']);


How to set time in cookies
$arrayData=array(
    'web technology experts',
    'web technology experts Notes',
    'web technology experts Notes  php technology'    
);
setcookie('cookieData', json_encode($arrayData), time()+3600);// set time for 1 hour [1 hour=3600 seconds]