homepage Welcome to WebmasterWorld Guest from 54.226.191.80
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
htmlspecialchars() Function
Syntax question
Sub_Seven




msg:4185071
 8:56 pm on Aug 10, 2010 (gmt 0)

Hello there, I have yet a few more question for you guys.

I have this example code to insert data to a DB:


<?php
$con = mysql_connect("localhost","user","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("application", $con);

$sql="INSERT INTO applications (first_name, interest) VALUES ('{$_POST['first_name']}', '{$_POST['interest']}')";

if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}

header( 'Location: thankyou.php' ) ;

mysql_close($con)
?>



My questions are:

1. Is this where you would escape special characters before they are inserted into the DB?

2. Is the htmlspecialchars() Function the best option to escape special characters?

3. If so, what is the syntax to use around '{$_POST['value']}',

Thanks for any help provided.

 

AlexK




msg:4185086
 9:39 pm on Aug 10, 2010 (gmt 0)

Hi Sub_Seven

1 Do not ever, ever, ever post user-input direct into MySQL without checking/cleaning. If you do so, your site will be hacked in days, if not hours.

2 MySQL is UTF8, and can accept any character whatsoever that you give it. What you therefore need to do is POST-processing, not PRE-processing (use
htmlspecialchars(), whatever, before you send it to the browser, not the DB).

3 The syntax that you are going to use, therefore, is something like: `
mysql_real_escape_string( $text, $connection )'.

4 In the end, whatever you decide to do, be consistent throughout, and also, make sure that you document it!

Matthew1980




msg:4185089
 9:42 pm on Aug 10, 2010 (gmt 0)

Hi there Sub_Seven,

<?php
$con = mysql_connect("localhost","user","pass") or die("Could not connect:".mysql_error());

mysql_select_db("application", $con);

$sql = "INSERT INTO `applications` (`first_name`, `interest`) VALUES ('". mysql_real_esscape_string(htmlspecialchars($_POST['first_name']))."', '". mysql_real_escape_string(htmlspecialchars($_POST['interest']))."') ";

if (!mysql_query($sql,$con)){
echo "there was an error";
}
else{
echo "Successfully added";
}

header("Location: thankyou.php");

mysql_close($con);
?>

1)You can do it OTF or outside, that's up to you
2)There are others, but depends on the context of your project I guess
3)As I have given in the example, I personally don't use the {} option as I find it hard to read ;P

That's sort what your looking at, though you can use array_map to apply the functions before the sql string to make things a little easier to read, hope this makes sense to you.

Also, so long as there is a connection going, mysql_real_escape_string() & any other function that uses a connection handle will inherit the last 'inuse' connection that is established to the server, so you can leave the parameter blank if you wish :)

Note: you don't necessarily need to explicitly close the connection, because after each query it's automatically done - it's documented on here:[uk3.php.net ]

I quote:-
>>The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling mysql_close().

Cheers,
MRb

Sub_Seven




msg:4185131
 12:44 am on Aug 11, 2010 (gmt 0)

@AlexK

1. Thanks for the quick reply.

2.
Do not ever, ever, ever post user-input direct into MySQL without checking/cleaning. If you do so, your site will be hacked in days, if not hours.


mysql_real_escape_string is a way to perform this checking/cleaning, right? I'm sorry; this confused me a little as it seems you're saying I'm still missing something.

3.
The syntax that you are going to use, therefore, is something like: `mysql_real_escape_string( $text, $connection )'.


This worked like a charm, I was able to pass ', ", &, < and > with no problem.

4.
In the end, whatever you decide to do, be consistent throughout, and also, make sure that you document it!


You know, me being new to php, around 6-8 weeks since I started learning, and I have learned more than I can imagine, I have not documented a thing...! Thanks for that one; I need to start ASAP...

@Matthew1980

1.
You can do it OTF or outside, that's up to you


Got it! Although outside would be a little harder right now as I would have to start by asking: outside where? Don't mind answering that question though, the code is working as I speak [write...]

2.
There are others, but depends on the context of your project I guess


Good to know there are others; I will someday need to compare what's better for different projects.

