PHP check if referral url is the homepage - php

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'] == '/')

Related

Trying to change a portion of my URL when going to profile page

Short and simple, trying to have a URL like facebook has. www.facebook.com/username . Where do I start? I want to get the username portion when I go to a profile.
Try this code I think this code will solve your issue.
<?php
if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on')
$link = "https";
else
$link = "http";
// Here append the common URL characters.
$link .= "://";
// Append the host(domain name, ip) to the URL.
$link .= $_SERVER['HTTP_HOST'];
// Append the requested resource location to the URL
$uri = $_SERVER['REQUEST_URI'];
$link .= $_SERVER['REQUEST_URI'];
// string start index
$start = strlen($link) - strlen($uri);
$requiredName = substr($link, $start + 1);
echo $requiredName;
?>

Cannot redirect correctly with PHP

I have a blog in a website that I want to redirect.
For example this URL https://example.com/blog/june-2021/name-of-blog-post should redirect to https://example2.com/blog/june-2021/name-of-blog-post
There are hundreds of blog posts so I can't use an array to redirect them one by one.
I'm using Pantheon as the host. I added the script to settings.php.
Currently everything from example.com goes to example2.com, so it's not working correctly.
Here's my script:
$url = $_SERVER['REQUEST_URI'];
$uri_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri_segments = explode('/', $uri_path);
$blog = $uri_segments[0];
$post_date = $uri_segments[1];
$post_name = $uri_segments[2];
if ((stripos($url, "/blog/") === 0) && (php_sapi_name() != "cli")) {
header('HTTP/1.0 301 Moved Permanently'); header("Location: https://example2.com".$blog.$post_date.$post_name);
if (extension_loaded('newrelic')) {
newrelic_name_transaction("redirect");
}
exit(); }
Thanks in advance!
You can check for /blog/ by checking that it is found !== false anywhere in $_SERVER['REQUEST_URI']:
if ((stripos($url, "/blog/") !== false) && (php_sapi_name() != "cli")) {
Or check to see if it is found at the first 0 position of $_SERVER['REQUEST_URI']:
if ((stripos($url, "/blog/") === 0) && (php_sapi_name() != "cli")) {
Notes:
stripos only takes three arguments and you only need the first two.
Location header should consist of a single absolute URI like https://example2.com/blog/june-2021/name-of-blog-post, so you might look at the other $_SERVER variables to construct one.

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.

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

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.

Grabbing Refferer's URL - PHP

I am trying to grab statistics on my site and I need a way in PHP to assign just the referrer URL to a variable. All I want is just the "www" or subdomain, the domain, and the tld... I.E. www.facebook.com instead of http://www.facebook.com/BLAH-BLAH/?blah=blah
Try something like the following:
$referer = $_SERVER['HTTP_REFERER'];
$parts = parse_url($referer);
echo $parts['host']; //should echo example.com, or whatever
<?php
$ref = $_SERVER["HTTP_REFERER"];
$host = null;
if ($ref != null) {
$parse = parse_url($ref);
$host = $parse["host"];
}
?>
and then you have $host to work with

Categories