The get_http_origin() WordPress PHP function retrieves the HTTP Origin of the current request.
Usage
$origin = get_http_origin();
Parameters
None
More information
See WordPress Developer Resources: get_http_origin()
Examples
Validate an AJAX request
Check if the request is a valid AJAX request by matching the HTTP origin.
$origin = get_http_origin();
if ( $origin === site_url() ) {
// This is a valid AJAX request from our own site
// Continue processing
} else {
// Invalid request, possibly a cross-origin request
// Terminate processing
}
Allow cross-origin requests for a specific domain
Allow cross-origin requests from a specific domain (e.g., example.com).
$origin = get_http_origin();
if ( $origin === 'https://example.com' ) {
header('Access-Control-Allow-Origin: ' . $origin);
}
Allow all cross-origin requests
Allow all cross-origin requests to the site.
$origin = get_http_origin();
header('Access-Control-Allow-Origin: ' . $origin);
Check if the request is from a subdomain
Verify if the request originates from a subdomain of the current site.
$origin = get_http_origin();
$current_site_url = site_url();
if ( strpos( $origin, $current_site_url ) !== false ) {
// The request is from a subdomain
} else {
// The request is from an external domain
}
Log the HTTP origin of a request
Log the HTTP origin of a request for debugging purposes.
$origin = get_http_origin();
// Log the origin to the debug.log file
error_log("Request origin: " . $origin);