Automatically redirect to the PREVIOUS BROWSED page - php

I have read some stackoverflow hyperlinks about how to redirect to the previous browsed page after a user logs in or creates a new post in a forum. I have found that most of the answers mentioned about using AJAX or javascript or the like, because most of the answerers think that it should only happen on the client side. Furthermore, most of their codes provided helpfully advised how to redirect to a certain page like index.php after log-in.
For me, what i really want to do now is how to redirect to the previous browsed/visited page after clicking the submit button of the form by using PHP (PLEASE FORGET ABOUT AJAX OR JAVASCRIPT NOW). I don't redirect users to any certain assigned page, but to the page immediately before it. For example, a user visits the index.php, then clicks a hyperlink on it to go to the posts.php page to view the new posts, and then he's interested in the forum, he then goes to the login.php page from the http://domain.com/posts.php?qid=7, for instance, to sign in so that he can reply to the post if he wants to or does something else. In this scenario, after he logs in, the forum would *REDIRECT* him to the immediately previous posts.php page, which is http://domain.com/posts.php?qid=7. That is what I want to code now.
And this is the function I just created:
function str_url($a, $b) {
return substr($a, 0, strpos($a, $b));
}
function self_url() {
if(!isset($_SERVER['REQUEST_URI'])) {
$self = $_SERVER['PHP_SELF'];
}else{
$self = $_SERVER['REQUEST_URI'];
}
$secure = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s":"";
$protocol_secure = str_url(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$secure;
$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
$_SESSION['previous'] = $protocol_secure."://".$_SERVER['SERVER_NAME'].$port.$self;
header("Location: " . $_SESSION['previous']);
}
All I have to do is to place the functions in the head of the document and the self_url(); anywhere within the PHP code after the form checking and submission conditionals that I want.
The problem is that the function self_url(); just checks the domain.com/posts.php to redirect the logged-in users to (it truncates the rest part of the URL), but not the whole long URL of the previously visited page like http://domain.com/posts.php?qid=7 (in which the id=7 is the name=value pair of a certain post) he just visited before he signed in.
Can you help me to isolate the reason, please? Or If you have any handy PHP function to replace mine, I'll appreciate it.

The previous URL might be visible to you via $_SERVER['HTTP_REFERER'] so you could just take this as your redirection target. But this is not very reliable - from the docs:
'HTTP_REFERER'
The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents
will set this, and some provide the ability to modify HTTP_REFERER as
a feature. In short, it cannot really be trusted.
The better approach would be to let the previous script insert a GET parameter of itself so your redirection script knows where the user was before.
Well, you could store every visited page a cookie or session and just read it from there but that doesn't make much sense in my opinion.
//edit some code:
if(!isset($_SERVER['REQUEST_URI'])) {
$self = $_SERVER['PHP_SELF'];
}else{
$self = $_SERVER['REQUEST_URI'];
}
Just append ?redir=$self to the action of your form.

Related

How do I stop people manipulating URLs to submit forms in PHP?

When a user submits any form, a $_GET['variable_name'] is sent by the webpage and will give a URL like the following: www.mywebsite.com/index.php?variable_name_here='yes'.
However people can just write the URL www.mywebsite.com/index.php?variable_name='yes' into the address bar of the website and gain access to this part of the script, without actually submitting the form!
This is a problem! It's breaking specific parts of the script linked to that form submission! This is because the part of the script relating to the $_GET['variable_name'] can't get the variables that should be sent by the form as it is never submitted!
How do I stop people getting to specific parts of a script when they manipulate the URL by sending them back to www.mywebsite.com/index.php?
P.S. : This is for user submitted data through a form which is then processed (no SQL or any alike software involved)
If you are worrying about people getting in to your site without logging in or not having correct params, you should first check to see if the correct $_GET variables exist using isset(). If all paramaters you are expecting exist allow them to pass, otherwise use header('Location: /index.php'); to force a redirect.
To redirect from www.mywebsite.com/index.php?variable_name='yes' to www.mywebsite.com/index.php you would need to include the following code below before you open a HTML header! This solution will work for any $_GET variables within your whole website if you place it within an includes("filename_here"), no need to change the code.
//if there are any $_GET variable(s) set (doesn't matter what the name of the variables are)
if (! empty($_GET))
{
//if there is no record of the previous page viewed on the server
if(! isset($_SERVER['HTTP_REFERER']))
{
//get requested URL by the user
$redir = $_SERVER['PHP_SELF'];
//split parts of the URL by the ?
$redir = explode('?', $redir);
//redirect to the URL before the first ? (this removes all $_GET variables)
header("Location: $redir[0]");
}
}

Detect redirected visitor

Here is the scenario:
Visitor of Page1.php is being redirected with JavaScript to Page2.php
Is there a way to know that visitor which lands on Page2.php is a redirected visitor by monitoring Page2.php if I don't use any sessions and variables at all in any language?
Without Doing/Using:
URL Manipulation
Cookie
Session
Any kind of Variables
Absolutely no changes to Page1.php
I'm asking this because I don't want other sites to detect that I have redirected users to their website.
I just want to know the possibility.
Just set a flag in the query string when you redirect (append the query string to your redirect location):
Page2.php?redirect=1
Or if you need the referring page:
Page2.php?referer=Page1.php
Then check with $_GET['referer']
You might be able to read the $_SERVER['HTTP_REFERER'], but I personally tend to avoid it because it doesn't always contain what you think it should.
If you don't want to use server-side languages, your only alternative is JavaScript. You could redirect to Page2.php?redirected=true and use the following code to GET the redirected variable on Page2.php.
var $_GET = {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
function decode(s) {
return decodeURIComponent(s.split("+").join(" "));
}
$_GET[decode(arguments[1])] = decode(arguments[2]);
});
if($_GET['redirected']){
// Redirected from Page1.php!
}
Source: how to get GET and POST variables with JQuery?
Set a javascript cookie on the initial page when you do the redirect.
On the new page, check to see if the cookie is set, then delete it.

