0

I have this command

echo "<?php $x=$_GET['x']; echo $x;?>" > x.php

the output file x.php is:

<?php =['x']; echo ;?>

Has that any relation to the $ variable? and how do I avoid ???, so that I get the right php code in the x file?

ctrl-alt-delor
  • 27,473
  • 9
  • 58
  • 102
Robotix
  • 33
  • 1
  • 1
  • 6
  • If you don't need a replacement for this command, what do you need? – Michael Homer Jun 15 '19 at 21:18
  • I mean I don't need to use cat or something else I need to avoid the $ problem ? – Robotix Jun 15 '19 at 21:21
  • 2
    If you're asking how to prevent the shell from interpreting `$x` then the answer is here: [What is the difference between “…”, '…', $'…', and $“…” quotes?](https://unix.stackexchange.com/questions/503013/what-is-the-difference-between-and-quotes) – steeldriver Jun 15 '19 at 21:22
  • 2
    What is the _expected_ output? – Kusalananda Jun 15 '19 at 21:25
  • The first php code – Robotix Jun 15 '19 at 21:26
  • 3
    Possible duplicate of [What is the difference between "...", '...', $'...', and $"..." quotes?](https://unix.stackexchange.com/questions/503013/what-is-the-difference-between-and-quotes) – Michael Homer Jun 15 '19 at 21:34
  • If you tell us what output you are expecting, then it would be easier to answer. I knew that you think that you have told us. You have not. You only have some code, and the wrong output. – ctrl-alt-delor Jun 15 '19 at 22:44

1 Answers1

2

Your code:

echo "<?php $x=$_GET['x']; echo $x;?>" > x.php

Since the string that you pass to echo is double quoted, the shell will try to expand any shell variables in it. The string contains two such variables, $x (twice) and $_GET. If these variables have no assigned value, they will be replace by empty strings.

Assuming that you want to print the string as it is to the file, do this instead:

echo '<?php $x=$_GET['"'"'x'"'"']; echo $x;?>' >x.php

Here, I've put the string in single quotes. This prevents the shell from trying to expand the things that looks like shell variables in it.

Since a single quoted string can't include single quotes, these would have to be added in a special way. I've opted for adding them as "'" (double quoted single quotes) through concatenation with the rest of the string.

Alternatively, escape every $ in the string:

echo "<?php \$x=\$_GET['x']; echo \$x;?>" >x.php

A third way is to use a quoted here-document:

cat <<'PHP_END' >x.php
<?php $x=$_GET['x']; echo $x;?>
PHP_END

This way you don't have to modify the actual string to make the shell treat it correctly, and you also don't have to remember that some shells' implementation of echo may do additional things with C-style escape sequences etc. (if you want to insert these into your PHP code).

Kusalananda
  • 320,670
  • 36
  • 633
  • 936