Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is fopen+fwrite quicker than shell_exec?

Tags:

php

unix

I want to write text to a file (like log-entries/data/whatever), where the server is on a unix system

is it quicker to use:

$handle = fopen("somefile"); 
fwrite($handle,"sometext");

or this:

shell_exec("echo 'sometext' > somefile");

is there any other drawbacks to using the shell_exec method? speed? security? preformance?

like image 939
Artog Avatar asked Oct 28 '25 19:10

Artog


2 Answers

For something as simple as your example, neither will be noticeably faster and security is no issue. If your shell arguments are to be PHP variables, then be sure to use escapeshellcmd() on them (docs here).

However, in procedural code, I think I would prefer the fopen() fwrite() method, just because it's easier to check for errors and the validity of your file handle before writing to it, and then check the return of fwrite() to make sure your write operation succeeded. The shell command would only return a single error code, so it would be more difficult to debug where the error occurred.

like image 61
Michael Berkowski Avatar answered Oct 30 '25 12:10

Michael Berkowski


Way faster. Just consider that shell_exec is forking, then loading a shell binary, running it, then the shell interprets the command, then the shell forks again to run the command ...

like image 31
Paul Beckingham Avatar answered Oct 30 '25 12:10

Paul Beckingham