PHP - How to get Shell errors echoed out to screen

2019-03-22 22:07发布

I am in the process of using shell_exec() for the first time. I am trying to convert some video files on my server using the ffmpeg shell script.

When I the below code in the browser, it returns NULL:

var_dump(shell_exec("ffmpeg -i /var/www/html/sitedomain/httpdocs/tmp/ebev1177.mp4"));

However when I run the equivalent code in my terminal:

> ffmpeg -i /var/www/html/sitedomain/httpdocs/tmp/ebev1177.mp4

I get back a whole load of useful information which ends in an error "At least one output file must be specified"

Why is this info not being passed back to my PHP script so I can echo it out?

1条回答
你好瞎i
2楼-- · 2019-03-22 22:45

The error data is output from the target program's STDERR stream. You can get access to the error data through the normal returned string from shell_exec() by appending 2>&1 to the command, which will redirect STDERR to STDOUT, the stream that you are currently seeing:

var_dump(shell_exec("ffmpeg -i /var/www/html/sitedomain/httpdocs/tmp/ebev1177.mp4 2>&1"));

You may also want to take a look at proc_open() which will allow you to get access to STDIN, STDOUT and STDERR as three individual streams, which can afford much finer grained control over the target program and exactly how you handle the input and output to it, including redirecting any and all of them directly to a log file if so desired. Be aware though that this is a much more complex mechanism with many pitfalls and tripping hazards.

More information on the standard streams can be found here.

查看更多
登录 后发表回答