Using WordPress ‘addslashes_gpc()’ PHP function

The addslashes_gpc() WordPress PHP function is used to add slashes to a string, or recursively add slashes to strings within an array.

Usage

To use addslashes_gpc(), you simply need to pass the data you want to add slashes to as an argument. This data could be either a string or an array of strings.

Example:

$data = "John's Car";
$slashed_data = addslashes_gpc($data);
echo $slashed_data; // Outputs: John\'s Car

Parameters

  • $gpc (string|array) – This is the data you wish to add slashes to. It can be a string or an array of strings.

More information

See WordPress Developer Resources: addslashes_gpc()

Examples

Adding slashes to a string

This code adds slashes to a string.

$data = "John's Car";
$slashed_data = addslashes_gpc($data);
echo $slashed_data; // Outputs: John\'s Car

Adding slashes to an array of strings

This code recursively adds slashes to all strings within an array.

$data = array("John's Car", "James's Bike");
$slashed_data = addslashes_gpc($data);
print_r($slashed_data); // Outputs: Array ( [0] => John\'s Car [1] => James\'s Bike )

Adding slashes to a multidimensional array

This code recursively adds slashes to strings within a multidimensional array.

$data = array(
  "vehicles" => array("John's Car", "James's Bike"),
  "pets" => array("John's Dog", "James's Cat")
);
$slashed_data = addslashes_gpc($data);
print_r($slashed_data);
// Outputs: Array ( 
//   [vehicles] => Array ( [0] => John\'s Car [1] => James\'s Bike ) 
//   [pets] => Array ( [0] => John\'s Dog [1] => James\'s Cat ) 
// )

Preventing SQL Injection

This code shows how you might use addslashes_gpc() to prevent SQL Injection attacks by adding slashes to user input.

$user_input = "John'; DROP TABLE users;";
$safe_input = addslashes_gpc($user_input);
echo $safe_input; // Outputs: John\'; DROP TABLE users;

Adding slashes to form input

This code adds slashes to form input before processing it.

$form_input = $_POST['input']; // User input from form
$safe_input = addslashes_gpc($form_input);
// Now you can safely process $safe_input