mysql_real_escape_string missing in php4

Discussions of secure PHP coding. Security in software is important, so don't be afraid to ask. And when answering: be anal. Nitpick. No security vulnerability is too small.

Moderator: General Moderators

Post Reply
User avatar
llimllib
Moderator
Posts: 466
Joined: Mon Jul 01, 2002 2:19 pm
Location: Baltimore, MD

mysql_real_escape_string missing in php4

Post by llimllib »

So, I've been out of PHP for a while but it pulled me back in. The server installation of PHP I'm using is of version 4.1.0, which doesn't have the mysql_real_escape_string function installed. I have limited control over the server environment, so I cannot install mysqli or any other shared libraries.

What's the best way to go about properly escaping mysql data? Has somebody ported the mysql_real_escape_string function to pure PHP? Does everyone just use addslashes?
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post by Burrito »

you might try its predecessor mysql_escape_string()...that came in around 4.0 something I think.
User avatar
aaronhall
DevNet Resident
Posts: 1040
Joined: Tue Aug 13, 2002 5:10 pm
Location: Back in Phoenix, missing the microbrews
Contact:

Post by aaronhall »

>=4.0.3 -- should work
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

You can use this (untested) but it's not as good as the real thing of course..

Code: Select all

if (!function_exists('mysql_real_escape_string')) 
{
    function mysql_real_escape_string($string, $link = null)
    {
        $chars = array(
            "\x00" => "\\x00",
            "\n" => "\\n",
            "\r" => "\\r", 
            "\\"  => "\\\\",
            "'" => "\'",
            '"' => '\"',
            "\x1a" => "\\x1a"
        );

        return str_replace(array_keys($chars), array_values($chars), $string);
    }
}
or rely on addslashes().
User avatar
aaronhall
DevNet Resident
Posts: 1040
Joined: Tue Aug 13, 2002 5:10 pm
Location: Back in Phoenix, missing the microbrews
Contact:

Post by aaronhall »

mysql_escape_string and mysql_real_escape_string are perfectly identical aside from the second *optional* argument in mysql_real that takes the charset of the connection into account (according to the manual)
User avatar
llimllib
Moderator
Posts: 466
Joined: Mon Jul 01, 2002 2:19 pm
Location: Baltimore, MD

Post by llimllib »

aaronhall wrote:mysql_escape_string and mysql_real_escape_string are perfectly identical aside from the second *optional* argument in mysql_real that takes the charset of the connection into account (according to the manual)
Sweet... I somehow looked right over that function. Thanks a lot.
Post Reply