Manipulate URL $_SERVER['REQUEST_URI'] - php

This is my url:
http://localhost/framework/index.php
echo $_SERVER['REQUEST_URI'];
Would output: /framework/index.php
But If my url was:
http://localhost/framework/
The output would be:
/framework/
And If I move the file, yeah you get the idea.
How do I grab the content after folders/eventually index.php file? My idea is to have index.php as a front controller.
If I have:
http://localhost/framework/index.php/test/test
I only want the test/test part.
http://localhost/framework/test/test
I only want the test/test part.

You can automatically detect the base uri and remove it, leaving you with the test/test part.
if(!empty($_SERVER['PATH_INFO']))
{
// Uri info does not contain docroot or index
$uri = $_SERVER['PATH_INFO'];
}
else
{
if(!empty($_SERVER['REQUEST_URI']) && !empty($_SERVER['HTTP_HOST']))
{
$fullUrl = 'http://'
. ((isset($_SERVER['HTTP_HOST'])) ? $_SERVER['HTTP_HOST'] : '')
. ((isset($_SERVER['REQUEST_URI'])) ? $_SERVER['REQUEST_URI'] : '');
$uri = parse_url($fullUrl, PHP_URL_PATH);
}
else if(!empty($_SERVER['PHP_SELF']))
{
$uri = $_SERVER['PHP_SELF'];
}
}
$baseUri = substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], "/")+1);
$uri = str_replace($baseUri, '', $uri);
Edit: mAu's comment above is correct. I was under the assumption you was already using mod rewrite.

Related

What is the fastest way to strip a single GET parameter from a URL in PHP?

Example:
The user calls:
http://www.example.com/?mysecret=hello&second=world&third=bar
If "mysecret" is correct a cookie is set and user shall be redirected to:
http://www.example.com/?second=world&third=bar
Code sample:
if(is_page(MY_LOCKED_PAGE)) {
if($_COOKIE["unlocked"]=="y") {
// proceed
} else if(isset($_GET["mysecret"])) {
setcookie('unlocked','y',time()+3600*24*180,'/',"",false,true);
// strip mysecret from the URL
// redirect to the original URL without the get parameter "mysecret", but keeping other get parameters
} else {
// redirect 404
}
}
Fill in the missing code - what is the fastest way to strip the parameter mysecret and redirect to the same url?
Just simply unset() your mysecret and harness http_build_query() to generate the new url from the $_GET super global:
unset($_GET['mysecret']);
$url = http_build_query($_GET);
// redirect
header("Location: {$url}");
And here's an Example.
The full answer which worked for me is as below:
unset($_GET['mysecret']);
$build = http_build_query($_GET);
$uri_parts = explode('?', $_SERVER['REQUEST_URI'], 2);
$prot = "http://";
if(isset($_SERVER['HTTPS'])) {
if ($_SERVER['HTTPS'] == "on") {
$prot = "https://";
}
}
$url = $prot . $_SERVER['HTTP_HOST'] . $uri_parts[0] . "?" . $build;
// redirect
header("Location: {$url}"); die;

htaccess redirect to modified url

