WP-Mix

A fresh mix of code snippets and tutorials

Strip Slashes from PHP Magic Quotes

Here are a couple of functions to strip or remove slashes (i.e., backslashes) from variables when PHP magic quotes are enabled on the server.

Strip slashes from strings

If you are working with a string, you can do something like this:

if (get_magic_quotes_gpc()) {
	$message = stripslashes($message);
}

Here we are using stripslashes to remove all backslashes from the string. So if $message contains \', this snippet will replace it with '. Likewise, if $message contains \\', it will be replaced with \', and so on.

Strip slashes from arrays

In this example, we’ll strip all backslashes from common global variables ($_POST, $_GET, $_COOKIE, and $_REQUEST), which happen to be arrays.

if (get_magic_quotes_gpc()) {
	$_POST    = array_map('stripslashes', $_POST);
	$_GET     = array_map('stripslashes', $_GET);
	$_COOKIE  = array_map('stripslashes', $_COOKIE);
	$_REQUEST = array_map('stripslashes', $_REQUEST);
}

Here we first use get_magic_quotes_gpc() to check whether or not magic quotes are enabled. If they are enabled, then we pass each of our global variables through array_map(), which in turn applies stripslashes() to each array value. The result is a set of global variables that have been properly “de-slashed”. Works with any array :)

★ Pro Tip:

USP ProSAC Pro