Heliosh Heliosh - 4 months ago 21
PHP Question

php: prevent escapeshellcmd() from removing special characters

I would like to pass special characters to a shell command, however escapeshellcmd() doesn't let me to.
How do I mask them so they get through?

Example:

<?php
$specialchars='I would like to print a µ';
$escaped_specialchar=escapeshellcmd($specialchars);
echo $escaped_specialchar;
?>

Answer

You could first create a whitelist, in which you define the special characters which are ok to display. Also set some string with which you could replace the characters.

Then replace the characters in your command with the string. Escape your command.

Switch the special characters in again by replacing the string.

Like this:

$allowedCharakters = array(
    'µ' => 'microUThingie',
);

$specialchars='I would like to print a µ';

foreach ($allowedCharakters as $key => $value) {
    $specialchars = str_replace($key, $value, $specialchars);
}

$escaped_specialchar=escapeshellcmd($specialchars);

foreach ($allowedCharakters as $key => $value) {
    $escaped_specialchar = str_replace($value, $key, $specialchars);
}
Comments