Jump to content

Problem inserting text in database


nicuz

Recommended Posts

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
Link to comment
Share on other sites

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]
Link to comment
Share on other sites

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]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.