PHP Doku:: Maskiert eine Zeichenkette (String), um sie als Shell-Argument benutzen zu können - function.escapeshellarg.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzErweiterungen zur ProzesskontrolleAusführung von SystemprogrammenFunktionen zur Programmausführungescapeshellarg

Ein Service von Reinhard Neidl - Webprogrammierung.

Funktionen zur Programmausführung

<<Funktionen zur Programmausführung

escapeshellcmd>>

escapeshellarg

(PHP 4 >= 4.0.3, PHP 5)

escapeshellargMaskiert eine Zeichenkette (String), um sie als Shell-Argument benutzen zu können

Beschreibung

string escapeshellarg ( string $arg )

escapeshellarg() fügt einfache Anführungszeichen um eine Zeichenkette herum ein und maskiert alle existierenden einfachen Anführungszeichen innerhalb der Zeichenkette und ermöglicht es so die Zeichenkette direkt als Argument einer Shell-Funktion zu verwenden so das es als ein einziges Argument interpretiert wird. Die Funktion sollte benutzt werden um aus Benutzereingaben stammende Argumente an Shell-Funktionen weiterzugeben. Zu den Shell-Funktionen zählen unter anderem exec(), system() und der Backtick Operator.

Parameter-Liste

arg

Die zu maskierende Zeichenkette

Rückgabewerte

Die maskierte Zeichenkette

Beispiele

Beispiel #1 escapeshellarg() Beispiel

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

Siehe auch


16 BenutzerBeiträge:
- Beiträge aktualisieren...
phil at philfreo dot com
4.08.2010 0:56
When escapeshellarg() was stripping my non-ASCII characters from a UTF-8 string, adding the following fixed the problem:

<?php
setlocale
(LC_CTYPE, "en_US.UTF-8");
?>
phpman at crustynet dot org dot uk
12.10.2009 19:53
The comment from 'rmays at castlecomm dot com' is incorrect: single quotes cannot be backslash-escaped inside a single-quoted string when constructing a shell argument. The output from this function is in fact correct. It drops out of the single-quoted string, includes a literal single quote with a backslash-escape, then resumes the single-quoted string. Observe:

[shellarg.php]
<?php

system
("echo ' single quote\'d '");
system("echo ' single quote'\''d '");
?>

$ php shellarg.php
sh: -c: line 0: unexpected EOF while looking for matching `''
sh: -c: line 1: syntax error: unexpected end of file
 single quote'd
rmays at castlecomm dot com
23.07.2009 19:34
A warning on how this handles single quotes in a string

Example:
print escapeshellarg(" single quote'd ");

Expected:
' single quote\'d '

Actual Result:
' single quote'\''d '

So if you pass a ' into this function, it will return an incorrectly escaped string!!!!
jrbeaure at uvm dot edu
26.06.2009 15:51
When running a string of LaTeX code containing hyphens through as an argument to pdflatex escaped using this command, it will result in failure.
info at infosoporte dot com
20.01.2009 13:12
If escapeshellarg() function removes your accents (like á, a with an 'accute') from the given string, ensure your LC_ALL variable is correct. If using it via web, you need to restart Apache or the corresponding web server after setting LC_ALL with a export LC_ALL=es_ES.utf8 (for example) from your shell.
Audun
30.07.2008 14:02
The reason why % are replaced with space on windows is that it is impossible in cmd.exe to escape or quote them so that environment variables are not expanded.  If for instance %path% is in your argument it will always be expanded, so the only safe thing to do is to replace % with something else.

Alternatively, you could wipe the environment before making the call to exec(), but that has its side-effects.
Cameron
3.05.2008 8:45
in regards to the bug returning no string where it should return "" or '', just do
<?php
shell_exec
("example ". (($arg=escapeshellarg($arg))? $arg : "''"));
?>
egorinsk at gmail dot com
28.04.2007 13:09
Under Windows, this function puts string into double-quotes, not single, and replaces %(percent sign) with a space, that's why it's impossible to pass a filename with percents in its name through this function.
php at atu dot cjb dot net
15.03.2007 18:45
In reply to vosechu at roman-fleuve dot com: 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...

When many commands are executed, the order of the parameters is of critical importance, especially with shell scripts where $1, $2, $3, etc. are commonly used without checking what is stored in them first.  In such cases, having this function not return even an empty parameter will break things.

As was mentioned earlier, putting two single quotes '' before the output of this function will remedy this issue, as the '' in itself will not add any characters to that command line parameter, but it will turn it into a placeholder for that parameter when the value is empty.

22.05.2006 14:25
Most of the comments above have misunderstood this function. It does not need to escape characters such as '$' and '`' - it uses the fact that the shell does not treat any characters as special inside single quotes (except the single quote character itself). The correct way to use this function is to call it on a variable that is intended to be passed to a command-line program as a single argument to that program - you do not call it on command-line as a whole.

The person above who comments that this function behaves badly if given the empty string as input is correct - this is a bug. It should indeed return two single quotes in this case.
phpnet at lostreality dot org
11.11.2005 17:53
This function does not escape $ it seems. This lets user embed shell variables such as $PATH into commands, which you may or may not want to allow.  I'm using shell_exec() because I need the entire command as one string, and need access to the stdout data as one string as well.
ludvig dot ericson at gmail dot com
1.09.2005 19:17
It seems from my tests that escapeshellarg("`ls -al`") is _NOT_ escaped into \`ls -al\` as it should be.

Anyway, a bash/sh environment does not seem to interprett ` inside of a singleqoute (').

$ echo "`echo hello`"
hello
$ echo '`echo hello`'
`echo hello`
$ echo "\`echo hello\`"
`echo hello`

Just a tip.

18.05.2005 20:37
According to my test (PHP 4.3.10) there is no need to call escapeshellarg() on a filename that is being written to by proc_open, and probably others. E.g.
<?php
$process
= proc_open("echo hi",
                               array(
                                 
0 => array("pipe", "r"),
                                 
1 => array("file", 'filename with spaces', "w"),
                                 
2 => array("pipe", "w"),
                               ),
                              
$pipes);
?>
creates a file named:

filename with spaces

In fact,
<?php
         1
=> array("file", escapeshellarg('filename with spaces')
?>
creates a file named:

'filename with spaces'

(quotes included in filename.) Maybe all the PHP functions that take a filename as a separate parameter work this way. I guess you just need to escape filenames when they are part of a single string command line such as with the backtick operator, system(), etc.
antony lesuisse
23.04.2004 5: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
26.03.2004 2: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.03.2003 16: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...



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)