Reputation: 3224
I know htmlspecialchars
is for html output and mysql_real_escape_string
is for insert for the database. I'm not sure how to apply in this scenario. For example
$search = mysql_real_escape_string(htmlspecialchars($_GET['search'],ENT_QUOTES));
mysql_query("INSERT INTO table1 VALUES ('','$search')",$this->connect);
echo "<a href='http://www.example.com/$search'>$search</a>";
Do i have to seperate the top line so mysql_real_escape_string
is before the insert and htmlspecialchars
is after? I'm hoping i don't have to otherwise i have to go over alot of code..
Also would using htmlspecialchars
twice do anything different then once? I'm sure somewhere in my code i have used htmlspecialchars
twice on the same variable.
e.g.
$var = htmlspecialchars($one); //top of page
$var2 = htmlspecialchars($var); //another function
Upvotes: 1
Views: 835
Reputation: 522042
$searchTerm = $_GET['search'];
mysql_query("INSERT INTO table1 VALUES ('', '" . mysql_real_escape_string($searchTerm) . ')"', $this->connect);
echo "<a href='http://www.example.com/" . htmlspecialchars(urlencode($searchTerm), ENT_QUOTES) . "'>$search</a>";
Only escape at the exact moment needed, once. In your case, since the value is supposed to be part of a URL, it needs to be URL encoded. Since that URL is then made part of HTML, it needs to be HTML escaped.
Upvotes: 2
Reputation: 57388
You need two copies of the search variable: one to be stored in SQL, and that one you can pass through mysql_real_escape_string; the other to be displayed, and there you use htmlspecialchars.
Actually you need three copies: in one, you encode e.g. " " to "+" and this is for GET URLs; another will escape SQL characters; and the third will escape HTML.
You may want to pass _web and _sql through UTF8, too.
$search_web = htmlspecialchars($_GET['search'],ENT_QUOTES);
$search_sql = mysql_real_escape_string($_GET['search']);
$search_url = urlencode($_GET['search']);
// Do try and upgrade to PDO, here...
mysql_query("INSERT INTO table1 VALUES ('','$search_sql')",$this->connect);
echo "<a href='http://www.example.com/$search_url'>$search_web</a>";
Upvotes: 1
Reputation: 160833
Use mysql_real_escape_string
to escape string for sql (※do not escape html special chars).
$search = mysql_real_escape_string($_GET['search']);
Use htmlspecialchars
when you display the data in web page.
<?php echo htmlspecialchars($var) // ex. $var is the content of $_GET['search'] ?>
Upvotes: 0