I have multiple pages that are used to pull metadata for facebook, however they are linked to a page that is to be hidden from the public. The url that is to not be seen is:
test.local/university/test_name
The above link should redirect to:
test.local/content/university
Is there any way I can do this with a RewriteRule in htaccess? Or does it need to be done via a PHP redirect?
Apologies if duplicate.
Update:
This is how I resolved this problem.
$domain = $_SERVER["HTTP_HOST"];
$uri = $_SERVER["REQUEST_URI"];
$url = "http://".$domain . $uri;
$parsedURL = parse_url($url);
// search regex
$regex = "(^\/[\d]+-(.*?)/)";
// get the matched part of the url
if (strpos($_SERVER['HTTP_REFERER'], 'facebook.com') !== false) {
if (preg_match($regex, $parsedURL['path'], $matches) === 1) {
$url = $parsedURL['scheme'] . "://" . $parsedURL['host'] . "/content" . $matches[0];
header('Location: ' . $url);
}
}
Try something like this...
RewriteEngine On # Turn on the rewriting engine
RewriteRule ^test.local/content/university$ path/to/real/page.php [NC,L]
Hope this helps.
You can use this RedirectMatch rule in your site root's .htaccess:
RedirectMatch 301 ^/(university)/[\w-]+ /content/$1
cheers for your input. I done this in via PHP in the end.
$domain = $_SERVER["HTTP_HOST"];
$uri = $_SERVER["REQUEST_URI"];
$url = "http://".$domain . $uri;
$parsedURL = parse_url($url);
// search regex
$regex = "(^\/[\d]+-(.*?)/)";
// get the matched part of the url
if (strpos($_SERVER['HTTP_REFERER'], 'facebook.com') !== false) {
if (preg_match($regex, $parsedURL['path'], $matches) === 1) {
$url = $parsedURL['scheme'] . "://" . $parsedURL['host'] . "/content" . $matches[0];
header('Location: ' . $url);
}
}

Get URL of page without domain using the same site structure

I have the following problem: I have a set of domains with the same url structure:
domain-a.com/london/
domain-b/london/
domain-c/london/
I want to do the following thing:
If you are on domain-a.com/london/, I want "related" links underneath pointing to domain-b.com/london/ and domain-c.com/london/
I want these links to appear automatically using the URL of the current page, remove the domain so that only the rest is left - in my example: /london/ and add the other domains in front of this.
I know I have to use echo $_SERVER['REQUEST_URI']; to get the rest of the URL but I don't know how to create a link using this function.
<?php
$url = $_SERVER['HTTP_HOST'];
$uri = $_SERVER['REQUEST_URI'];
function generateLink($url, $uri){
if(strpos($url,'domain-a.com') !== false){
$link = 'http://domain-b.com' . $uri;
return $link;
}else if(strpos($url,'domain-b.com') !== false){
$link = 'http://domain-c.com' . $uri;
return $link;
}else if(strpos($url,'domain-c.com') !== false){
$link = 'http://domain-a.com' . $uri;
return $link;
}
}
?>
Link

PHP how to get the base domain/url?

