$_SERVER['HTTP_REFERER'] - how to make if to compare with base url - php

I'm trying to compare value of HTTP_REFERER and my base url . How to do that? If I write it in this way, it doesn't show back button. If I use whole url of my project:
http://localhost/myproject/index.php/home/index
It works, but I want to compare base url - not to write many if conditions for each page. How could I do that?
<?php
if ((isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']) )) {
if ($_SERVER['HTTP_REFERER'] == 'http://localhost:/myproject/') {
echo '<a type="button" onclick="history.back(-1);">Back</a>';
}
}
Edited: In this way it'working but it's showing this warning:
Message: strtolower() expects parameter 1 to be string, array given
How to fix it?
<?php
if ((isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']) )) { $referer = $_SERVER['HTTP_REFERER']; $current = 'localhost:/myproject/';
$ref =parse_url($referer); $my=parse_url($current);
if (strtolower($ref) === strtolower($my)) { echo '<a type="button" onclick="history.back(-1);">Back</a>'; } }

check if in HTTP_REFERER its constains your domain.
if (isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], 'localhost/myproject' !== false))
{
echo '<a type="button" onclick="history.back(-1);">Back</a>';
}

Try the following:
if ((isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']) )) {
$referer = $_SERVER['HTTP_REFERER'];
$current = 'http://localhost:/myproject/'; // Do you mean for the : to be here?
$refererBaseUrl = trim(preg_replace('/\?.*/', '', $referer), '/');
$currentBaseUrl = trim(preg_replace('/\?.*/', '', $current), '/');
if (strtolower($refererBaseUrl) === strtolower($currentBaseUrl)) {
echo '<a type="button" onclick="history.back(-1);">Back</a>';
}
}
This is the basic technique that I use to compare base URLs.
Edit:
How about using parse_url (http://php.net/manual/en/function.parse-url.php) to parse both URLs and compare results?

You can get the base URL using $_SERVER['HTTP_HOST'] you may need to append http/https to the string.
You can also then use $_SERVER['REQUEST_URI'] to get the remainder of the URL.

Related

PHP conditional statement is not working

I have a statement that checks the page's url and marks up a page accordingly, but it only works when my if statement has one option to check for.
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
<?php if (strpos($url, 'events/eventname')!= false) { ?>
~markup~
<? } ?>
If I modify it to check for two possible urls...
<?php if (strpos($url, 'events/eventname')!= false) { ?>
~markup~
<? }else if (strpos($url, 'events/othereventname')!= false) { ?>
~markup~
<? } ?>
... the page won't load. I must be missing something obvious- can someone tell me what is wrong with this function?
*edit: Since it was requested I have included the $url variable and more specific url examples
strpos returns 0 when search substring is in the beginning of the query string. You can replace != to !== to make it work - otherwise php is internally transforming false to zero, which leads to incorrect comparison result.
For example:
<?php
var_dump(strpos('aaa', 'a'));
echo var_dump(strpos('aaa', 'a') === false);
echo var_dump(strpos('aaa', 'a') == false);
Try to use !== comparison just just in case string is at position 0.
Another syntax problem is else if, while you should use elseif.
Try also changing short php tag <? to full one <?php.
Rather than using the strpos() you can get the request uri which is anything after the domain name (ie: www.example.com/foo/bar would give you /foo/bar).
$url = $_SERVER['REQUEST_URI'];
if($url == "/foo/bar") {
// markup
} elseif($url == "/bar/foo") {
// markup
} else {
// markup
}

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.

FILTER_VALIDATE_URL and $_GET, copy string after $_GET parameter

I use:
if (filter_var($_GET['paste_here'], FILTER_VALIDATE_URL)) {
echo ???;
}
And I'd like as soon as user enters a site after .php?paste_here = that specific site to be displayed on echo. But I don't want how to print. Any ideas? Thanks a lot
You should check out if param exists, so:
if (isset($_GET['paste_here']) && filter_var($_GET['paste_here'], FILTER_VALIDATE_URL)) {
echo $_GET['paste_here'];
}

Validate a URL PHP

I've working on a project and in this project i need to check the user input is a valid URL.
I've made a preg_match for all possible characters used on a URL. However, I'm trying to make it show an error if HTTP:// / HTTPS:// is not in front of the URL.
Here is what I've done.
if(preg_match('/[^0-9a-zA-Z.\-\/:?&=#%_]/', $url) || substr($url, 0, 7) != "http://" || substr($url, 0, 8) != "https://") {
But that doesn't work. It keeps giving me the an OK message. I'm not sure what I'm doing wrong here, I hope I can get some help!
The if statement will return true or false. So
if(preg_match('/[^0-9a-zA-Z.\-\/:?&=#%_]/', $url) || substr($url, 0, 7) != "http://" || substr($url, 0, 8) != "https://") {
echo "true";
} else {
echo "false";
}
I just need to check if the url has entered a valid url. I don't need to verify it. Just need to check if it has HTTP:// or HTTPS:// and contains valid URL characters.
Instead of a regex, you could make things easy on yourself and use the URL filtering in filter_var:
if (filter_var($url, FILTER_VALIDATE_URL)) { ...
Alternately you can do this without regex. Though you do also need to validate the url imagine http://">bla</a><script>alert('XSS');</script> as the value passed as there url
<?php
$url = 'http://example.com';
if(in_array(parse_url($url, PHP_URL_SCHEME),array('http','https'))){
if (filter_var($url, FILTER_VALIDATE_URL) !== false) {
//valid url
}else{
//not valid url
}
}else{
//no http or https
}
?>
parse_url()
filter_var()
You've not shown your complete relevant code. So, not sure, why it is not working for you but for url validation, you can check for a detailed discussion on the thread link below:
PHP validation/regex for URL
To validate user input with website url it is good to allow with or without scheme and with or without www, then in view add scheme to set as external url.
$withWww = 'www.' . str_replace(array('www.'), '', $value);
$withScheme = 'http://' . str_replace(array('http://', 'htttps://'), '', $withWww);
$headers = #get_headers($withScheme);
if (strpos($headers[0], '200') === false) {
return false;
}

PHP check if referral url is the homepage

I'm trying to figure out how to check if the referral url to one of my inner pages is the homepage. This would be easy if the homepage was always www.mysite.com/index.php but what happens when it's simply www.mysite.com?
I know I could simply do
$url = $_SERVER['HTTP_REFERER'];
$pos = strrpos($url, "/");
$page = substr($url, $pos+1, (strlen($url)-$pos+1));
if (substr_count($url, 'index')) echo 'from index ';
but I don't have the index.php in my $url variable.
parse_url() can help you here.
// An array of paths that we consider to be the home page
$homePagePaths = array (
'/index.php',
'/'
);
$parts = parse_url($_SERVER['HTTP_REFERER']);
if (empty($parts['path']) || in_array($parts['path'], $homePagePaths)) echo 'from index';
N.B. This should not be relied upon for anything important. The Referer: header may be missing from the request, and can easily be spoofed. All major browsers should do what you expect them to, but hackers and webcrawlers may not.
Use this
if($_SERVER["REQUEST_URI"] == "/" || $_SERVER["REQUEST_URI"] == "/index.php")
echo "Home";
$url = parse_url($_SERVER['HTTP_REFERER']);
$url = explode('/',$url['path']);
if ($url[1]=='index.html'||empty($url[1])) echo 'from index ';
$referer = $_SERVER['HTTP_REFERER'];
$homepage = "index.php";
$ref_array = explode("/", $referer);
if(trim($ref_array[1]) == trim($homepage) || trim($ref_array[1]) == "") echo "From URL";
You should note that yoursite.com/index.php and yoursite.com/ is the same!
This would work:
if ($_SERVER['REQUEST_URI'] == '/')

Categories