send_origin_headers()
Sends CORS headers if the request came from an allowed source (URL).
Sends the following headers if the request came from an allowed source (origin):
Access-Control-Allow-Origin: http://example.com Access-Control-Allow-Credentials: true
Usually, this function is used as an additional check for the validity of the request during an AJAX request, for example in the file admin-ajax.php. For instance, thanks to this function, AJAX requests to another site will not work—requests are only allowed within the current domain.
The function may also be useful for handling preflight requests.
The source (origin) of the request is determined by the function get_http_origin()—it is taken from the parameter $_SERVER['HTTP_ORIGIN']. This parameter is set from the request header Origin:, which is set by the browser (client), so the value of this parameter cannot be trusted.
For OPTIONS requests (HTTP request method), the script simply terminates PHP execution via exit, while setting the response header to 403 if the origin is not allowed.
Criticism
In my opinion, this is a very strange function because:
-
$_SERVER['HTTP_ORIGIN']can be spoofed, so get_http_origin() cannot be trusted—protection is illusory. -
The essence of the function is some kind of pseudo-check, but not a real protection of the request.
-
If the origin is not allowed—CORS headers are not sent at all, meaning the request is not blocked by the browser. It turns out that to bypass this "protection," it is enough to specify an inappropriate source—which looks strange.
-
The return value ($origin or false) is not used anywhere in the core and has no practical meaning. The purpose of the function is to set HTTP headers. Why does it return anything at all?
- The practical benefit of the function remains unclear (please explain in the comments if you know).
Conclusion: a useless function.
No Hooks.
Returns
String|false. Returns:
origin URL, if headers are sent.false, if headers are not sent.
Usage
send_origin_headers();
Examples
#1 Demo
Example of a function that will generate the headers necessary for an ajax request:
function send_ajax_headers() {
wp_magic_quotes();
send_origin_headers();
@header('X-Robots-Tag: noindex' );
send_nosniff_header();
nocache_headers();
@header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
@header('Content-Type: application/json; charset=' . get_option( 'blog_charset' ));
}
Changelog
| Since 3.4.0 | Introduced. |
send_origin_headers() send origin headers code WP 7.0
function send_origin_headers() {
$origin = get_http_origin();
if ( is_allowed_http_origin( $origin ) ) {
header( 'Access-Control-Allow-Origin: ' . $origin );
header( 'Access-Control-Allow-Credentials: true' );
if ( 'OPTIONS' === $_SERVER['REQUEST_METHOD'] ) {
exit;
}
return $origin;
}
if ( 'OPTIONS' === $_SERVER['REQUEST_METHOD'] ) {
status_header( 403 );
exit;
}
return false;
}