Retrieving referral url application

Let say we've the following
Objective : User will post certain exact URL $refere to lock viewing text content and only be allowed for view if the viwer is coming from the same exact URL $refere.
$refere = "http://www.site_site.com"; // User will post it
$r = $_SERVER['HTTP_REFERER']; // To get real referral
and i want to do the following
<?PHP
if(stripos($r, $refere) == false){
echo "Wrong";
} else { ?>
echo "Go";
}
?>
It always gives me $r = $_SERVER['HTTP_REFERER']; blank ! so does it deprecated on any PHP version 4 or 5 whatever !
Also
what is the user posted $refere like https:// or missed www. or only posted site_site.com while the $r = $_SERVER['HTTP_REFERER']; showing www.site_site.com
so can anyone help me to adjust this code to be working fine no matter the user posted the $refere link fully or only site_site.com.
The $_SERVER['REFERER'] variable will only be set when you click a link to your page from another page and if the browser (or an eventual proxy or firewall you're on) isn't removing the referer header.
To your second question: do some string comparisons. The functions strpos() and substr() will be of great help.

HTTP_REFERER empty when redirected by Auth Component

In CakePHP when you try to access a protect action you are automatically taken to the login form within your app. However the HTTP_REFERER is empty????
$referer = env('HTTP_REFERER');
echo $referer;
So normally when I visit the login page I will see the previous page URL with this code displayed, but if I visit the login page after being taken there by the Auth Component then it will be empty...
why is it empty? as I was just referred???
and how do I get it to acknowledge the redirect as a referal? NOTE: Using the Auth.Redirect session value is not an option in this case because it will stay around after the person has left the site, so for example if they return to the login page it will show the ORIGINAL requested action and NOT the referred page! So it will act as a referral even when its not because it's using the existing session
EDIT:
As an alternate example:
if(isset($_SERVER['HTTP_REFERER'])) {
echo $_SERVER['HTTP_REFERER'];
}
else
{
echo 'their was no referer';
}
When the user is taken to the login form it will say their was no referer but that's obviously not TRUE! ????
HTTP_REFERER is a way of the browser to tell the server what page the user was visiting before. It does not signal what page the user has just been redirected from.
Take for example the Ads on Stackoverflow here. Clicking on one of them will take you to some long URL at adzerk.net, which records your click and then redirects you to the target URL. The intermediate Adzerk page is not an interesting page in itself and the user is never actually seeing it, unless he's paying close attention to the address bar. In fact there isn't even a "page" there. So it doesn't count as a "page visit". The next page will receive stackoverflow.com as the referer, the intermediate redirect page is irrelevant.
Stackoverflow -> Adzerk redirect -> Some advertiser
HTTP_REFERER: stackoverflow.com
There's also no referer at all if you type an address into the address bar. If you're on Stackoverflow and type yahoo.com into the address bar, Yahoo will not see any referer from you. If you click on a link that takes you from Stackoverflow to Yahoo, the browser does send a referer.
In your case, if you directly access a protected action by typing it in the address bar and get redirected, there simply is no previous page you came from.
As per the comments, here how to inject data into the URL while redirecting:
AppController extends Controller {
function redirect($url, $status = null, $exit = true) {
if (is_array($url)) {
$url['?'] = 'redirect=true';
} else {
$url.= '?redirect=true';
}
return parent::redirect($url, $status, $exit);
}
}
Is $_SERVER['HTTP_REFERER'] also empty?
If it is empty it is not set by the server, this means normally there was no referer, you did a simple refresh or called this page via bookmark. See some use cases for referer here: http://www.electrictoolbox.com/php-http-referer-variable/
Have you tried the refer controller?
$refer =
Controller::referer(); // referral url

Intended URL redirect upon form submission

I am working on a WordPress site that has a static squeeze page with the plugin "SplashScreen".
The user can choose from two options:
A.) Enter their email address in the form to proceed to the site.
B.) Click a link located under the field which allows them to bypass giving their email.
Currently as it stands the user is taken to a thank you page upon giving their email, where they can then click a link to get taken to the home page. Or they are taken directly to the home page if they click the bypass link. However, this only works out well if they came to site directly. If they came to the site from a direct link to a specific post or page they will not be taken back to the page they intended to view originally.
What I am looking to do is have them taken directly to that intended page upon filling out the form or by clicking the bypass link. I have looked everywhere for this and all I can find is information on how to redirect a user back to their intended page after logging in. I know how to do that, this is a bit more complex.
The squeeze page is a simple static HTML page that uses Javascript to set the cookies so the page only appears once:
function setCookie(name, value, expires, path, domain, secure) {
document.cookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
function setsplash() {
var exp = new Date();
var expDays = 365;
exp.setTime(exp.getTime() + (expDays * 24 * 60 * 60 * 1000));
setCookie("splash", "1", exp, "/");
}
And:
<input class="sub-btn-join" type="submit" value="" onclick="setsplash()">
I am open to using whatever works, but Javascript or jQuery would be ideal. Hopefully one of you can help me out on this. I have wasted a lot of time on this.
You can do this in three steps:
Temporarily store the user's URL request in that same cookie. You can get the requested URL with PHP http://$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; or JavaScript (document.URL).
Handle the splash check like you already are with the "splash" cookie.
If the originally-attempted URL is not the home/splash page, use PHP again to redirect to it.
<?php
header( 'Location: http://www.example.com/the_page_we_first_wanted.html' ) ;
?>
While I don't see the code in your question, which will redirect the user somewhere, it is possible to redirect him to the correct page by sending a redirect-header with the new Location. The original location may be read from the $_SERVER['HTTP_HOST'] and $_SERVER['REQUEST_URI']. These should be put on the links / target page of the redirect, which may mean you'll have to edit the SplashScreen-Plugin to send this:
header('Location: '.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
Bear in mind, that no headers may be send, when some other content has already been send.

Categories