3.
That's sort what your looking at, though you can use array_map to apply the functions before the sql string to make things a little easier to read, hope this makes sense to you.

Also, so long as there is a connection going, mysql_real_escape_string() & any other function that uses a connection handle will inherit the last 'inuse' connection that is established to the server, so you can leave the parameter blank if you wish :)


None of those two paragraphs made sense... at all, I'm starting to believe I'm not theoric and I need to see things in examples.

4.
you don't necessarily need to explicitly close the connection, because after each query it's automatically done


By that you mean I can get rid of: mysql_close($con);?

5. You are more than helpful in this side of the forum, I believe not one of my topics has been left without an answer from you, if you ever come to Costa Rica you have to let me buy you a beer, or 100 based on how much you've helped, thanks a lot :)

Thanks Matthew and AlexK

Matthew1980




msg:4185220
 7:17 am on Aug 11, 2010 (gmt 0)

Hi there Sub_Seven,

mysql_real_escape_string is a way to perform this checking/cleaning, right? I'm sorry; this confused me a little as it seems you're saying I'm still missing something.

A few preferred 'cleansers'
  • mysql_real_escape_string() <- make the data more 'acceptable'
  • strip_tags() <- remove HTML from user submitted data
  • trim() <- remove surplus whitespace

    There are more, but I haven't had my coffee yet ;-p

    Ok, mysql_real_escape_string() is just a way of making text submitted by the user to be inserted into the DB arrive intact - at least that's how I think of it :)

    Here is the read-up for it:-
    [uk2.php.net ]

    You can use this (mysql_real_escape_string) during sanitising if you like, I just have it in a function along with some others and call that function outside the sql string, so that the data used in the sql string is cleaned before I use it I guess that as you get more proficient you will see how things can be done in a more efficient way.

    //comments are good, especially if you are forgetful & comments are ignored by the parser so you
    //dont need to worry about how often you comment

    >>By that you mean I can get rid of: mysql_close($con);?
    That's up to you, but I rarely use them, unless I really go out of my way to do so, but if I write something that has persistent connection with lots of requests/querys I see no point in using it at all.. That's just me though...

    Lol, beer is currency in some places!

    Cheers,
    MRb

  • AlexK




    msg:4185235
     7:47 am on Aug 11, 2010 (gmt 0)

    Sub_Seven:
    mysql_real_escape_string is a way to perform this checking/cleaning, right?

    No.

    mysql_real_escape_string() (as you have discovered) will help you get all sorts of problematic characters into the DB. It *is* also vital when you use user-input to search the DB. The reason for this latter is because so many people will attempt to send specially-crafted strings to hack your website - the main villain there is the `;' character. Nevertheless, the reason for my statement is that you need to get into the habit of coding checks for user-input as early as possible.

    When I see such as your example:
      $sql=INSERT INTO ... $_POST['first_name']
    ...it makes me shiver. I'm a webmaster as well as programmer, and I spend time looking at server logs. I therefore see the raw strings that are sent to my server. Please understand, there are hundreds of attempts to hack my server each day (mine is not unique in this). You need to educate yourself in website & server security from day one.

    None of those two paragraphs made sense

    I'll deal with the
    $connection item.

    $connection = mysql_connect('localhost','user','pass');
    mysql_select_db($db, $connection);

    From this point on, certain PHP functions can include
    $connection as a parameter. mysql_real_escape_string() is just one example of those. IF YOU ONLY HAVE ONE DB OPEN, it is not *required* to include the parameter (the function then makes use of the last-used value). Personally, I always include it.
    Sub_Seven




    msg:4190114
     5:58 am on Aug 21, 2010 (gmt 0)

    Hey guys, sorry for the late reply, I have been quite busy since I was able to put this together, it is funny how I just read the entire thread and now all makes sense (even those things I could not understand when I had all the pressure on me)

    Thanks for all the help and have a nice weekend :)

    Global Options:
     top home search open messages active posts  
     

    Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
    rss feed

    All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
    Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
    WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
    © Webmaster World 1996-2014 all rights reserved