Search code examples
phpexecshell-exec

PHP passing string with apostrophe to shell_exec


I’m trying to pass a string (drawn from a PDO query to an MYSQL DB) via PHP shell_exec to a *nix program, in this case xtide.

All works fine until I pass a string containing an apostrophe.

This works in the Terminal on OSX:

house@New-MacBook-Pro:~$ tide -l "Nomans Land, Martha's Vineyard, Massachusetts"

but the exact same string, from a PDO query to a MYSQL DB, and passed as a variable into shell_exec, always fails. It doesn’t seem to matter how I arrange the single/double quotes.

Running this adds the backslash, but it still fails:

$tideLocation = mysql_real_escape_string($tideLocation);

outputs:

Nomans Land, Martha\’s Vineyard, Massachusetts

Failures:

$output1 = shell_exec("/opt/local/bin/tide -l 'Nomans Land, Martha's Vineyard, Massachusetts'");

$output1 = shell_exec("/opt/local/bin/tide -l '$tideLocation'");

This works, when set up manually in shell_exec:

$output1 = shell_exec("/opt/local/bin/tide -l 'Nomans Land, Martha\'s Vineyard, Massachusetts'");

Advice most welcome.


Solution

  • Use escapeshellarg to properly escape a string in single quotes for a command line arguments.

    Example:

    $command = '/opt/local/bin/tide -l ' . escapeshellarg($tideLocation);
    shell_exec($command);