Kadjo

SoftDev Journal

About This Journal

24 June 2007 by Jojo Makiling

Technical concerns tend to find a solution as long as there are good people working on them. And Linux has the very best. - Linus Torvalds

Notes on PHP addslashes,mysql_escape and stripcslashes

April 21st, 2009 by pepesmith

This is just a short note while I was coding/studying on PHP a few minutes earlier for my site.

From the manual of PHP:

addslashes – Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote (’), double quote (”), backslash (\) and NUL (the NULL byte). [1]

mysql_real_escape_string — Escapes special characters in a string for use in a SQL statement [2]

stripslashes — Un-quote string quoted with addslashes() [3]

The purpose of using mysql_real_escape_string is to prevent this sql injection attack thing on data that was then typed by the user. This mysql_real_escape_string is somewhat functions like addslashes. When you browse or retrieve your data via mysql shell or any mysql query browser utility you will notice that there are additional characters that were added. To remove that additional character, the stripslashes function is needed and provided also by PHP.

Here is my sample code :

foreach ($dispute_message2 as $key => $value)
{
$value[messages] = stripslashes($value[messages]);
}

Note that is code is on a function and the field messages is the one that contains the extra-codes made by mysql_real_escape_string(). The issue then here is that when i tried to print the messages here from $dispute_message2 array, still i can see the extra-codes.

I’ve found later my answer on this on the foreach explanation.
“Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself.”

Thus, I made some revisions on the code and here is the latest one.

foreach ($dispute_message2 as $key => $value)
{
$dispute_messages2[$key][messages] = stripslashes($value[messages]);
}

:) Adding this $dispute_messages2[$key] fixed my problem.

[1] http://www.php.net/manual/en/function.addslashes.php
[2] http://www.php.net/manual/en/function.mysql-real-escape-string.php
[3] http://www.php.net/manual/en/function.stripslashes.php

Posted in Miscellaneous | No Comments »

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.