I am storing PHP snippets i开发者_StackOverflow中文版n a MySQL database, I am using mysql_real_escape_string and all is well unless there is a & in the php code and then I get a MySQL error. Is there another why I should try and store this information?
Thanks
@Peter : unless you're building a website for helping developers, you have no reason to put php code into your database, it's a warning : this is gonna be a big nightmare to maintain/debug. Can't you link your pages to some parameters and then in your code use these parameters to build each request ? it may seems a simple design solution at the beginning "how god I can do whatever I want in all my pages" but it might be the worse you're taking on your poject.
I don't know how to say this but you should really try to consider an other solution. And i'm not speaing about security : if you have an SQL Injection the guy can execute SQL AND php so he can really take all your system/server down, or even attack bigger site with yours (and then you'll be responsible).
I'm really surprised everyone is fine with it.
Use base64_encode when you save snippet into the database and base64_decode when you retreive it.
First, I am going to go on record and say I wholeheartedly agree with remi bourgarel. This is likely a bad idea.
But, from a technical standpoint here's how I'd do this IF I NEEDED TO:
$php_code = '
<?php
$var = "this is a string";
$var = strtoupper($var);
echo $var;
?>
';
$php_code = bin2hex($php_code);
$db->query("INSERT INTO php_code_snips (text_code) VALUES(x'{$php_code}')");
bin2hex
will transform the string $php_code
from a binary string to a hex string, and the x'{$php_code}'
tells mysql to expect a hex string.
This means the string is stored as a string in the DB, and is fully searchable. But, since all chars are encoded as hex during the INSERT
the special chars won't cause a problem.
Documentation:
bin2hex
Mysql Hex Values
精彩评论