How do I secure PHP applications (CSRF, XSS, SSRF, RCE)?

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.

CSRF Protection

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.'); } ?>

XSS Protection

For XSS mitigation, always escape output data.

<?php $user_input = "<script>alert('XSS')</script>"; // Escape output echo htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8'); ?>

SSRF Protection

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 ?>

RCE Prevention

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); ?>

PHP Security CSRF XSS SSRF RCE Web Application Security