nicuz Posted November 1, 2006 Share Posted November 1, 2006 I have a crawler that will fetch urls from a webpage. The urls are stored in my database. The next time I run the crawler script it checks the page for new urls and adds them to the database. The problem I'm having is that some of the webpages have urls with invalid characters (I think):[CODE]<a href="javascript:MM_openBrWindow('/pay-5','terms','scrollbars=yes,width=500,height=400');">[/CODE]This kind of url cannot be inserted in my database:[CODE]You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '','terms','scrollbars=yes,width=500,height=400');', '2006-11-01 00:38:59', 'pl' at line 1[/CODE]Anyone knows a way around this?I appreciate it Quote Link to comment Share on other sites More sharing options...
btherl Posted November 1, 2006 Share Posted November 1, 2006 When inserting your data, use mysql_real_escape_string() on the url first. Otherwise the quotes will alter your SQL statement. This is also a security issue, and allows someone to run arbitrary commands on your database, if they know you are crawling this site.eg[code]$escaped_url = mysql_real_escape_string($url);$sql = "INSERT INTO urls (url) VALUES '$escaped_url'";$result = mysql_query($sql) or die("Query failed: $sql\n with error " . mysql_error());[/code] Quote Link to comment Share on other sites More sharing options...
nicuz Posted November 1, 2006 Author Share Posted November 1, 2006 Thank you. It worked.Can you please tell me what were the ilegal characters? Quote Link to comment Share on other sites More sharing options...
btherl Posted November 1, 2006 Share Posted November 1, 2006 The illegal character there is the single quote: 'Imagine you do this:[code]$string = "'); DROP TABLE tab; SELECT ('";$sql = "INSERT INTO tab (col) VALUES ('$string')";[code]Then your sql statement will be this:[code]INSERT INTO tab (col) VALUES (''); DROP TABLE tab;SELECT ('')[/code]The key to this is that the single quote within the string lets you get out of the string.. after that, you will usually get a syntax error in your SQL. But someone crafty can start running his own sql commands.If you escape the string first, then the quotes will be escaped, so you get this:[code]INSERT INTO tab (col) VALUES ('\'); DROP TABLE tab;SELECT (\'')[/code]which will insert the string properly. The \' is treated as a normal character, instead of ending the string.[/code][/code] Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.