function url(){
if(isset($_SERVER['HTTPS'])){
$protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
}
else{
$protocol = 'http';
}
return $protocol . "://" . $_SERVER['HTTP_HOST'];
}
For example with the function above, it works fine if I work with the same directory, but if I make a sub directory, and work in it, it will give me the location of the sub directory also for example. I just want example.com but it gives me example.com/sub if I'm working in the folder sub. If I'm using the main directory,the function works fine. Is there an alternative to $_SERVER['HTTP_HOST']?
Or how could I fix my function/code to get the main url only? Thanks.
Use SERVER_NAME.
echo $_SERVER['SERVER_NAME']; //Outputs www.example.com
You could use PHP's parse_url() function
function url($url) {
$result = parse_url($url);
return $result['scheme']."://".$result['host'];
}
Shortest solution:
$domain = parse_url('http://google.com', PHP_URL_HOST);
/**
* Suppose, you are browsing in your localhost
* http://localhost/myproject/index.php?id=8
*/
function getBaseUrl()
{
// output: /myproject/index.php
$currentPath = $_SERVER['PHP_SELF'];
// output: Array ( [dirname] => /myproject [basename] => index.php [extension] => php [filename] => index )
$pathInfo = pathinfo($currentPath);
// output: localhost
$hostName = $_SERVER['HTTP_HOST'];
// output: http://
$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https'?'https':'http';
// return: http://localhost/myproject/
return $protocol.'://'.$hostName.$pathInfo['dirname']."/";
}
Use parse_url() like this:
function url(){
if(isset($_SERVER['HTTPS'])){
$protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
}
else{
$protocol = 'http';
}
return $protocol . "://" . parse_url($_SERVER['REQUEST_URI'], PHP_URL_HOST);
}
Here is another shorter option:
function url(){
$pu = parse_url($_SERVER['REQUEST_URI']);
return $pu["scheme"] . "://" . $pu["host"];
}
Step-1
First trim the trailing backslash (/) from the URL. For example, If the URL is http://www.google.com/ then the resultant URL will be http://www.google.com
$url= trim($url, '/');
Step-2
If scheme not included in the URL, then prepend it. So for example if the URL is www.google.com then the resultant URL will be http://www.google.com
if (!preg_match('#^http(s)?://#', $url)) {
$url = 'http://' . $url;
}
Step-3
Get the parts of the URL.
$urlParts = parse_url($url);
Step-4
Now remove www. from the URL
$domain = preg_replace('/^www\./', '', $urlParts['host']);
Your final domain without http and www is now stored in $domain variable.
Examples:
http://www.google.com => google.com
https://www.google.com => google.com
www.google.com => google.com
http://google.com => google.com
2 lines to solve it
$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$myDomain = preg_replace('/^www\./', '', parse_url($actual_link, PHP_URL_HOST));
/* Get sub domain or main domain url
* $url is $_SERVER['SERVER_NAME']
* $index int remove subdomain if acceess from sub domain my current url is https://support.abcd.com ("support" = 7 (char))
* $subDomain string
* $issecure string https or http
* return url
* call like echo getUrl($_SERVER['SERVER_NAME'],7,"payment",true,false);
* out put https://payment.abcd.com
* second call echo getUrl($_SERVER['SERVER_NAME'],7,null,true,true);
*/
function getUrl($url,$index,$subDomain=null,$issecure=false,$www=true) {
//$url=$_SERVER['SERVER_NAME']
$protocol=($issecure==true) ? "https://" : "http://";
$url= substr($url,$index);
$www =($www==true) ? "www": "";
$url= empty($subDomain) ? $protocol.$url :
$protocol.$www.$subDomain.$url;
return $url;
}
Use this code is whork :
if (!preg_match('#^http(s)?://#', $url)) {
$url = 'http://' . $url;
}
$urlParts = parse_url($url);
$url = preg_replace('/^www\./', '', $urlParts['host']);
This works fine if you want the http protocol also since it could be http or https.
$domainURL = $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME'];
Please try this:
$uri = $_SERVER['REQUEST_URI']; // $uri == example.com/sub
$exploded_uri = explode('/', $uri); //$exploded_uri == array('example.com','sub')
$domain_name = $exploded_uri[1]; //$domain_name = 'example.com'
I hope this will help you.
Tenary Operator helps keep it short and simple.
echo (isset($_SERVER['HTTPS']) ? 'http' : 'https' ). "://" . $_SERVER['SERVER_NAME'] ;
If you're using wordpress, use get_site_url:
get_site_url()

How do I get the base URL with PHP?

