WP-Mix

A fresh mix of code snippets and tutorials

PHP: Get current URL

Nice lil slab of PHP to get the current URL. Useful for a wide variety of applications, nice one to have in the tool belt.

// get current URL
function get_current_URL() {
	$current_url  = 'http';
	$server_https = $_SERVER["HTTPS"];
	$server_name  = $_SERVER["SERVER_NAME"];
	$server_port  = $_SERVER["SERVER_PORT"];
	$request_uri  = $_SERVER["REQUEST_URI"];
	if ($server_https == "on") $current_url .= "s";
	$current_url .= "://";
	if ($server_port != "80") $current_url .= $server_name . ":" . $server_port . $request_uri;
	else $current_url .= $server_name . $request_uri;
	return $current_url;
}

Usage:

echo get_current_URL();

Note: this returns the server name and other variables without any sanitization. It’s probably a good idea to sanitize the output just in case the server is sending bogus name and/or other infos.

Bonus! Here is an alternate technique, taken from a previous version of my frontend posts plugin:

// get current URL
function shapeSpace_current_url() {
	$pageURL = 'http';
	
	if ($_SERVER['HTTPS'] == 'on') {
		$pageURL .= 's';
	}
	
	$pageURL .= '://';
	if ($_SERVER['SERVER_PORT'] != '80') {
		$pageURL .= $_SERVER['SERVER_NAME'] .':'. $_SERVER['SERVER_PORT'] . $_SERVER['REQUEST_URI'];
	} else {
		$pageURL .= $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
	}
	
	do_action('usp_current_page', $pageURL);
	return esc_url($pageURL);
}

Usage:

echo shapeSpace_current_url();

★ Pro Tip:

USP ProSAC Pro