0

Is there a code to block special characters in the url? If you try to put a special character into the URL of a site (example: / ;) it's converted to a "%".

This prevent against SLQ injection, or some kind of injection, right?

How can i do it?

At the moment my website only convert the Apostrophe (').

Susi
  • 153
  • 1
  • 3
  • 11
  • 2
    *"This prevent against SLQ injection, or some kind of injection, right?"* - No it doesn't. In any case, use a prepared statement. I'm on the fence as to close this as the standard ["How can I prevent SQL injection in PHP?"](https://stackoverflow.com/q/60174/1415724). If not, then you'll need to expand on what it is you really need here. – Funk Forty Niner Sep 12 '18 at 21:30
  • I'm always amazed at how many questions on Stack Overflow are trying to find a defense against SQL Injection other than the one that actually works: using query parameters. – Bill Karwin Sep 12 '18 at 21:38

3 Answers3

3

This is called URL encoding and is not used to prevent SQL injection or any other kind of attack. You can do it in PHP through URL functions, notably urlencode.

However, I would advise against doing that "blindly" if you don't understand the implications or what it's for.

If you have an actual problem that you are trying to solve, you should ask about that problem and not your perceived solution.

Alex Turpin
  • 46,743
  • 23
  • 113
  • 145
3

Replacing characters that are not valid for URL with special codes is urlencode function. It is not about security. But without it URL may become invalid so you will not get a response.

To avoid SQL injection vulnerability use prepared statement(depending on library/extension you use to connect to DB it could be mysqli::prepare, pdo::prepare ) or something else. Check examples in docs articles.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
2

What you're talking about is known as URL encoding, and has nothing to do with SQL injection. URL encoding is done to prevent confusion with the following characters which have special meaning:

!    *       '       (       )       ;       :       @       &       =       +       $        ,      /        ?       #      [       ]
%21  %23     %24     %26     %27     %28     %29     %2A     %2B     %2C     %2F     %3A     %3B     %3D     %3F     %40    %5B     %5D

This is done automatically by the browser, and you do not need to set anything up server-side for your users. However, you can make use of urlencode() if you need to pass an encoded string, and urldecode() if you need to find what the string used to be.

To prevent SQL injection, the most important thing to do is make use of prepared statements. In procedural MySQLi, this would look like:

$stmt = $conn->prepare('SELECT * FROM table WHERE field = ?');
$stmt->bind_param('s', $variable);
$stmt->execute();

For additional preventative measures, I would recommend referring to this post.

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71