I am using XAMPP on Windows Vista. In my development, I have http://127.0.0.1/test_website/.
How do I get http://127.0.0.1/test_website/ with PHP?
I tried something like these, but none of them worked.
echo dirname(__FILE__)
or
echo basename(__FILE__);
etc.
Try this:
<?php echo "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; ?>
Learn more about the $_SERVER predefined variable.
If you plan on using https, you can use this:
function url(){
return sprintf(
"%s://%s%s",
isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
$_SERVER['SERVER_NAME'],
$_SERVER['REQUEST_URI']
);
}
echo url();
#=> http://127.0.0.1/foo
Per this answer, please make sure to configure your Apache properly so you can safely depend on SERVER_NAME.
<VirtualHost *>
ServerName example.com
UseCanonicalName on
</VirtualHost>
NOTE: If you're depending on the HTTP_HOST key (which contains user input), you still have to make some cleanup, remove spaces, commas, carriage return, etc. Anything that is not a valid character for a domain. Check the PHP builtin parse_url function for an example.
Function adjusted to execute without warnings:
function url(){
if(isset($_SERVER['HTTPS'])){
$protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
}
else{
$protocol = 'http';
}
return $protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}
Fun 'base_url' snippet!
if (!function_exists('base_url')) {
function base_url($atRoot=FALSE, $atCore=FALSE, $parse=FALSE){
if (isset($_SERVER['HTTP_HOST'])) {
$http = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
$hostname = $_SERVER['HTTP_HOST'];
$dir = str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
$core = preg_split('#/#', str_replace($_SERVER['DOCUMENT_ROOT'], '', realpath(dirname(__FILE__))), NULL, PREG_SPLIT_NO_EMPTY);
$core = $core[0];
$tmplt = $atRoot ? ($atCore ? "%s://%s/%s/" : "%s://%s/") : ($atCore ? "%s://%s/%s/" : "%s://%s%s");
$end = $atRoot ? ($atCore ? $core : $hostname) : ($atCore ? $core : $dir);
$base_url = sprintf( $tmplt, $http, $hostname, $end );
}
else $base_url = 'http://localhost/';
if ($parse) {
$base_url = parse_url($base_url);
if (isset($base_url['path'])) if ($base_url['path'] == '/') $base_url['path'] = '';
}
return $base_url;
}
}
Use as simple as:
// url like: http://stackoverflow.com/questions/2820723/how-to-get-base-url-with-php
echo base_url(); // will produce something like: http://stackoverflow.com/questions/2820723/
echo base_url(TRUE); // will produce something like: http://stackoverflow.com/
echo base_url(TRUE, TRUE); || echo base_url(NULL, TRUE); // will produce something like: http://stackoverflow.com/questions/
// and finally
echo base_url(NULL, NULL, TRUE);
// will produce something like:
// array(3) {
// ["scheme"]=>
// string(4) "http"
// ["host"]=>
// string(12) "stackoverflow.com"
// ["path"]=>
// string(35) "/questions/2820723/"
// }
$base_url="http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["REQUEST_URI"].'?').'/';
Usage:
print "<script src='{$base_url}js/jquery.min.js'/>";
$modifyUrl = parse_url($url);
print_r($modifyUrl)
Its just simple to use
Output :
Array
(
[scheme] => http
[host] => aaa.bbb.com
[path] => /
)
I think the $_SERVER superglobal has the information you're looking for. It might be something like this:
echo $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']
You can see the relevant PHP documentation here.
Try the following code :
$config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$config['base_url'] .= "://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
echo $config['base_url'];
The first line is checking if your base url used http or https then the second line is use to get the hostname .Then the third line use to get only base folder of your site ex. /test_website/
The following code will reduce the problem to check the protocol.
The $_SERVER['APP_URL'] will display the domain name with the protocol
$_SERVER['APP_URL'] will return protocol://domain ( eg:-http://localhost)
$_SERVER['REQUEST_URI'] for remaining parts of the url such as /directory/subdirectory/something/else
$url = $_SERVER['APP_URL'].$_SERVER['REQUEST_URI'];
The output would be like this
http://localhost/directory/subdirectory/something/else
Simple and easy trick:
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$path = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$baseurl = "http://" . $host . $path . "/";
URL looks like this: http://example.com/folder/
You can do it like this, but sorry my english is not good enough.
First, get home base url with this simple code..
I've tested this code on my local server and public and the result is good.
<?php
function home_base_url(){
// first get http protocol if http or https
$base_url = (isset($_SERVER['HTTPS']) &&
$_SERVER['HTTPS']!='off') ? 'https://' : 'http://';
// get default website root directory
$tmpURL = dirname(__FILE__);
// when use dirname(__FILE__) will return value like this "C:\xampp\htdocs\my_website",
//convert value to http url use string replace,
// replace any backslashes to slash in this case use chr value "92"
$tmpURL = str_replace(chr(92),'/',$tmpURL);
// now replace any same string in $tmpURL value to null or ''
// and will return value like /localhost/my_website/ or just /my_website/
$tmpURL = str_replace($_SERVER['DOCUMENT_ROOT'],'',$tmpURL);
// delete any slash character in first and last of value
$tmpURL = ltrim($tmpURL,'/');
$tmpURL = rtrim($tmpURL, '/');
// check again if we find any slash string in value then we can assume its local machine
if (strpos($tmpURL,'/')){
// explode that value and take only first value
$tmpURL = explode('/',$tmpURL);
$tmpURL = $tmpURL[0];
}
// now last steps
// assign protocol in first value
if ($tmpURL !== $_SERVER['HTTP_HOST'])
// if protocol its http then like this
$base_url .= $_SERVER['HTTP_HOST'].'/'.$tmpURL.'/';
else
// else if protocol is https
$base_url .= $tmpURL.'/';
// give return value
return $base_url;
}
?>
// and test it
echo home_base_url();
output will like this :
local machine : http://localhost/my_website/ or https://myhost/my_website
public : http://www.my_website.com/ or https://www.my_website.com/
use home_base_url function at index.php of your website and define it
and then you can use this function to load scripts, css and content via url like
<?php
echo '<script type="text/javascript" src="'.home_base_url().'js/script.js"></script>'."\n";
?>
will create output like this :
<script type="text/javascript" src="http://www.my_website.com/js/script.js"></script>
and if this script works fine,,!
I found this on
http://webcheatsheet.com/php/get_current_page_url.php
Add the following code to a page:
<?php
function curPageURL() {
$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"];
}
return $pageURL;
}
?>
You can now get the current page URL using the line:
<?php
echo curPageURL();
?>
Sometimes it is needed to get the page name only. The following example shows how to do it:
<?php
function curPageName() {
return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
}
echo "The current page name is ".curPageName();
?>
$http = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'? "https://" : "http://";
$url = $http . $_SERVER["SERVER_NAME"] . $_SERVER['REQUEST_URI'];
Try this. It works for me.
/*url.php file*/
trait URL {
private $url = '';
private $current_url = '';
public $get = '';
function __construct()
{
$this->url = $_SERVER['SERVER_NAME'];
$this->current_url = $_SERVER['REQUEST_URI'];
$clean_server = str_replace('', $this->url, $this->current_url);
$clean_server = explode('/', $clean_server);
$this->get = array('base_url' => "/".$clean_server[1]);
}
}
Use like this:
<?php
/*
Test file
Tested for links:
http://localhost/index.php
http://localhost/
http://localhost/index.php/
http://localhost/url/index.php
http://localhost/url/index.php/
http://localhost/url/ab
http://localhost/url/ab/c
*/
require_once 'sys/url.php';
class Home
{
use URL;
}
$h = new Home();
?>
Base
This is the best method i think so.
$base_url = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != "off") ? "https" : "http");
$base_url .= "://".$_SERVER['HTTP_HOST'];
$base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
echo $base_url;
The following solution will work even when the current url has request query string.
<?php
function baseUrl($file=__FILE__){
$currentFile = array_reverse(explode(DIRECTORY_SEPARATOR,$file))[0];
if(!empty($_SERVER['QUERY_STRING'])){
$currentFile.='?'.$_SERVER['QUERY_STRING'];
}
$protocol = $_SERVER['PROTOCOL'] == isset($_SERVER['HTTPS']) &&
!empty($_SERVER['HTTPS']) ? 'https' : 'http';
$url = "$protocol://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$url = str_replace($currentFile, '', $url);
return $url;
}
The calling file will provide the __FILE__ as param
<?= baseUrl(__FILE__)?>
Here's one I just put together that works for me. It will return an array with 2 elements. The first element is everything before the ? and the second is an array containing all of the query string variables in an associative array.
function disectURL()
{
$arr = array();
$a = explode('?',sprintf(
"%s://%s%s",
isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
$_SERVER['SERVER_NAME'],
$_SERVER['REQUEST_URI']
));
$arr['base_url'] = $a[0];
$arr['query_string'] = [];
if(sizeof($a) == 2)
{
$b = explode('&', $a[1]);
$qs = array();
foreach ($b as $c)
{
$d = explode('=', $c);
$qs[$d[0]] = $d[1];
}
$arr['query_string'] = (count($qs)) ? $qs : '';
}
return $arr;
}
Note: This is an expansion of the answer provided by maček above. (Credit where credit is due.)
Edited at #user3832931 's answer to include server port..
to form URLs like 'https://localhost:8000/folder/'
$base_url="http://".$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].dirname($_SERVER["REQUEST_URI"].'?').'/';
Try using: $_SERVER['SERVER_NAME'];
I used it to echo the base url of my site to link my css.
<link href="//<?php echo $_SERVER['SERVER_NAME']; ?>/assets/css/your-stylesheet.css" rel="stylesheet" type="text/css">
Hope this helps!
$some_variable = substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['REQUEST_URI'], "/")+1);
and you get
something like
lalala/tralala/something/
In my case I needed the base URL similar to the RewriteBasecontained in the .htaccess file.
Unfortunately simply retrieving the RewriteBase from the .htaccess file is impossible with PHP. But it is possible to set an environment variable in the .htaccess file and then retrieve that variable in PHP. Just check these bits of code out:
.htaccess
SetEnv BASE_PATH /
index.php
Now I use this in the base tag of the template (in the head section of the page):
<base href="<?php echo ! empty( getenv( 'BASE_PATH' ) ) ? getenv( 'BASE_PATH' ) : '/'; ?>"/>
So if the variable was not empty, we use it. Otherwise fallback to / as default base path.
Based on the environment the base url will always be correct. I use / as the base url on local and production websites. But /foldername/ for on the staging environment.
They all had their own .htaccess in the first place because the RewriteBase was different. So this solution works for me.
Currently this is the proper answer:
$baseUrl = $_SERVER['REQUEST_SCHEME'];
$baseUrl .= '://'.$_SERVER['HTTP_HOST'];
You might want to add a / to the end. Or you might want to add
$baseUrl .= $_SERVER['REQUEST_URI'];
so in total copy paste
$baseUrl = $_SERVER['REQUEST_SCHEME']
. '://' . $_SERVER['HTTP_HOST']
. $_SERVER['REQUEST_URI'];
function server_url(){
$server ="";
if(isset($_SERVER['SERVER_NAME'])){
$server = sprintf("%s://%s%s", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['SERVER_NAME'], '/');
}
else{
$server = sprintf("%s://%s%s", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['SERVER_ADDR'], '/');
}
print $server;
}
I had the same question as the OP, but maybe a different requirement. I created this function...
/**
* Get the base URL of the current page. For example, if the current page URL is
* "https://example.com/dir/example.php?whatever" this function will return
* "https://example.com/dir/" .
*
* #return string The base URL of the current page.
*/
function get_base_url() {
$protocol = filter_input(INPUT_SERVER, 'HTTPS');
if (empty($protocol)) {
$protocol = "http";
}
$host = filter_input(INPUT_SERVER, 'HTTP_HOST');
$request_uri_full = filter_input(INPUT_SERVER, 'REQUEST_URI');
$last_slash_pos = strrpos($request_uri_full, "/");
if ($last_slash_pos === FALSE) {
$request_uri_sub = $request_uri_full;
}
else {
$request_uri_sub = substr($request_uri_full, 0, $last_slash_pos + 1);
}
return $protocol . "://" . $host . $request_uri_sub;
}
...which, incidentally, I use to help create absolute URLs that should be used for redirecting.
Just test and get the result.
// output: /myproject/index.php
$currentPath = $_SERVER['PHP_SELF'];
// output: Array ( [dirname] => /myproject [basename] => index.php [extension] => php [filename] => index )
$pathInfo = pathinfo($currentPath);
// output: localhost
$hostName = $_SERVER['HTTP_HOST'];
// output: http://
$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https://'?'https://':'http://';
// return: http://localhost/myproject/
echo $protocol.$hostName.$pathInfo['dirname']."/";
$http = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'? "https://" : "http://";
$dir = str_replace(basename($_SERVER['SCRIPT_NAME']), '',$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME']);
echo $url = $http . $dir;
// echo $url = $http . $_SERVER["SERVER_NAME"] . $_SERVER['REQUEST_URI'];

Categories