Jump to content


Photo

mysql_real_escape_string()


  • Please log in to reply
11 replies to this topic

#1 russia5

russia5
  • Members
  • PipPipPip
  • Advanced Member
  • 94 posts

Posted 29 August 2006 - 07:01 PM

I have just put MySQL_real_escape_string() on my form variables.  Is there an input I can put in a text field that I can go to my admin and see if the code is escaping the characters ie) if the mysql_real_escape_string() is working?

#2 wildteen88

wildteen88
  • Staff Alumni
  • Advanced Member
  • 10,482 posts
  • LocationUK, Bournemouth

Posted 29 August 2006 - 07:08 PM

use echo

#3 russia5

russia5
  • Members
  • PipPipPip
  • Advanced Member
  • 94 posts

Posted 29 August 2006 - 07:45 PM

Sorry, let me clarify the question a bit.  I have never used mysql_real_escape_string() so sorry if the question is elementary.  I am uder the impression, that it takes characters, namely ', and escapet them ie) /'  So, it seems to me, if I was to put testing'  in my text box, in my admin panel, I should get testing/'  The problem is that I am not.  (the admin panel is an output of the database)

#4 wildteen88

wildteen88
  • Staff Alumni
  • Advanced Member
  • 10,482 posts
  • LocationUK, Bournemouth

Posted 29 August 2006 - 07:51 PM

It is doing the trick I assure, otherwise your SQL Query would fail. When you get the data out of the database mysql will unescape the previously escaped characters.

You should be able to see the escape characters when you look into your database, you can do by using phpMyAdmin which most hosts provide to help manage your mysql databases.

#5 russia5

russia5
  • Members
  • PipPipPip
  • Advanced Member
  • 94 posts

Posted 29 August 2006 - 08:07 PM

Ooohhh.... Thankyou very much!  I was having fits.  How does mysql know to do that?

#6 wildteen88

wildteen88
  • Staff Alumni
  • Advanced Member
  • 10,482 posts
  • LocationUK, Bournemouth

Posted 29 August 2006 - 11:27 PM

I ment PHP rather than MySQL. PHP is smart enough to recognise escaped characters within a string and attempts to unescape them when they are outputted.

#7 russia5

russia5
  • Members
  • PipPipPip
  • Advanced Member
  • 94 posts

Posted 29 August 2006 - 11:56 PM

Oh Boy... it didn't work.  I went to the database and the table showed all of the characters just the way I put them in.

I will post the code in case you would be kind enough to take a look and see if you see anything.

(Thanks again in a major way!)

<?php
//the variables below are an abbreviated list
name = trim($_POST['name']);
$city = trim($_POST['city']);
$country = trim($_POST['country']);

$name = mysql_real_escape_string($_POST['name']);
$city = mysql_real_escape_string($_POST['city']);
$country = mysql_real_escape_string($_POST['country']);


$name = strip_tags($_POST['name']);
$city = strip_tags($_POST['city']);
$country = strip_tags($_POST['country']);



// Anti-SQL Injection
function check_inject()
  {
    $badchars = array(";", "'", "\"", "*", "DROP", "SELECT", "UPDATE", "DELETE", "-");
 
    foreach($_POST as $value)
    {
      if(in_array($value, $badchars))
      {
        filelogs("injection", "user", $_SERVER['REMOTE_ADDR']);
        die("SQL Injection Detected\n<br />\nIP: ".$_SERVER['REMOTE_ADDR']);
      }
      else
      {
        $check = preg_split("//", $value, -1, PREG_SPLIT_OFFSET_CAPTURE);
        foreach($check as $char)
        {
          if(in_array($char, $badchars))
          {
            filelogs("injection", "user", $_SERVER['REMOTE_ADDR']);
            die("SQL Injection Detected\n<br />\nIP: ".$_SERVER['REMOTE_ADDR']);
          }
        }
      }
    }
  }
// File Logger
function filelogs($type, $info, $muser) {
$agent = $_SERVER['HTTP_USER_AGENT'];
    $uri = $_SERVER['REQUEST_URI'];
    $ip = $_SERVER['REMOTE_ADDR'];
    $ref = $_SERVER['HTTP_REFERER'];
    $dtime = date('r');
   
    if($ref == ""){
        $ref = "None";
    }
    if($muser == ""){
        $muser = "None";
    }
    $location = "/";
    $type = $location . $type . ".txt";
    $entry_line = "$dtime - IP: $ip | Agent: $agent  | URL: $uri | Referrer: $ref | Username: $muser | Query : $info \n";
    $fp = fopen("$type", "a");
    fputs($fp, $entry_line);
    fclose($fp);
}

   
if (empty($_REQUEST['step'])) $step = 1; else $step = $_REQUEST['step'];


include_once ("config.php");

