Pages

Sunday, February 27, 2011

Make Addslashes More Universal

When writing user submitted data to a MySQL database, it is important to add the appropriate slashes to prevent errors. If magic quotes is running then there is no need to do anything, but if magic quotes is turned off then you need to run addslashes (). What if you want to make a more universal program, that will work for both types of PHP configuration?

One way to do it is to write a function that checks if magic quotes is running and then runs addslashes () based on the results. We check the status of magic quotes using the get_magic_quotes_gpc () function.

 <?php
 function Mod_addslashes ( $string )
 {
 if (get_magic_quotes_gpc()==1)
{
 return ( $string );
 }
 else
 {
 return ( addslashes ( $string ) );
 }
 }
 ?>

In the code above, we first check if magic quotes is turned on. If it is, we just return the data again. If it isn't we run it through addslashes () first. So, each place in our code where we would have normal run addslashes (), we will now run Mod_addslashes () instead.

No comments:

Post a Comment