Securing PHP applications is crucial to protect against various attack vectors, such as Cross-Site Request Forgery (CSRF), Cross-Site Scripting (XSS), Server-Side Request Forgery (SSRF), and Remote Code Execution (RCE). Below are methods to mitigate these risks along with examples.
To protect against CSRF, implement CSRF tokens in forms.
<?php
session_start();
// Generate token
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
?>
<form method="POST" action="submit.php">
<input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
<!-- Other form fields -->
<input type="submit" value="Submit">
</form>
<?php
// Validate token in submit.php
if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
die('CSRF token validation failed.');
}
?>
For XSS mitigation, always escape output data.
<?php
$user_input = "<script>alert('XSS')</script>";
// Escape output
echo htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
?>
To prevent SSRF attacks, whitelist URLs or use DNS filtering.
<?php
$allowed_hosts = ['example.com', 'api.example.com'];
$url = $_POST['url'];
$host = parse_url($url, PHP_URL_HOST);
if (!in_array($host, $allowed_hosts)) {
die('URL not allowed.');
}
// Proceed with the request
?>
To avoid Remote Code Execution, avoid using eval() and sanitize all inputs.
<?php
// Avoid using eval() in your code
$unsafe_code = $_POST['code'];
// Instead use a safe alternative
// $result = safe_function($unsafe_code);
?>
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?