Sneakyp33t
Sneakyp33t

Reputation: 93

PHP - Access-Control-Allow-Origin not working

I own a site that we'll call www.example.com. The main chunk of my site is in two files; header.php and index.php. The top half of the website code is in header.php while the bottom half is in index.php. My problem is, I can't get the Access-Control-Allow-Origin attribute to show up in the response header from example.com

My code:
The following is a simplified version of header.php:

<?php
header("Access-Control-Allow-Origin:*", false);
...
additional code here
...
?>
<!DOCTYPE html>
<html>
    <head>
        <title>My Site</title>
    </head>
    <body>
        ....
        top half of site code
        ....

The following is a simplified version of index.php:

<?php
header("Access-Control-Allow-Origin:*", false);
include ("header.php");
?>
        ....
        bottom half of site code
        ....
   </body>
</html>

Here is my request to retrieve the images:

$.ajax({
            type: "GET",
            url : folder,
            success: function (data) {
                if($(".img").length){
                    $(".img").remove();
                }

                $(data).find("a").attr("href", function (i, val) {
                    if( val.match(/\.(jpe?g|png|gif)$/) ) {
                        $("#img-lib").append( "<img class='img' src='"+ folder + val +"'>" );
                    }
                });
            },
            error: function () {
                $("#er").remove();
                $("#img-lib").append("<p id='er'>There was an error retrieving the images</p>");
            }
});



My error: This is what I get when I try to access www.example.com/Section/images/ :
https://i.sstatic.net/29t8n.jpg


What I have already tried:
(The following code snippets are the first line of php code)


It Might be worth mentioning that the site I am currently building is going to be used to edit my existing site (www.example.com).

Upvotes: 1

Views: 5397

Answers (1)

Daniel Kucal
Daniel Kucal

Reputation: 9242

Probably your static files, like images, aren't accessed via index.php (you are referring to their physical location). In this case, CORS headers can be set at the level of HTTP server. If it handles .htaccess files, you can simply create .htaccess file containing following content:

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"

in the main or specified directory.

Upvotes: 4

Related Questions