generating PHP code - escaping strings

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

I am outputting generated PHP code, and part of the code has something

$var = 'some string here';

Where the string part is generated from a value from a database.

What is the best/easiest way to escape that string?

I thought about addslashes, but that would also escape double quotes,
which would change the value of the string.

If I do it with double quotes:

$var = "some string here";

and then use addslashes, now, for example, if the string contained
$name, it would consider that a variable.   I want the variable to
have the exact value of the string from the database. Any suggestions?

Re: generating PHP code - escaping strings

On 3 Feb, 16:00, ""
Quoted text here. Click to load it

I don't really understand what you're asking. PHP won't interpolate
strings unless they are explicitly coded with variable names within
the php code....if you do:

$user=3D"random crap";
$qry=3D'INSERT INTO mytable (some_field) values ( \'hello $user\')';
$user=3D"other stuff"
$fetch=3D'SELECT some_field FROM mytable';

.....then $row['some_field']=3D=3D=3D"hello $user"

You should never use addslashes(). If you need to encode a string for
a specific purpose, then you should use the method appropriate
(mysql_real_escape_string(), urlencode(), htmlentities()....etc)


Site Timeline