How to trim $_SERVER['HTTP_REFERER'] - php

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');

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');

How to make sure a parameter "lang" always is present in url without adding it to all links?

I have a simple multi language website. The langauge of the displayed page is controlled by the use of a session variable, but I want users to be able to copy the url and send it to other people and end up on the same language page -- that is I want the "lang" url parameter to be present in the url always.
I could of course edit all links on the page and add it to them, but isn't there an easier way to do this? Is there an alternative solution?
Maybe you can try this:
<?php
//get full url
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
//check if get lang exists.
if(isset($_GET['lang'])){
if($_GET['lang'] == "en"){
//then do nothing.
} else{
//get all parameters.
$query_arr = $_GET;
//chang lang parameter.
$query_arr["lang"] = "en";
$query = http_build_query($query_arr);
$uri_parts = explode('?', $_SERVER['REQUEST_URI'], 2);
//make first part of url.
$first_url = 'http://' . $_SERVER['HTTP_HOST'] . $uri_parts[0];
//redirect to correct url.
header("location: " . $first_url . "?" . $query);
}
}else{
//redirect to correct url.
header("location: " . $url . "&lang=en");
}
?>
Hope this is wat you meant.
You can use something like:
<?php
session_start();
if(isset($_SESSION['lang'])){
$sessionLang = $_SESSION['lang'];
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$rUri = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if(!(isset($_GET['lang']))){
if (strpos($rUri, '?')) { // returns false if '?' isn't there
$newUrl = "$rUri&$sessionLang";
header("Location: $newUrl");
} else {
$newUrl = "$rUri?$sessionLang";
header("Location: $newUrl");
}
}
}
We make sure $_SESSION['lang'] isset.
Get the current url protocol and uri
Check if $_GET['lang'] isn't already set
Check if the url already contains parameters (strpos($_SERVER[REQUEST_URI], '?')), is so,
append &lang=, otherwise append ?lang= to it.

Remove query from URL before $_SERVER['HTTP_REFERER']

On success or fail of a form submission I am using the following. The resulting url appears as http://example.com/directory/?success=false
The problem I am having is that when a user attempts to submit the form again after correcting validation error the resulting url becomes http://example.com/directory/?success=false?success=true - I need it to clear any querystring first. How could I do this?
PHP
# Redirect user to error message
header('Location: ' . $_SERVER['HTTP_REFERER'] . '?success=false');
}
You could use explode() to break the $_SERVER['HTTP_REFERRER'] string to get rid of the existing $_GET arguments:
$bits = explode('?',$_SERVER['HTTP_REFERRER']);
$redirect = $bits[0];
# Redirect user to error message
header('Location: ' . $redirect . '?success=true');
How about something like this:
$i = strchr($_SERVER['HTTP_REFERER'], "?");
$address = substr($_SERVER['HTTP_REFERER'], 0, $i);
header('Location: ' . $address . '?success=false');

Differentiate between Subdomains and Subdirectories

I've got a site that is pretty customized, set up on subdomains; sitename.domain.com and it's got some pages (that are the same for ALL subdomains) sitename.domain.com/this-page. Every single site has "/this-page".
We've got someone interested in using some of the stuff we've developed, but they are MARRIED to using subdirectories; domain.com/sitename which would, of course, have domain.com/sitename/this-page as well.
My question is, I've got some code
$sN = 'http://www.' . $_SERVER['HTTP_HOST'];
$PAGE = $sN . '/this-page/';
but of course this does not work for the subdirectory install (it looks for domain.com/this-page/ instead of domain.com/sitename/this-page
is there a way I can differentiate between subdomains and subdirectories?
$setup = "GET THE HOME PAGE, REGARDLESS OF SETUP"
if($setup ( CONTAINS www.X.X.com)) { //do the code above }
else if ($setup ( CONTAINS www.X.com/X)) { //do different code }
[EDIT] Tried the solution from http://www.php.net/manual/en/reserved.variables.server.php#100881 but didn't work for me, so I did this:
<?php
$sitename = 'sitename';
if (strpos($_SERVER['HTTP_HOST'],$sitename)!==false){
echo 'you are in http://'.$_SERVER['HTTP_HOST'] . '/';
// you are in http://sitename.domain.com/
} else {
$path = explode('/',$_SERVER['PHP_SELF']);
unset ($path[count($path)-1]);
echo 'you are in http://' . $_SERVER['HTTP_HOST'] . implode('/',$path) .'/';
// you are in http://www.domain.com/sitename/
}
?>
The answer from #elcodedocle is the better way of doing this. While they came up with that solution, I had ended up with a (yuckier) solution as well.
//Let's grab the current url for other uses
$cur = 'http://www.' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
//Is this subdomains or subdirectories?
$TYPE = explode('.', $cur);
if(isset($TYPE[3])){
//Yay! It's subdomains! not stupid subdirectories!
$this_root = 'http://www.' . $_SERVER['HTTP_HOST'];
} else {
//Boo.... It's stupid subdirectories.... ;o(
$chunks = explode('/', $TYPE[2]);
$this_root = 'http://www.' .$TYPE[1]. '.' .$chunks[0]. '/' .$chunks[1];
}
?>
This works as well, but it's a less graceful solution. I ended up using a slightly modified version of the code above, but for those of you wondering, this is how I got there before reloading SO. :)

How to pass GET variables from php to php on another server

In a php script I am receiving some data:
$data = $_POST['someData'];
How can I do something like this:
goToThisUrl( "http://someDomain.com/someScript.php?data = ".$data );
or if it is easier how can I do it by POST?
BTW.
This is not happening in a browser, the first php script is getting called by a cart when the order is paid for (if it makes any difference)
Replace goToThisUrl with the real function file_get_contents and remember to urlencode($data) and that would work just fine.
If you want to POST the data instead, look at cURL. Typing "[php] curl post" into the search box will get you the code.
If you want to send the user there, then:
header('Location: http://someDomain.com/someScript.php?data='.$data);
exit;
Or if you just want to call the other server, you can do:
$response = file_get_contents('http://someDomain.com/someScript.php?data='.$data);
Both assume data is already a urlencoded string, you might want to use 'data=' . urlencode($data) or just http_build_query($data) otherwise.
foreach ($_POST as $key => $val) {
$qs = urlencode($key) . "=" . urlencode($val) . "&";
}
$base_url = "<url here>";
$url = $base_url . "?" . $qs;
header('Location: $url'); exit();

Categories