if (!empty($_POST))
{
if ($step < 3) // insert/update info
{
  $fields = $values = array();
 
  unset($_POST['Submit']);
 
  if (empty($_POST['id']))
  {
  unset($_POST['id']);
  foreach ($_POST as $field=>$value)
  {
    $fields[] = $field;
    $values[] = '"'.htmlspecialchars(trim($value)).'"';
  } 
  $query = 'INSERT INTO Profile_submission ('.implode(',', $fields).') VALUES ('.implode(',',$values).')';
  mysql_query($query);
  $id = mysql_insert_id();

  # set cookies
  if (!empty($id)) setcookie('authcode', $id, time() + 3600*24*365, '/');
 
  }
  else
  {
  $qryString = array();
  $currentID = $_POST['id'];
  unset($_POST['id']);
  foreach ($_POST as $field=>$value)
  {
    $qryString[] = $field.' = "'.htmlspecialchars(trim($value)).'" ';
  } 
  $query = 'UPDATE Profile_submission SET '.implode(',', $qryString).' WHERE sid = "'.$currentID.'"';
  mysql_query($query);
  }
}
else // upload photos
{
$uploaded_file ="";
  // move uploaded file
  if ($_FILES['picture']['tmp_name'] != "none" and $_FILES['picture']['tmp_name'] != "")
  {
  $tmpname = rand(time()-10000, time()).".jpg";
  $uploaded_file = 'uploads/'.$tmpname;
                             
                           
  if (@move_uploaded_file($_FILES['picture']['tmp_name'], $uploaded_file))
  {
    chmod($uploaded_file, 0777);
  } 
  }
$query = 'UPDATE Profile_submission SET picture'.($step-2).' = "'.$uploaded_file.'" WHERE sid = '.$id;
  mysql_query($query);
}
}
elseif (!empty($_COOKIE['authcode']))
{
$query = 'SELECT * FROM Profile_submission WHERE sid = "'.$_COOKIE['authcode'].'"';
$result = mysql_query($query);
if (mysql_num_rows($result))
{
  $profile = mysql_fetch_assoc($result);
  $id = $_COOKIE['authcode'];
}
}


if ($step > 6) {
header("Location: http://");
}

?>


#8 wildteen88

wildteen88
  • Staff Alumni
  • Advanced Member
  • 10,482 posts
  • LocationUK, Bournemouth

Posted 30 August 2006 - 12:00 AM

before you use mysql_real_escape_string make sure you are connected to mysql first. mysql_real_escape_string requires you to be connected to mysql in order for this function to work. From looking at your code you connect to mysql way after you use mysql_real_escape_string.

#9 redarrow

redarrow
  • Members
  • PipPipPip
  • Advanced Member
  • 7,308 posts
  • Locationlondon

Posted 30 August 2006 - 01:13 AM

another way ok.

<?php

$name = addslashes($_POST['name']);
$city = addslashes($_POST['city']);
$country = addslashes($_POST['country']);

?>


Wish i new all about php DAM i will have to learn
((EMAIL CODE THAT WORKS))
http://simpleforum.ath.cx/mail2.inc
((PAYPAL INTEGRATION THAT WORKS))
http://simpleforum.a...aypal1_info.inc

#10 .josh

.josh
  • Staff Alumni
  • .josh
  • 14,871 posts

Posted 30 August 2006 - 06:01 AM

<?php
//the variables below are an abbreviated list
name = trim($_POST['name']);
$city = trim($_POST['city']);
$country = trim($_POST['country']);

$name = mysql_real_escape_string($_POST['name']);
$city = mysql_real_escape_string($_POST['city']);
$country = mysql_real_escape_string($_POST['country']);


$name = strip_tags($_POST['name']);
$city = strip_tags($_POST['city']);
$country = strip_tags($_POST['country']);
you keep overwriting your previous variables with your new variables, because you use the same $_POST in each new php function call, instead of using the new and altered data.  example:

$name = trim($_POST['name']);

you are making a variable called $name, trimming $_POST['name'] and assigning the result to $name.

then in the next step, you are taking this same $name, mysql_escape_real_stringing it, but instead of using your trimmed variable, you are using the original $_POST['name'].  so when all is said and done, all you've really done is strip_tagged the original $_POSTed data.

what you should be doing is something like this:

<?php
$name = trim($_POST['name']);
$name = mysql_real_escape_string($name);
$name = strip_tags($name);
?>

also to re-iterate what wildteen said too: you need to establish a db connection before you can use mysql_real_escape_string.  move your include('config.php'); up to somewhere before calling that function.
Did I help you? Feeling generous? Buy me lunch! 
Please, take the time and do some research and find out how much it would have cost you to get your help from a decent paid-for source. A "roll-of-the-dice" freelancer will charge you $5-$15/hr. A decent entry level freelancer will charge you around $15-30/hr. A professional will charge you anywhere from $50-$100/hr. An agency will charge anywhere from $100-$250/hr. Think about all this when soliciting for help here. Think about how much money you are making from the work you are asking for help on. No, we do not expect you to pay for the help given here, but donating a few bucks is a fraction of the cost of what you would have paid, shows your appreciation, helps motivate people to keep offering help without the pricetag, and helps make this a higher quality free-help community :)

#11 Jenk

Jenk
  • Members
  • PipPipPip
  • Advanced Member
  • 778 posts

Posted 30 August 2006 - 08:50 AM

mysql_real_escape_string() is all you need to make a variable safe for inserting to mysql. strip_tags() is not necessary (and is not favored over htmlentities(),) trim is just not necessary.

Escaping characters only turns them to literal values. You will not see the escaping character ("\") in your MySQL database. Inserting a value of: O'Reilly (when escaped will appear as O\'Reilly) will appear in your database as O'Reilly.

If you do not escape, the query will fail.

#12 russia5

russia5
  • Members
  • PipPipPip
  • Advanced Member
  • 94 posts

Posted 31 August 2006 - 11:26 AM

Thankyou very much!  I took something from all the posts and made it work!  I moved the MySQL connection to the top, deleted the addslashes() so now all I have is the mysql_real_escape_string() so the variables are not being overwritten and it works fine.  I understand from the posts, that the way you know it works, is that you are not getting an error.  (and I am not) Thankyou very much for your help! Greg




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users