Magic Quotes in PHP

John Wachira May 21, 2022
Magic Quotes in PHP

This article will discuss the addslashes() function in PHP. It returns strings with backslashes before predefined characters.

Predefined characters include:

  1. Single quote '
  2. Double quote ''
  3. Backslash \
  4. Null

Magic Quotes in PHP

We can practically use this function when preparing strings for storage in databases and queries.

Before magic quotes in PHP were depreciated, the magic_quotes_gpc was on by default. It used to run the addslashes() function on $_GET/$_POST/$_COOKIES/$_REQUEST by default.

We always check for already escaped strings. Running the addslashes() function on such a string leads to double escaping.

Use the get_magic_quotes_gpc() to verify if a string has been escaped.

Syntax:

addslashes(string)

The code below shows how the addslashes() function works.

<?php
// PHP code to show the
// working of the addslashes() function

// String
$str = addslashes('delftstack provides "coding" lessons');

// prints the escaped string
echo($str);
?>

Output:

delftstack provides \"coding\" lessons

Example 2:

<?php
$str = "My name's Chris.";
echo $str . " This is not secure in a database query.<br>";
echo addslashes($str) . " This is secure in a database query.";
?>

Output:

My name's Chris. This is not secure in a database query.
My name\'s Chris. This is secure in a database query.

It is important to note that the addslashes() function is different from the addcslashes() function.

Author: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn