Intended URL redirect upon form submission - php

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.

Related

Automatically redirect to the PREVIOUS BROWSED page

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.

How to create a redirect page within a query string in javascript?

I have a website which changes the content of the page depending on what the user puts into the url.
There is only one page, but it seems like there are more because of the .htaccess I have used.
The website goes
www.site.com/1 or www.site.com/482
the content then changes depending on what the url is, for example /1 would load content assigned to ID 1 and /482, load data assigned to that of ID 482.
My problem is when the user just goes to www.site.com the page still loads but the youtube clip on the page displays a fuzzy screen with the message 'invalid parameters' which is clearly unprofessional. I want the user to be redirected to a random page within my website (anything from /1 to /999) when they go to www.site.com (when there is no forward slash and a number).
I have this code:
var randomnumber = Math.round((Math.random()) * 999 + 1);
var DATA = window.location.pathname.replace('/', '');
if (typeof DATA == "undefined"){
DATA = randomnumber;
}
but it doesn't seem to change anything
If you want to redirect using javascript, you've got to set location property of window object like this
var randomnumber = Math.round((Math.random()) * 999 + 1);
var DATA = window.location.pathname.replace('/', '');
if ( DATA == ""){
window.location = '/' + randomnumber;
}
You can use php to do the redirect in case Javascript is disabled:
<?php
if (!is_numeric($_SERVER['QUERY_STRING'])){
header("Location: http://www.site.com/?".rand(1,999));
}

Redirect website from within frame PHP

I have a web page, let's call it main.php which displays an image of football field and some players distributed on the field. However, that page uses list.php as a right side frame that loads a list of players.
What happens is, when the user clicks on a player on the field (main.php), let's say on the image of the Goal Keeper (GK), a list of GKs from world wide teams will load in right list fram (list.php). This is by using ajax.
So far we are good.
The current situation is, when session times out and the user clicks on a player from the field, the list on the right does not load, instead, list of players disappears from the list and a message says "Please login" is displayed on the right side frame (list.php)
The objective is, when session times out I want the whole website to redirect to the main page index.php
The problem is, I already put the redirecting code just before the code that is responsible of displaying the message "Please login". But what happened is, the redirection happens from within the frame, so i ended up having main.php displaying the field, and list.php displaying the main page!
Here's the code I added.
$user_id = NSession::get('user_id');
if (!isset($user_id))
{
NSession::removeall();
General::Redirect('index.php');
}
They are using Smarty. and btw, I added the same code to top of main.php, and now if user tries to access main.php without logging in, it will redirect him to the main page, so the code works!
n.b. The project is not mine, it belongs to the company I work in.
And I don't know which code is checking the session, all what I know is, if the user click on a player from the field after the session timeout, the "Please Login" message will be shown in the frame.
I'm guessing the redirect is essentially the same as using a header() function. It isn't possible to specify a target using a php redirect as it is server-side - specifying the target is client-side.
You would need to print something like this to the screen:
<script type="text/javascript">window.open('index.php','_parent');</script>
And that will redirect the user to the index.
Using frames for such purpose is... well... so 80ish...
Anyway, the frames are probably named in such a scenario. This means you can address them, but also that you have to address them. Just loading an url inside the "current" frame does exactly that, which is why your approach won't work.
If you really have to go with that frame based approach, then you will have to use javascript to address all known frames and redirect them.
Maybe you can use some javascript inside of your frame like so :
<script type="text/javascript">
window.top.location = 'YourPage.html';
</script>
Hope this helps
The issue was that the session expires while I'm on main.php. Therefore, any subsequent Ajax requested will fail since all requests requires session to be active.
the problem was that the Ajax request being sent from the IFrame (the IFrame is inside main.php and points to list.php thru Ajax calls) is failing due to session expiry.
So I've fixed this issue by adding another two session checks, one on main.php, list.php using PHP (check for session, if it's there, redirect). And in the main container, main.php, I check for the session via JS, interval Ajax requests to check the session, if session has ended, then use redirect using JS.
PHP:
$user_id = NSession::get('user_id');
if (isset($_POST["checklogin"]))//check loging
{
die(isset($user_id) ? "true" : "false");
}
if (!isset($user_id) || $user_id == "")
{
NSession::removeall();
General::Redirect('login.php');
}
JavaScript:
jQuery(document).ready(function($) {
$(window).focus(function() {
checkSession();
});
});
function checkSession()
{
$.ajax({
type: "POST",
data: {"checklogin": "cl"},
url: "list_players.php",
success: function(result) {
if (result === "false")
{
if (FIELD.showMessage === false)
{
FIELD.showMessage = true;
alert("Your session has been closed\nYou will be redirected to login page now. ");
window.location.href = ("login.php");//incase user clicks OK
}
}
}
});
}

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

How to prevent the "Confirm Form Resubmission" dialog?

