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

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');