1

I have to execute a php script (test.php) in the background. I tried this but it's not working:

<?
$cmd = "php /home/megad404/www/prove/test.php &> /dev/null &";
exec('/bin/bash -c "'.$cmd.'"',$output,$return);
if($return===0)
{
    echo 'Successful';
} 
else
{
    echo 'Unsuccessful';
}
?>

It returns "Successful" but it doesn't execute test.php

test.php:

<?
file_put_contents(date("s"),"");
sleep(5);
file_put_contents(date("s"),"");
sleep(5);
file_put_contents(date("s"),"");
?>

test.php writes a file every 5 second and it works fine, except if I try to execute it in the background with the first script.

Could it be a server issue? Is there another way to run a script in the background?

2 Answers 2

2

Use shell_exec and nohup

shell_exec("nohup php /home/megad404/www/prove/test.php > /dev/null & echo $!");
Sign up to request clarification or add additional context in comments.

3 Comments

Open console and write command php /home/megad404/www/prove/test.php. See result or error exception. I hope you use *nix OS and you had set the environment variable php
How do I open the console?
Sorry for my ignorance, but, how I know that? I think that my problem is related to permission. I just set all to 777 but now i can't connect to the server to see if it works
0

Use shell_exec and give absolute path for php:

$output = shell_exec("nohup /usr/bin/php7.0 -f /home/megad404/www/prove/test.php &> /dev/null &");

Just confirm the absolute path for php in your server. For instance, I'm using php 7.0 and the absolute path is /usr/bin/php7.0

Also, give executable permission to the php file you are running from your code.

chmod +x /home/megad404/www/prove/test.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.