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

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

Related

Redirecting a page Based on URL Value

I am trying to redirecting my register page to https:// based on parse url value.Below is my code
$url = $current_url="//".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$parts = parse_url($url);
parse_str($parts['query'], $query);
if ($query['view']=='register') {
$porthttp = "https://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
header("Location: " . $porthttp);
exit();
}
But it is giving error 'server is redirecting the request for this address in a way that will never complete.'
what's wrong i am doing?
You are redirecting on same page which you accessing so it will not work.
I.e http://localhost/demo/test.php?view=register and you are checking condition like if ($query['view']=='register') {} then you are redirecting on same page using $_SERVER['REQUEST_URI'] so it will go to infinite loop.

Header already sent after form redirect

Header already sent after form submission, I'm using a redirect to take my form elements to a new page to process them, but i'm getting the header Headers ALready Sent error and I cannot see why.
Is there an better cleaner way to do this?
if(isset($_POST["associate"])) {
$partner = $_POST['partner'];
$location = $_POST['location'];
$redirect = plugins_url() . "/myremovalsquote/inc/associate.php?partner=" . $partner . "&location=" . $location . "";
header('Location: '.$redirect);
} else {
echo 'Failed';
}
Are you using wordpress? Than the problem is maybe caused by plugins_url (). When the error still occurs please double check that there is no data sent to the client (e.g <html> or even a whitespace) before header () is used.

I cannot resolve "redirect loop"

This webpage has a redirect loop.
The above has been discussed and answered broadly here but, after following the recommendations found here I still cannot resolve problem with "header("Location:...)".
The code is executed when user clicks a "forgotten password" link in email. The link has random string attached to it like ".../?trs=randomstringstoredindatabase".
When code executes:
if string is valid I get the following results:
Case with code lines "header...;: & "exit;" uncommented:
URL in browser: http://localhost/pl_00_00/pl_process_forgot_password_back.php/pl_reset_password.php/index.php
Chrome displays: This webpage has a redirect loop
Case with code lines "header...;: & "exit;" commented out:
URL in browser: http://localhost/pl_00_00/pl_process_forgot_password_back.php/?trs=015df6fcf5bdcd4d9a339d5ca79d27a7 - correct
Chrome displays echo: "Redirect to: pl_reset_password.php/?memid=11" - as expected
otherwise (string not valid):
Case with code lines "header...;: & "exit;" uncommented:
URL in browser: http://localhost/pl_00_00/pl_process_forgot_password_back.php/index.php
Chrome displays: This webpage has a redirect loop
Case with code lines "header...;: & "exit;" commented out:
URL in browser: http://localhost/pl_00_00/pl_process_forgot_password_back.php/?trs=015df6fcf5bdcd4d9a339d5ca79d27a
Chrome displays echo: "Redirect to: index.php" - as expected
So, when not using "header()" function the logic seems correct. As soon as I uncomment "header()" & "exit" and comment out echos and var_dumps, the problem appears and redirections are not happening. Here is the code I use (PASSWORD_RESET_PAGE & HOME_PAGE are constants defined elsewhere and both do not have function "header ("Location...")" that could cause redirect loop in them):
<?php
# pl_process_forgot_password_back.php
require_once ("lib/required.php");
# $_GET the string from url check and if matches, active and not expired display password change form
$trs_from_email = $_GET['trs'];
# retrieve user data
$query = "SELECT * FROM tbl_member WHERE temporary_random_string = '" . $trs_from_email . "'";
$data_retrieved = sql_get_results_array($query); # retrieve data
if (db_affected_rows() == 1) { # string matched - 1 row selected
if ($data_retrieved[0]['random_string_active']){ # string active
if ($data_retrieved[0]['random_string_expiry'] > time()){ # string not expired
# all ok - display reset password form
header ( "Location: " . PASSWORD_RESET_PAGE . '/?memid=' . $data_retrieved['id'] ); # send them to page with reset-password form
exit;
echo '<br>' . '# all ok - display reset password form';
echo '<br>' . 'Redirect to: ' . PASSWORD_RESET_PAGE . '/?memid=' . $data_retrieved[0]['id'];
var_dump($_SESSION);
var_dump($data_retrieved);
die;
} else { # string expired
$_SESSION['popup_msg_id'] = 17; # this is to popup request expiry message
} # /if string not expired
} else { # string inactive
$_SESSION['popup_msg_id'] = 18; # request already processed message
} # /if string active
} else { # string not matched
$_SESSION['popup_msg_id'] = 19; # string not matched message
} # /if valid string found
header ( "Location: " . HOME_PAGE ); # send them to homepage and display popup error
exit;
echo '<br>' . '# some error';
echo '<br>' . 'Redirect to: ' . HOME_PAGE;
var_dump($_SESSION);
var_dump($data_retrieved);
die;
?>
Can anybody see why the above code is causing the "redirect loop"?
Keep in mind that die and exit are equivalent, so pick one.
The script will not continue to execute after die or exit is hit in the script. Because of this you are cutting off your echo statements and var_dumps, which should be before header if you want them to be seen, but a redirect can be pretty quick which means they may not be seen at all.
a redirect loop can happen if you are redirecting to the same page that you are currently on or if you keep redirecting the user on subsequent pages. If you are sure this is not the case then you need to remove all the cookies and browser cache associated with your site which should fix the problem.
The following sample and place your code in the correct order.
<?php
# pl_process_forgot_password_back.php
require_once ("lib/required.php");
# $_GET the string from url check and if matches, active and not expired display password change form
$trs_from_email = $_GET['trs'];
# retrieve user data
$query = "SELECT * FROM tbl_member WHERE temporary_random_string = '" . $trs_from_email . "'";
$data_retrieved = sql_get_results_array($query); # retrieve data
if (db_affected_rows() == 1) { # string matched - 1 row selected
if ($data_retrieved[0]['random_string_active']){ # string active
if ($data_retrieved[0]['random_string_expiry'] > time()){ # string not expired
# all ok - display reset password form
echo '<br>' . '# all ok - display reset password form';
echo '<br>' . 'Redirect to: ' . PASSWORD_RESET_PAGE . '/?memid=' . $data_retrieved[0]['id'];
var_dump($_SESSION);
var_dump($data_retrieved);
header ( "Location: " . PASSWORD_RESET_PAGE . '/?memid=' . $data_retrieved['id'] ); # send them to page with reset-password form
exit;
} else { # string expired
$_SESSION['popup_msg_id'] = 17; # this is to popup request expiry message
} # /if string not expired
} else { # string inactive
$_SESSION['popup_msg_id'] = 18; # request already processed message
} # /if string active
} else { # string not matched
$_SESSION['popup_msg_id'] = 19; # string not matched message
} # /if valid string found
echo '<br>' . '# some error';
echo '<br>' . 'Redirect to: ' . HOME_PAGE;
var_dump($_SESSION);
var_dump($data_retrieved);
header ( "Location: " . HOME_PAGE ); # send them to homepage and display popup error
exit;
?>

