Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
How do I unescape shell arguments in PHP?
I have a PHP script which I want to call a Bash script which then in turn calls another PHP script. This may be completely unnecessary, but nonetheless.
PHP script 1:
// Borrowed from https://stackoverflow.com/a/25879953/209139
function my_shell_exec($cmd, &$stdout=null, &$stderr=null) {
$proc = proc_open(
$cmd,
[
0 => ["pipe", "r"], // stdin
1 => ["pipe", "w"], // stdout
2 => ["pipe", "w"], // stderr
],
$pipes
);
$stdout = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[2]);
return proc_close($proc);
}
$status = my_shell_exec(dirname(__FILE__) . '/import "' . escapeshellarg($path) . '"', $stdout, $stderr);
From Bash:
sudo -u www-data ${dir}/importer.php "${1-0}"
The final PHP script receives an escaped path, encased in single quotes, such as '/var/www/vhosts/assets.local/incoming/#N'\''LenCali [Wk] (Copy).webm'
(Yes, I'm deliberately testing this with a file name which begins with a hash and includes a single quote. Later tests will include Thai file names.) Spaces are not escaped. The actual file name is #N'LenCali [Wk] (Copy).webm
, so there's only one single quote there.
I can't see how to unescape this, to get a path which PHP will recognise. stripslashes()
, for example, gives three single quotes, not one.
0 comment threads