'php system() command files due to '&' in password

I'm running the following command:

$cmd = escapeshellcmd( "echo '$password' | sudo -S mv \"$old\" \"$new\" " );
system( $cmd, $out );

This works when $password doesn't contain & but fails if it does. How do I get this to allow & and any other special characters in the password ?

Thanks

php


Solution 1:[1]

Don't use escapeshellcmd() on the whole command, use escapeshellarg() on individual arguments.

$password_esc = escapeshellarg($password);
$cmd = "echo $password_esc | sudo -S mv '$old' '$new'";
system($cmd, $out);

You don't need quotes around $password_esc because escapeshellarg() adds them.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1