Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppressing output from exec() calls in PHP

Tags:

php

I have a number of command line scripts in PHP that use exec() to perform tasks such as restarting services, loading MySQL timezone files, etc. While exec() itself does not output anything to the screen, some of the commands I am running are forcing output that I can't seem to suppress (even with ob_start()/ob_end_clean()). For example, the following would load timezone files into MySQL. We run this periodically to make sure MySQLs timezone data is up to date:

 $command = 'mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql mysql';  exec($command, $output, $result); 

In this example, I would expect all output from the command to be written into $output, but I still get the following output forced to the screen:

Warning: Unable to load '/usr/share/zoneinfo/Asia/Riyadh87' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/Asia/Riyadh88' as time zone. Skipping it. Warning: Unable to load '/usr/share/zoneinfo/Asia/Riyadh89' as time zone. Skipping it. ... 

Is there any way to suppress this output? Redirecting to /dev/null is not ideal as that would cause PHP to continue processing without waiting for the command to complete.

Thanks in advance,
~ JamesArmes

like image 567
JamesArmes Avatar asked Oct 22 '09 12:10

JamesArmes


People also ask

What does Exec return 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.

What is the difference between exec and Shell_exec?

1. The shell_exec() function is an inbuilt function in PHP that is used to execute the commands via shell and return the complete output as a string. The exec() function is an inbuilt function in PHP that is used to execute an external program and returns the last line of the output.

Does PHP exec wait until finished?

If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.


Video Answer


1 Answers

Redirecting stderr alone should not influence where processing takes place, just make sure not to add an &. It should only run in the background if you redirect the output and make it run in the background.

Edit:

Cracked open cygwin, you need to redirect stderr for the first command, give this a try:

$command = 'mysql_tzinfo_to_sql /usr/share/zoneinfo 2> /dev/null | mysql mysql'; exec($command, $output, $result); 
like image 124
Yannick Motton Avatar answered Oct 07 '22 17:10

Yannick Motton