Form redirection with multiple variables

I found a wonderful example on form redirection when there is an error with the form elements. In validation.php the system checks if there is an error and if it's true it redirects the user to the form page.
My question is what if I have more than one form element?
As you see I renamed user_name to app_name and I added a new variable (adtext) so now I get two error messages when both form elements have some error (right now they not equal to a certain word), but I don't know what to do with the $query_string variable so the url would contain the second variable and its value as well.
This is how the url of the form page (adparameters.php) looks like when I click the submit button and there is an error with $appname:
/adparameters.php?appname=aa&error=App%20name%20is%20requiredAd%20text%20is%20required
<?php
# validate.php
$appname = trim($_POST['appname']);
$adtext = trim($_POST['adtext']);
$error = '';
if ($appname != 'myapp') $error = 'App name is required<br />';
if ($adtext != 'mytext') $error = $error . 'Ad text is required<br />';
$query_string = '?appname=' . $appname;
$server_dir = $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\') . '/';
header('HTTP/1.1 303 See Other');
if ($error != '') {
// Back to register page
$next_page = 'adparameters.php';
// Add error message to the query string
$query_string .= '&error=' . $error;
// This message asks the server to redirect to another page
header('Location: http://' . $server_dir . $next_page . $query_string);
}
// If Ok then go to confirmation
else $next_page = 'confirmation.php';
/*
Here is where the PHP sql data insertion code will be
*/
// Redirect to confirmation page
header('Location: http://' . $server_dir . $next_page . $query_string);
?>
The greatness of this code is that if I type something in the first input type object and it doesn't equal 'myapp' it is still filled with the text after redirection. That's what I want with the second object as well.
Best practice would be to send them in a $_SESSION.
session_start();
$_SESSION['form'] = array();
$_SESSION['form']['myapp'] = 'App Error Code';
$_SESSION['form']['adtext'] = 'AdText Error Code';
Then on the new page you would get the values as an array;
session_start();
$form_error = $_SESSION['form']['myapp'];
$form_error = $_SESSION['attext']['myapp'];
If you insist on using GET parameters why not append them on with the & character.
?field1=one&field2=two
I woldn't do it the way you do it but if you want it like that just change few things
if ($appname != 'myapp') $error = 'App name is required<br />';
if ($adtext != 'mytext') $error .= 'Ad text is required<br />';//note contatenation
$query_string = '?appname=' . $appname .'&addtext='.$adtext;

How to trim $_SERVER['HTTP_REFERER']

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

Categories