How often have you ever found out that magic quotes was turned on, but you forgot all about it? Or your result from a database row is fine in its’ result set, except for the slashes?
Not too often for me either. But there are exceptions. Today, for example, I needed to stripslashes from every string in an array of strings. The normal stripslashes function just isn’t equipped to handle arrays of data.
Here’s what I’ve come up with:
<?php function stripslashesArray($arr) { //check if the variable is an array if (is_array($arr)) { //get the keys of the array $keys = array_keys($arr); for ($x=0;$x<count($keys);$x++) { //check if array item is not an object if (!is_object($arr[$keys[$x]])) { //strip the slashes of the item, even if it's an array $arr[$keys[$x]] = stripslashesArray($arr[$keys[$x]]); } } return $arr; //return the stripped array } else { //variable is just a string, treat as normal return stripslashes($arr); //return the stripped string } } //end stripslashesArray function ?>
Download this code: stripslashesarray.php
So you see, the function makes sure you’re not sending it an object, or an array with an object as an item. The function also calls itself again and again until all branches on the array are stripped. However, if you have an array with an object as an item, and that object has an array of strings, they won’t be stripped. I don’t see many opportunities where that would come up anyway!
Now that we’re stripping slashes, it’s just a simple modification to start adding slashes:
<?php function addslashesArray($arr) { //check if the variable is an array if (is_array($arr)) { //get the keys of the array $keys = array_keys($arr); for ($x=0;$x<count($keys);$x++) { //check if array item is not an object if (!is_object($arr[$keys[$x]])) { //add the slashes to the item, even if it's an array $arr[$keys[$x]] = addslashesArray($arr[$keys[$x]]); } } return $arr; //return the stripped array } else { //variable is just a string, treat as normal return addslashes($arr); //return the stripped string } } //end addslashesArray function ?>
Download this code: addslashesarray.php
The functions have more use than you’ve thought. For example, if you’ve just transferred your site to a new server, and magic quotes behave differently than before, you can use stripslashesArray or addslashesArray on your $_POST, $_REQUEST and $_GET arrays.
I hope this keeps you all sane.
Technorati: php, programming