Handling Cross-Origin Requests and Security Restrictions in PHP

This article explains how to use PHP functions such as header(), mysqli_real_escape_string(), and htmlspecialchars() to enable cross-origin resource sharing, handle preflight OPTIONS requests, and protect against SQL injection and XSS attacks, thereby improving web security and user experience.

php Courses
php Courses
php Courses
Handling Cross-Origin Requests and Security Restrictions in PHP

In web development, cross-origin requests and security restrictions are common challenges; cross-origin requests occur when a page on one domain accesses resources on another, and browsers block them by default for security.

This article explains how PHP can be used to address these issues.

Setting Response Headers

Using the PHP header() function, you can set HTTP response headers to allow other domains to access resources, e.g., header('Access-Control-Allow-Origin: *'); Replace * with a specific domain to restrict access.

Handling Preflight Requests

For complex cross-origin requests, browsers send a preflight OPTIONS request. You can detect this method and send appropriate headers:

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type');
    header('Access-Control-Max-Age: 86400');
    exit;
}

This code sets allowed methods, headers, and caching time.

Preventing SQL Injection

PHP’s mysqli_real_escape_string function escapes user input to avoid SQL injection:

$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";

Preventing XSS Attacks

Use htmlspecialchars to convert special characters to HTML entities, preventing XSS:

$username = htmlspecialchars($_POST['username']);

By setting appropriate response headers and using escaping functions, PHP can effectively manage cross-origin requests and enhance security.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Web DevelopmentPHPXSSCORS
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.