Learn how to escape and handle special characters in PHP for SQL queries, HTML output, and URLs. Prevent security vulnerabilities and data corruption.
Introduction
Special characters in PHP can cause security risks, data corruption, and formatting issues if not handled properly. Common scenarios include:
- Preventing SQL injection by escaping special characters in database queries
- Protecting against XSS (Cross-Site Scripting) in HTML output
- Encoding URLs properly for safe transmission in web applications
PHP provides built-in functions like mysqli_real_escape_string()
, htmlspecialchars()
, and urlencode()
to safely process user input and output.
This guide covers:
- Escaping strings for safe SQL queries
- Handling special characters in HTML output
- Encoding URLs properly for safe web navigation
- Best practices to prevent security vulnerabilities
1. Escaping Special Characters in SQL Queries
SQL injection is a serious vulnerability that occurs when user input is directly inserted into SQL queries without proper escaping.
Unsafe SQL Query (Vulnerable to Injection)
$user_input = "'; DROP TABLE users; --";
$query = "SELECT * FROM users WHERE name = '$user_input'"; // Dangerous!
If a user inputs ' OR 1=1 --
, it could return all database records or delete tables.
Using mysqli_real_escape_string()
to Escape Input
The correct approach is using mysqli_real_escape_string()
to sanitize user input before inserting it into an SQL query.
$mysqli = new mysqli("localhost", "user", "password", "database");
$user_input = $mysqli->real_escape_string($_GET['name']);
$query = "SELECT * FROM users WHERE name = '$user_input'";
$result = $mysqli->query($query);
- Escapes special characters like quotes and backslashes, preventing SQL injection.
- Always use prepared statements for better security.
Using Prepared Statements (Recommended Approach)
$mysqli = new mysqli("localhost", "user", "password", "database");
$stmt = $mysqli->prepare("SELECT * FROM users WHERE name = ?");
$stmt->bind_param("s", $_GET['name']);
$stmt->execute();
- Separates SQL logic from user input, preventing SQL injection completely.
2. Escaping Special Characters in HTML Output
HTML injection can lead to XSS attacks, where an attacker inserts malicious scripts into web pages.
Example of Vulnerable HTML Output
$name = "<script>alert('Hacked!');</script>";
echo "Welcome, $name";
If the user enters <script>alert('Hacked!');</script>
, the browser executes the script, posing a security risk.
Using htmlspecialchars()
to Prevent XSS
$name = "<script>alert('Hacked!');</script>";
$safe_name = htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
echo "Welcome, $safe_name";
Output
Welcome, <script>alert('Hacked!');</script>
- Converts special HTML characters into safe entities, preventing execution.
ENT_QUOTES
ensures single and double quotes are also escaped.- Always use
htmlspecialchars()
when displaying user-generated content.
3. Handling Special Characters in URLs
URLs cannot contain spaces, special characters, or non-ASCII text. Encoding URLs correctly prevents broken links and security risks.
Using urlencode()
for Query Parameters
$search = "PHP & MySQL";
$safe_url = "https://example.com/search?query=" . urlencode($search);
echo $safe_url;
Output
https://example.com/search?query=PHP+%26+MySQL
&
is converted to%26
to prevent query string corruption.urlencode()
encodes all unsafe URL characters.
Using rawurlencode()
for Path Components
If encoding a URL path rather than a query string, use rawurlencode()
.
$filename = "my file.txt";
$url = "https://example.com/files/" . rawurlencode($filename);
echo $url;
Output
https://example.com/files/my%20file.txt
- Spaces are encoded as
%20
instead of+
, ensuring compatibility with file paths.
4. Escaping JSON Strings
When sending data in JSON format, special characters must be properly escaped to avoid parsing errors.
Example of Unsafe JSON Encoding
$data = ["text" => "Hello \"world\"!"];
$json = json_encode($data);
echo $json;
Output
{"text":"Hello \"world\"!"}
- The double quotes in
"world"
are escaped automatically. json_encode()
ensures the JSON remains valid and safe.
5. Best Practices for Handling Special Characters
✅ Use prepared statements instead of manual SQL escaping.
✅ Always escape user input in HTML output using htmlspecialchars()
.
✅ Use urlencode()
for query strings and rawurlencode()
for URL paths.
✅ Use json_encode()
when handling JSON data to ensure valid formatting.
✅ Never trust user input—sanitize and validate all data before using it.
Conclusion
Handling special characters correctly ensures security, data integrity, and proper functionality in PHP applications.
This guide covered:
- Escaping SQL queries with
mysqli_real_escape_string()
and prepared statements - Preventing XSS with
htmlspecialchars()
- Encoding URLs with
urlencode()
andrawurlencode()
- Ensuring JSON safety with
json_encode()
By following these best practices, you can protect your application from security vulnerabilities while ensuring proper data handling.