简体   繁体   中英

PHP Access-Control-Allow-Origin header not working

I'm working on a JavaScript script that makes AJAX requests to another server (my own domain). The JavaScript script is added to the page using a plugin. It should retrieve data from a PHP file on my domain.

I've added the following header to the PHP file:

<?php
header("Access-Control-Allow-Origin: *");

but the AJAX request still throws an error. Changing the * to the actual domain I plan to use it on doesn't work either. I've searched stack overflow for answers, and came across the following:

// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day
}

// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

    exit(0);
}

which doesn't work, either.

I thought my .htaccess file may have somehow affected things, so I deleted it temporarily, but the AJAX request still said no Access-Control-Allow-Origin header was set in the PHP file.

I've found this on daniweb.com: https://www.daniweb.com/web-development/php/threads/461902/php-header-is-not-working-for-access-control-allow-origin which was unresolved.

If the headers have definitely been set (in multiple ways), how come the AJAX request still throws an error, stating the headers haven't been set?

The data that was being sent via the AJAX request was breaking the PHP script - causing it to not execute correctly, which I guess prevented the headers from being set correctly.

Note to all that view this in the future: I assume this is the reason yours may not be working properly too - and most probably why the topics I have viewed prior to writing this were never answered. It is admittedly quite embarrassing. I guess nobody fancied admitting they did something stupid before now.

Make sure the data you send within the request doesn't somehow cause the PHP script to fail to execute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM