Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing an exec() or system() in PHP and do not wait for output

I want to trigger a shell command in eider exec() or system() from PHP script but it is a task that take a while to complete, is there a way to trigger it and continue running the PHP page load without delay?

Edit: I am on CentOS 6, PHP 5.3

like image 738
adrianTNT Avatar asked Jan 18 '12 12:01

adrianTNT


People also ask

Does PHP wait for exec to finish?

PHP exec will wait until the execution of the called program is finished, before processing the next line, unless you use & at the end of the string to run the program in background.

What does exec do in PHP?

The exec() function is an inbuilt function in PHP which is used to execute an external program and returns the last line of the output. It also returns NULL if no command run properly.

How do you check if exec is enabled in PHP?

php phpinfo(); ?> You can search for disable_functions and if exec is listed it means it is disabled. To enable it just remove the exec from the line and then you need to restart Apache and you will be good to go. If exec is not listed in the disable_functions line it means that it is enabled.

What is exec command?

The exec command is a powerful tool for manipulating file-descriptors (FD), creating output and error logging within scripts with a minimal change. In Linux, by default, file descriptor 0 is stdin (the standard input), 1 is stdout (the standard output), and 2 is stderr (the standard error).


2 Answers

Depends on the OS you are using.

For linux:

pclose(popen("php somefile.php &","r"));

notice the amperstand at the end (very important).

For windows:

pclose(popen("start php.exe somefile.php","r"));

here the start keyword is important.

Hope this helps.

like image 169
Eduard Luca Avatar answered Nov 03 '22 21:11

Eduard Luca


This doesn't answer your question directly, but you should consider doing your video conversion work in a background process with either a cron job or using a queue such as Beanstalkd.

This way you can stack up your ffmpeg work in the background without blocking your webserver.

I've had a lot of success with both methods (cron / queue) in the past.

Some other posts about background processes:

php execute a background process

Run a ffmpeg process in the background

Using ffmpeg, PHP and beanstalk

Some tools you might find useful:

http://kevin.vanzonneveld.net/techblog/article/create_daemons_in_php/

PEAR System_Daemon

Pheanstalk, a Beanstalkd library for PHP

like image 39
Darren Newton Avatar answered Nov 03 '22 22:11

Darren Newton