How to reliably get the current URL in PHP? [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I get current page full URL in PHP
I want to do something like this:
if (current url is 'site.com/dir1')
do something;
else if (current url is 'site.com')
do something else;
What's a reliable way to find this out? Thanks.

You can synthesise it with:
'http' . (443 == $_SERVER['SERVER_PORT'] ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
For IIS you don't get REQUEST_URI:
if (!isset($_SERVER['REQUEST_URI'])) {
$_SERVER['REQUEST_URI'] = substr($_SERVER['PHP_SELF'], 1);
if (isset($_SERVER['QUERY_STRING'])) {
$_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING'];
}
}

Use $_SERVER['REQUEST_URI']. This should give you the URL that the visitor is using.

if($_SERVER['REQUEST_URI']=="url"){}
Should do the trick.

Related

PHP Replace basename in the URL

I have this function.
function getCallbackUrl(){
$protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
return $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . 'response.php';
}
On my URL http://localhost/gateways/payu/index.php the above function displays URL like this http://localhost/gateways/payu/index.phpresponse.php. No idea why it is happening. The function seems correct to me. Maybe I am missing out something that I am not able to replace the base name from index.php to response.php. Any help would be truely appreciated. Thank you :)
Currently, your $_SERVER['REQUEST_URI'] itself has index.php, hence you are facing this issue, where response.php is concatenated instead of replacing. A quick fix is as below:
$_SERVER['REQUEST_URI'] = str_replace(basename($_SERVER['REQUEST_URI']),'response.php',$_SERVER['REQUEST_URI']);
return $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
You can also use a combination of parse_url(),str_replace() and basename() to achieve this.
Parse the url and get the URI path.
Get the basename of the URI.
Replace it with the one you want to.
Join these pieces together and return the URL.
Snippet:
<?php
function getCallbackUrl($url,$replacement_file){
$url_data = parse_url($url);
$url_data['path'] = str_replace(basename($url_data['path']),$replacement_file,$url_data['path']);
$url = $url_data['scheme'] . "://" . $url_data['host'] . $url_data['path'];
if(!empty($url_data['query'])) $url .= '?' . $url_data['query'];
return $url;
}
echo getCallbackUrl('http://localhost/gateways/payu/index.php','response.php');

Get url from script usage

So i'm writing a script in PHP which generates a image so other people can use it too.
But is it possible to get the url's on the pages the scripts are used ?
For example.
http://www.johnexample.com is using my image with this format
<img src="http://www.myurl.com/image.php">
Now i wan't to receive the url of http://www.johnexample.com without GET variables if possible.
It's basically a script that's suppose to track/note down all the websites that are using my image.
At first i though it was possible with this:
$url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
But that only get's the location of the script itself.
Thanks
Oh, that was simpler than i though.
Got it working like this now.
The page with the tag only has to load once and it will save.
Only using Session now because it's being tested local.
Gonna switch it over to a database.
Thanks guys
<?php
session_start();
$url = $_SERVER["HTTP_REFERER"];
if(!strpos($_SESSION["url"], $url)) {
if($url != '') {
$_SESSION["url"] = $_SESSION["url"] . "," . $url;
}
}
$tracker = explode(",", $_SESSION["url"]);
var_dump($tracker);
?>

PHP URL Directory

If the URL is the following :
If: http://www.imvu-e.com/products/dnr/
Then: http://www.imvu-e.com/products/dnr/
If: http://www.imvu-e.com/products/dnr/?
Then: http://www.imvu-e.com/products/dnr/
If: http://www.imvu-e.com/products/dnr/index.php
Then: http://www.imvu-e.com/products/dnr/
If: http://www.imvu-e.com/products/dnr/page.php?var=2
Then: http://www.imvu-e.com/products/dnr/
If: http://www.imvu-e.com/products/dnr
Then: http://www.imvu-e.com/products/
How can I do this?
My attempt:
print "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['REQUEST_URI'])."/";
Have a look at parse_url() function.
It returns anything you need.
Simply print_r() the result from parse_url to see what you get back.
You probably want something like:
$ARRurlParts = parse_url($orgurl);
$newURL = $ARRelem["scheme"].
"://".$ARRelem["host"].
((isset($ARRelem["port"]))?":".$ARRelem["port"]:"").
$ARRelem["path"];
The issue with your "attempt" is that $_SERVER['REQUEST_URI'] will contain everything the user passed, including index.php and question mark and possibly more. In order to get what you are after, you need to parse the $_SERVER['REQUEST_URI']:
If it ends with a slash /, leave it as it it
Otherwise, find the last slash in the string and take the substring from the beginning up to and including this slash
Finally append the result onto the http:// (or https:// with the domain name)
Ended up going with this
$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
$protocol = substr(strtolower($_SERVER["SERVER_PROTOCOL"]), 0, strpos(strtolower($_SERVER["SERVER_PROTOCOL"]), "/")) . $s;
$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
$address = $protocol . "://" . $_SERVER['SERVER_NAME'] . $port . $_SERVER['REQUEST_URI'];
$parseUrl = parse_url(trim($address));
$parent = (substr($parseUrl['path'], -1) == '/') ? $parseUrl['path'] : dirname($parseUrl['path']) . "/";
return $parseUrl['scheme'] . '://' . $parseUrl['host'] . $parseUrl['port'] . $parent;
Inspired in part by Erwin Moller's answer (Why I voted it) and snipplets across web.
You can strip everything from the last backslash till the end of the string. I am pretty sure that dirname($_SERVER['REQUEST_URI']) won't do the job. You can also try using dirname($_SERVER['SCRIPT_FILENAME']). The last shoud work if you don't have some fancy .htaccess rewrite rules.

How to retrieve complete URL from address bar using PHP? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to get full URL on the address bar using PHP
I use this function, but it does not work all the time. Can anyone give a hint?
function sofa_get_uri() {
$host = $_SERVER['SERVER_NAME'];
$self = $_SERVER["REQUEST_URI"];
$query = !empty($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : null;
$ref = !empty($query) ? "http://$host$self?$query" : "http://$host$self";
return $ref;
}
I want to retrieve the link in address bar (exactly) to use it to refer user back when he sign out. The urls are different:
http://domain.com/sample/address/?arg=bla
http://domain.com/?show=bla&act=bla&view=bla
http://domain.com/nice/permalinks/setup
But I can't get a function that works on all cases and give me the true referrer.
Hint please.
How about this?
function getAddress() {
$protocol = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
return $protocol.'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
}
echo getAddress();
You could use functions above to retrieve URL till GET parameters.
So You have string like = 'localhost/site/tmp' (example).
After that you could just loop through GET parameters if can't get anything else to work.
Add '?' at the end of string manually.
$str = 'localhost/site/tmp/?'
foreach ($_GET as $key => $value) {
$str .= $key.'='.$value.'&';
}
substr_replace($str, "", -1);
echo $str;
At the end You are deleting last symbol which is '&' and is not needed.

How to trim $_SERVER['HTTP_REFERER']

After from processing i am sending the user on the previous page using:
header('Location: ' . $_SERVER['HTTP_REFERER'] . '?Add=Successful');
Now it sends me to my add.php:
http://localhost/add.php?Add=Successful
Again when i add one more data the header location passes the following:
http://localhost/add.php?Add=Successful?Add=Successful
What i want is to trim the header location till question mark:
Lets say something like trimming the $_SERVER['HTTP_REFERER'] till ? and saving it into a variable so that if keyword ? exists it should trim it again to http://localhost/add.php and then pass that variable into header location, so that it can become something like this:
header('Location: ' . $trimmedHeader . '?Add=Successful');
You can also use PHP parse_url() function.
$url = parse_url($_SERVER['HTTP_REFERER']);
$trimmedHeader = $url['scheme'] . '://' . $url['host'] . $url['path'];
header('Location: ' . $trimmedHeader . '?Add=Successful');
This will return you everything before the first question mark in the string.
$trimmedheader = array_shift(explode("?", $_SERVER['HTTP_REFERER']));
$urlArray = parse_url($_SERVER['HTTP_REFERER']);
$newUrl = $urlArray['scheme'].'://'.$urlArray['host'].$urlArray['path'].'?Add=Successful';
header("Location: $newUrl");
This has been tested and works fine....
preg_replace('/(.*)\?/',$_SERVER['HTTP_REFERER'],'\1');

Categories