<?php function getScheme(): string { return isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) ? 'https' : 'http'; } function getHost(): string { if (!isset($_SERVER['HTTP_HOST'])) return ''; return $_SERVER['HTTP_HOST']; } function getPort(): string { if (!isset($_SERVER['SERVER_PORT'])) return ''; $port = $_SERVER['SERVER_PORT']; if ($port == '80' || $port == '443') { $port = ''; } return $port; } function getOrigin(): string { $url = getScheme() . '://' . getHost(); $port = getPort(); if (!empty($port)) { $url .= ':' . $port; } return $url; } function main(): void { $orig = getOrigin(); print "orig=$orig\n"; } main(); ?>
Programming Tips - PHP: get origin of a URL (everything before the path)
Date: 2023jun26
Language: php
Q. PHP: get origin of a URL (everything before the path)
A. The origin is very useful. In javaScript its simply done with:
const origin = window.location.origin;
In php: