escapeshellarg

(PHP 4 >= 4.0.3, PHP 5)

escapeshellarg -- Escape a string to be used as a shell argument

Описание

string escapeshellarg ( string arg )

escapeshellarg() adds single quotes around a string and quotes/escapes any existing single quotes allowing you to pass a string directly to a shell function and having it be treated as a single safe argument. This function should be used to escape individual arguments to shell functions coming from user input. The shell functions include exec(), system() and the backtick operator. A standard use would be:

<?php
system
('ls '.escapeshellarg($dir));
?>

See also escapeshellcmd(), exec(), popen(), system(), and the backtick operator.



add a note add a note User Contributed Notes
escapeshellarg
antony lesuisse
22-Apr-2004 11:30
NOTE: If you are using PHP >= 4.2 you should use the pcntl_* (Process
Control) functions instead of this hack.

PHP, before version 4.2, didn't provide any execl(3)-like or
execv(3)-like methods to invoke external programs, thus everything
goes trough /bin/sh -c and we are forced to quote arguments.

To make it worse escapeshellarg() behaves badly (IMHO) with an empty
string:
<?php
  
echo "mime-construct --to ".escapeshellarg($to)." --cc a@a.com";
?>

The following function is a wrapper to system(), and it can be adapted
to popen(),exec(),shell_exec():

<?php
  
# system with perl? semantics
  
function lib_system() {
      
$arg=func_get_args();
       if(
is_array($arg[0]))
          
$arg=$arg[0];
      
$cmd=array_shift($arg);
       foreach(
$arg as $i) {
          
$cmd.=" ''".escapeshellarg($i);;
       }
      
system($cmd);
   }
  
# example1
  
lib_system("mime-construct","--output", "--to",$a,"--string",$b);
  
# example2
  
lib_system(array("mime-construct","--output", "--to",$a,"--string",$b));
?>
vosechu at roman-fleuve dot com
25-Mar-2004 08:05
If escapeshellarg() returned something on a null input it would probably break more programs than it helps. Even if it's two "'s or two ''s, this function wouldn't work the way it's supposed to (that is, returning nothing).

However, most people do not put "" into their commands but I can see where it might be useful at the same time.
Perhaps an option in the command that would return the type of null we want. I might want the null character to be returned, someone else might want '', and someone else might want nothing at all.
php at floris dot nu
26-Mar-2003 10:27
i also thought the output was gonna be between 's because that's the way windows handles arguments with spaces in them. i think we have a unix <> windows misunderstanding here...
jbriggs at esoft dot com
04-Jan-2002 03:57
This function returns nothing when called with an empty argument.

escapeshellarg("b'lah") returns 'b'\''lah'
but escapeshellarg("") returns ""