How do I clean information in a form after submit so that it does not show this error after a page refresh?
See image (from chrome):
The dialog has the text:
The page that you're looking for used
information that you entered. Returning to that
page might cause any action you took to be
repeated. Do you want to continue?
I want this dialog not to appear.
This method works for me well and I think the simplest way to do this is to use this javascript code inside the reloaded page's HTML.
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
Edit: It's been a few years since I originally posted this answer, and even though I got a few upvotes, I'm not really happy with my previous answer, so I have redone it completely. I hope this helps.
When to use GET and POST:
One way to get rid of this error message is to make your form use GET instead of POST. Just keep in mind that this is not always an appropriate solution (read below).
Always use POST if you are performing an action that you don't want to be repeated, if sensitive information is being transferred or if your form contains either a file upload or the length of all data sent is longer than ~2000 characters.
Examples of when to use POST would include:
A login form
A contact form
A submit payment form
Something that adds, edits or deletes entries from a database
An image uploader (note, if using GET with an <input type="file"> field, only the filename will be sent to the server, which 99.73% of the time is not what you want.)
A form with many fields (which would create a long URL if using GET)
In any of these cases, you don't want people refreshing the page and re-sending the data. If you are sending sensitive information, using GET would not only be inappropriate, it would be a security issue (even if the form is sent by AJAX) since the sensitive item (e.g. user's password) is sent in the URL and will therefore show up in server access logs.
Use GET for basically anything else. This means, when you don't mind if it is repeated, for anything that you could provide a direct link to, when no sensitive information is being transferred, when you are pretty sure your URL lengths are not going to get out of control and when your forms don't have any file uploads.
Examples would include:
Performing a search in a search engine
A navigation form for navigating around the website
Performing one-time actions using a nonce or single use password (such as an "unsubscribe" link in an email).
In these cases POST would be completely inappropriate. Imagine if search engines used POST for their searches. You would receive this message every time you refreshed the page and you wouldn't be able to just copy and paste the results URL to people, they would have to manually fill out the form themselves.
If you use POST:
To me, in most cases even having the "Confirm form resubmission" dialog pop up shows that there is a design flaw. By the very nature of POST being used to perform destructive actions, web designers should prevent users from ever performing them more than once by accidentally (or intentionally) refreshing the page. Many users do not even know what this dialog means and will therefore just click on "Continue". What if that was after a "submit payment" request? Does the payment get sent again?
So what do you do? Fortunately we have the Post/Redirect/Get design pattern. The user submits a POST request to the server, the server redirects the user's browser to another page and that page is then retrieved using GET.
Here is a simple example using PHP:
if(!empty($_POST['username'] && !empty($_POST['password'])) {
$user = new User;
$user->login($_POST['username'], $_POST['password']);
if ($user->isLoggedIn()) {
header("Location: /admin/welcome.php");
exit;
}
else {
header("Location: /login.php?invalid_login");
}
}
Notice how in this example even when the password is incorrect, I am still redirecting back to the login form. To display an invalid login message to the user, just do something like:
if (isset($_GET['invalid_login'])) {
echo "Your username and password combination is invalid";
}
It has nothing to do with your form or the values in it. It gets fired by the browser to prevent the user from repeating the same request with the cached data. If you really need to enable the refreshing of the result page, you should redirect the user, either via PHP (header('Location:result.php');) or other server-side language you're using. Meta tag solution should work also to disable the resending on refresh.
After processing the POST page, redirect the user to the same page.
On
http://test.com/test.php
header('Location: http://test.com/test.php');
This will get rid of the box, as refreshing the page will not resubmit the data.
It seems you are looking for the Post/Redirect/Get pattern.
As another solution you may stop to use redirecting at all.
You may process and render the processing result at once with no POST confirmation alert. You should just manipulate the browser history object:
history.replaceState("", "", "/the/result/page")
See full or short answers
You could try using AJAX calls with jQuery. Like how youtube adds your comment without refreshing. This would remove the problem with refreshing overal.
You'd need to send the info necessary trough the ajax call.
I'll use the youtube comment as example.
$.ajax({
type: 'POST',
url: 'ajax/comment-on-video.php',
data: {
comment: $('#idOfInputField').val();
},
success: function(obj) {
if(obj === 'true') {
//Some code that recreates the inserted comment on the page.
}
}
});
You can now create the file comment-on-video.php and create something like this:
<?php
session_start();
if(isset($_POST['comment'])) {
$comment = mysqli_real_escape_string($db, $_POST['comment']);
//Given you are logged in and store the user id in the session.
$user = $_SESSION['user_id'];
$query = "INSERT INTO `comments` (`comment_text`, `user_id`) VALUES ($comment, $user);";
$result = mysqli_query($db, $query);
if($result) {
echo true;
exit();
}
}
echo false;
exit();
?>
I had a situation where I could not use any of the above answers. My case involved working with search page where users would get "confirm form resubmission" if the clicked back after navigating to any of the search results. I wrote the following javascript which worked around the issue. It isn't a great fix as it is a bit blinky, and it doesn't work on IE8 or earlier. Still, though this might be useful or interesting for someone dealing with this issue.
jQuery(document).ready(function () {
//feature test
if (!history)
return;
var searchBox = jQuery("#searchfield");
//This occurs when the user get here using the back button
if (history.state && history.state.searchTerm != null && history.state.searchTerm != "" && history.state.loaded != null && history.state.loaded == 0) {
searchBox.val(history.state.searchTerm);
//don't chain reloads
history.replaceState({ searchTerm: history.state.searchTerm, page: history.state.page, loaded: 1 }, "", document.URL);
//perform POST
document.getElementById("myForm").submit();
return;
}
//This occurs the first time the user hits this page.
history.replaceState({ searchTerm: searchBox.val(), page: pageNumber, loaded: 0 }, "", document.URL);
});
I found an unorthodox way to accomplish this.
Just put the script page in an iframe. Doing so allows the page to be refreshed, seemingly even on older browsers without the "confirm form resubmission" message ever appearing.
Quick Answer
Use different methods to load the form and save/process form.
Example.
Login.php
Load login form at Login/index
Validate login at Login/validate
On Success
Redirect the user to User/dashboard
On failure
Redirect the user to login/index

Categories