Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirection in PHP exec call creates empty file

It's quite simple, and I'm out of ideas. I'm sure there is a quick workaround.

exec('echo 123 &> /var/log/123.log');

I'm sure it's not about the permissions, because the file 123.log is created, but it's just- empty. I've also tried shell_exec, but it doesn't create the file at all. Also tried all variants of redirection, i.e. 1> 2> >.

Using PHP to capture the output is not the option, as the output in production is huge, and I don't want to run into memory issues.

Any ideas appreciated.

Btw, I'm using Ubuntu 12.04 LAMP.

like image 290
tishma Avatar asked Apr 18 '13 08:04

tishma


People also ask

What is exec() 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. Syntax: string exec( $command, $output, $return_var )

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.


1 Answers

Debian and Debian based Linux distributions like Ubuntu are using dash and not bash as /bin/sh by now.

&> is a bash extension, the dash does not know about.

The correct posix-compatible way to write cmd &> file is cmd > file 2>&1

cmd > file 2>&1 works in all posix-compatible shells: dash, bash, ksh, zsh, ash ...

So you need to change your code to:

exec('echo 123 > /var/log/123.log 2>&1');
like image 87
Samuel Kirschner Avatar answered Sep 24 '22 11:09

Samuel Kirschner