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?

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.