Solved

need form help with database and slashes etc...

Posted on 2002-06-03
9
192 Views
Last Modified: 2006-11-17
Can some please explain to me in detail what is the best way to setup a script when getting data from a user from a form that in then going to be sumbitted into a mysql database.  I have read as much as I can find and I get about 95% of it but it seems to be different in different articles I read. I want to know what is the best way.

Should I leave magic quotes on? Do I turn them off and use addslashes.
What about htmlspecialchars?  Should I also do that to every variable the user inputs?

This is a function I wrote for filtering the text with addslashes but I think I should remove it if magic quotes is on... correct?

function filter_text ($var)

{

        if (!empty($var))

        {

              $var = trim($var);

              $var = htmlspecialchars($var);

              $var = addslashes($var);

        }

        return $var;

}

What about getting the data back out of the database? If magic quotes is on do I do nothing or do I have to stripslashes?

Please help straighten this out for me. If you have function you use for filtering text can you please post the code or tell me what I should do with mine.

Thanks Onestar
0
Comment
Question by:onestar
9 Comments
 
LVL 1

Author Comment

by:onestar
ID: 7052940
I am still trying stuff out.

I noticed if you do no filtering and add 1" to the database it is 1" but if you first run it through htmlspecialchars then in the database you get 1"  This could be a problem if you searched for 1" to see if already exists then you won't find it because its 1"  

0
 
LVL 1

Author Comment

by:onestar
ID: 7052947
I am still trying stuff out.

I noticed if you do no filtering and add 1" to the database it is 1" but if you first run it through htmlspecialchars then in the database you get 1"  This could be a problem if you searched for 1" to see if already exists then you won't find it because its 1"  

0
 
LVL 1

Author Comment

by:onestar
ID: 7052953
I have a problem because my program uses a lot of searching and checking based on the product name. A lot of products have ' or " in the name.  My customer also gave in a text file with a list of all the products which I used to create a sql file to insert into the database from the command prompt.  So that doesn't have the same htmlspecialchars in it so I think thats messing me up too.
0
 
LVL 1

Author Comment

by:onestar
ID: 7053028
What about strip_tags() instead of htmlspecialchars? Does anyone use this?
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 5

Expert Comment

by:Hamlet081299
ID: 7053135
It probably helps to break this down into a few different parts.  There are a two main places where you are dealing with data that is passing between the user and the database...

1. Displaying the data from the database.

In this case you will need to use htmlspecialchars() to make sure that the browser does not confuse your output with html tags, or accidentally terminate a string too early.

2. Building the SQL that puts data back into the database.

Again it is important that special characters don't accidentally terminate a string at the wrong point.

It's probably a good idea that you understand the principles behind what's going on.  Try experimenting a bit by having lots of echo's in your script to tell you, for example, what the SQL looks like before you execute it.

Example:

Let's say you have a form with an input called "name", and the user has entered "John's Hardware".

$sql = "insert into table1 values (null, '$name')";
// this is bad: sql will be
// insert into table1 values (null, 'John's hardware')
// and the query will be rejected because "s hardware'" is just stuck there in a meaningless positions

$name = addslashes($name);
$sql = "insert into table1 values (null, '$name')";
// this will be better: sql will now be
// insert into table1 values (null, 'John\'s hardware')

This is assuming you magic_quotes_gpc off.  If it is on then $name will already have the slashes inserted.

In summary...

For display purposes you need to escape HTML codes.

For SQL queries you need to have quotes escaped - use magic quotes or add them yourself with addslashes.

I hope that made some sort of sense?
0
 
LVL 5

Expert Comment

by:dkjariwala
ID: 7053331
Hi Onestar,
You will have to see whether you have magic_quotes on or not.
Depending upon take the action.


I will write your function like,

function filter_text ($var)
{
       if (!empty($var))
       {
             $var = trim($var); //remove whitespaces.
          //now if you want no HTML tags to be interpreted, then use htmlentities instead of htmlspecialchars.
          $var = htmlentities($var);
          //              OR
          //sometimes you want to allow few HTML tags to be used and remove the other ones, in that case use strip_tags.
         // say you want to allow <b> and <i> tag.
         //then you will do it like
         $var = strip_tags($var,"<b><i>");

         //finally adding slashes,you need to do that ONLY when magic_quotes is ON,
         if(! get_magic_quotes_gpc())
                  $var = addslashes($var);
       }
       return $var;

}

This function should now take care of your data.
Remember to use stripslashes when you fetch data back otherwise you will have something like Harry O\' Corner ...

JD
0
 
LVL 1

Author Comment

by:onestar
ID: 7054014
Thanks for the advice.

Okay this is what I am think of doing.

Turn on mgaic_quotes_gpc ON
All data coming from the form run it through filter_intext
and all data getting printed to the screen run it through
filter_outtext.

I think writing functions to do this is much better then just using the php functions because if I have to change the function it will be much easier. (I know the program might be a little slower but not much).



function filter_intext ($var)
{
      if (!empty($var))
      {
           $var = trim($var); //remove whitespaces.
           if(! get_magic_quotes_gpc())
                 $var = addslashes($var);
      }
      return $var;
} // end func





function filter_outtext ($var)
{
      if (!empty($var))
      {
           $var = htmlentities($var);
           if(! get_magic_quotes_gpc())
                 $var = stripslashes($var);
      }
      return $var;
} // end func


So what do you think? Does anyone see any problems?

Thanks
Onestar
0
 
LVL 5

Accepted Solution

by:
Hamlet081299 earned 50 total points
ID: 7055095
That looks pretty good.  Just a couple of minor notes...

In filter_outtext you should probably do stripslashes BEFORE you do htmlentities.  It will probably still work the way you have it, but it may not in all cases.

And also you should probably do $var = htmlentities($var, ENT_QUOTES);

For example... (doing htmlentities first)

$s = 'Can\\\'t say \"No\" ';
// s = Can\'t say \"No\"

$s = htmlentities($s, ENT_QUOTES);
// now s = Can\&#039;t say \&quot;No\&quot;

$s = stripslashes($s);
// now s = Can&#039;t say &quot;No&quot;

Although the result is okay, it's really just a fluke because stripslashes is not fussy about where it takes the slashes from.

In htmlentities the ENT_QUOTES is necessary to make sure that single quotes are also translated, otherwise consider ...

$s = 'Don\'t do this';
$s = htmlentities($s);
echo "<option value='$s'>";

This will not work because it becomes...
<option value='Don't do this'>
... and if selected the value will be just 'Don' !?

0
 
LVL 11

Expert Comment

by:shmert
ID: 9643247
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:
SPLIT dkjariwala & hamlet
Please leave any comments here within the next seven days.
               
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
               
Sam Barnum
EE Cleanup Volunteer              
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Suggested Solutions

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now