Search code examples
phpsyntaxsedquoteslibssh2

Escaped Quotes in PHP for Sed Command


I have the following php code

if (!($stream = ssh2_exec($con, 'sed -i \'s/motd=A Minecraft Server/motd=\'.$name.\'s     Server/g\' /home/servers/runner15/server.properties
'))) {

But when I run it instead of replacing the text "motd=A Minecraft Server" to "motd=runner15s Server" it Changes it to motd=..s Server

It's something todo with escaping the quotes

Oh by the way $name holds runner15


Solution

  • Basic PHP strings... ' strings do NOT interpolate variables, so your sed command contains a literal $, n, a, m, e, etc... That'll be interpreted as a non-existent shell varaible on the remote server, and expand to an empty string.

    [...snip...]otd=A Minecraft Server/motd=\''.$name.'\'s [..snip...]
                                              ^-------^--- 'exit' the string in your client-side PHP