Enhancing Web Security: A Guide to Content-Security-Policy and X-Frame-Options

Sure thing! Let's break down this code step by step:

1. Setting Security Headers

header("Content-Security-Policy: frame-ancestors 'self' https://aicrafter.us https://qiksoft.com");
header('X-Frame-Options: SAMEORIGIN');
  • Content-Security-Policy (CSP): This header restricts which sources can embed your content in a frame. Here, it allows only the same origin ('self') and the specified domains (https://aicrafter.us and https://qiksoft.com).
  • X-Frame-Options: This header prevents your content from being embedded in an iframe by other sites, which helps to avoid clickjacking attacks. SAMEORIGIN means only pages from the same origin can embed this content.

2. Allowed Domains

$allowed_domains = [
    'https://aicrafter.us',
    'https://qiksoft.com',
];
  • This array lists the domains that are allowed to embed your content.

3. Referer Check

$referer = $_SERVER['HTTP_REFERER'] ?? '';
$valid_referer = false;

foreach ($allowed_domains as $domain) {
    if (strpos($referer, $domain) === 0) {
        $valid_referer = true;
        break;
    }
}
  • Referer: This retrieves the HTTP referer header, which indicates the URL of the page that linked to the resource being requested.
  • Validation: The code checks if the referer starts with any of the allowed domains. If it does, $valid_referer is set to true.

4. Redirect if Invalid Referer

if (!$valid_referer) {
    // Redirect to your desired URL
    header('Location: https://aicrafter.us/');
    exit();
}
  • If the referer is not valid (i.e., it doesn't start with any of the allowed domains), the user is redirected to https://aicrafter.us/.

Example Usage

Imagine you have a web application that should only be embedded in iframes on specific trusted domains. This code ensures that only those domains can embed your content, and it redirects users to a safe page if the referer is not valid.

Feel free to ask if you have any more questions or need further clarification!

// Set security headers
header("Content-Security-Policy: frame-ancestors 'self' https://aicrafter.us https://qiksoft.com");
header('X-Frame-Options: SAMEORIGIN');

// Allowed domains
$allowed_domains = [
    'https://aicrafter.us',
    'https://moreonlineprofit.com',
];

// Referer check
$referer = $_SERVER['HTTP_REFERER'] ?? '';
$valid_referer = false;

foreach ($allowed_domains as $domain) {
    if (strpos($referer, $domain) === 0) {
        $valid_referer = true;
        break;
    }
}

if (!$valid_referer) {
    // Redirect to your desired URL
    header('Location: https://aicrafter.us/');
    exit();
}