php shell exec wget to run not in background

2019-05-05 07:52发布

问题:

I want to run wget as follows

shell_exec('wget "'http://somedomain.com/somefile.mp4'"');
sleep(20);
continue my code...

What I want is to let PHP wait for the shell_exec wget file download to finish before continuing on with the rest of the code. I don't want to wait a set number of seconds.

How do I do this, because as I run shell_exec wget, the file will start downloading and run in background and PHP will continue.

回答1:

Does your URL contain the & character? If so, your wget might be going into the background and shell_exec() might be returning right away.

For example, if $url is "http://www.example.com/?foo=1&bar=2", you would need to make sure that it is single-quoted when passed on a command line:

shell_exec("wget '$url'");

Otherwise the shell would misinterpret the &.

Escaping command line parameters is a good idea in general. The most comprehensive way to do this is with escapeshellarg():

shell_exec("wget ".escapeshellarg($url));


回答2:

shell_exec does wait for the command to finish - so you don't need the sleep command at all:

<?php
shell_exec("sleep 10");
?>

# time php c.php
   10.14s real     0.05s user     0.07s system

I think your problem is likely the quotes on this line:

shell_exec('wget "'http://somedomain.com/somefile.mp4'"');

it should be

shell_exec("wget 'http://somedomain.com/somefile.mp4'");