PHP - Header(location: Blah) Not Redirecting
So I have a site in which a user logs in. When they click the submit button on the login page, it checks to see if a username and password combo exists in an array. If it doesn't exist, the user is supposed to be redirected back to the login page.
This code USED to work, and I think I added one thing completely away from the code that should do any of this, but now it doesn't work any more.
I've read that you can't have anything output before the header code, so I've double checked, and can't find any spaces, echo statements or anything of the like. I've thrown in a random echo statement to see if my if's else's were being entered correctly, and they are. I definitely get into the else statement with the header(location: blah) code when an incorrect username/password is used...
Here's the code I'm looking at. (And there is More HTML under this...)
<?php session_start();?> <?php include("passwords.php"); //this statement will be entered if coming from the login.php page. if ($_POST["ac"]=="log"){ //check if submitted username and password exist in $PASSWORD array if ($PASSWORD[$_POST["username"]]==$_POST["password"]){ //set various session variables $_SESSION["username"]=$_POST["username"]; $_SESSION["firstname"]=$FIRSTNAME[$_POST["username"]]; $_SESSION["lastname"]=$LASTNAME[$_POST["username"]]; $_SESSION["email"]=$EMAIL[$_POST["username"]]; } else{ //if username and password do not exist, set session variable for "incorrect username/password" message and redirect to login.php $_SESSION['incorrect'] = "incorrect"; header('Location: login.php'); }; }; // check if user is logged in already when they are coming from a random place. If not, redirect to login.php check_logged(); ?>Any ideas out there why my header('Location: login.php'); line is not working? Similar TutorialsAs the title says, my headers not redirecting. Login.php: <?php include("global.php"); if (isset($_POST['login'])) { // Form data $email = $_POST['email']; $password = $_POST['password']; // If email and password are both filled in if ($email && $password) { mysql_select_db("social_site") or die("Can\'t find database!"); $query = mysql_query("SELECT * FROM users where email = '$email'"); $numrows = mysql_num_rows($query); // If email in database if ($numrows != 0) { // Login while ($row = mysql_fetch_assoc($query)) { $dbemail = $row['email']; $dbpassword = $row['password']; } if ($email == $email && $password == $dbpassword) { // User is logged in header(' location: index.php '); } else { echo "Incorrect password."; } } else { echo "That email does not exist."; } } else { echo "Please fill in <strong>all</strong> fields."; } } ?> <p> <html> <form action = 'login.php' method = 'POST'> Email: <input type = 'text' name = 'email'> <p> Password: <input type = 'text' name = 'password'> <p> <input type = 'submit' name = 'login' value = 'Login'> </form> </html> Global.php: <?php // This is the global file for the entire website // Start a session session_start(); // Start MySQL connection mysql_connect('localhost', 'root', 'root'); ?> Any ideas? why won't this header redirect? it doesn't seem to like the mysql_close. can i update the database before redirecting to another page? is it possible? Code: [Select] <?php session_start(); $name = "uname"; $lastLogin = date('l jS \of F Y h:i:s A'); require_once('../Connections/uploader.php'); mysql_select_db($database_uploader, $uploader); $query = "SELECT * FROM members WHERE uname='" . $name . "'"; $result = mysql_query($query) or die(mysql_error()); // connect to database here MYSQL_CONNECT($server, $user, $password) or die ("Server unreachable"); MYSQL_SELECT_DB($database) or die ("Database non existent"); if (mysql_num_rows($result) > 0) { $row = mysql_fetch_array($result) or die(mysql_error()); mysql_query("UPDATE members SET lastLogin='$lastLogin' WHERE uname='$name'") // ERROR MESSAGE?? or die(mysql_error()); mysql_close($con); header('Location: redirect.php'); } ?> thanks in advance. Hello I have moved my web site from local machine to a hosted server (Ionos) I seem to be having issues with any code that has redirects or checks if the user is logged in, I just get a blank page, any idea's ? works fine on my local Xamp version two examples below (if I remove the code the page runs)
// We need to use sessions, so you should always start sessions using the below code. session_start(); // If the user is not logged in redirect to the login page... if (!isset($_SESSION['loggedin'])) { header('Location: login.php'); exit(); } ?>
<?php // database connect include('../db_connect.php'); // We need to use sessions, so you should always start sessions using the below code. session_start(); // If the user is not logged in redirect to the login page... if (!isset($_SESSION['loggedin'])) { header('Location: login.php'); exit(); } // if submit button selected run code if(isset($_POST['submit'])){ $_SESSION['district'] = $_POST['district']; header('Location: add_d_choice.php'); } ?> <!DOCTYPE html> <html> <head> </head>
Friends on my few php scripts i used header('Location: somefile.php'); which worked just fine until yesterday the redirects stopped to work, im on a shared web hosting and the hosting people said they made no changes to their server, i tried error reporting but no error shows the pages which should actually do the redirection displays a blank page with no error warnings on it.
what could be the issue any idea?
I was wondering if it's possible to retain loaded files and the current error setttings after a
header("Location: xxxx.php")is issued, for example in this: // Start up the session - not used yet but there just in case session_start(1); // Enable the Autoloader and initialise it require_once 'Autoloader.php'; Autoloader::init(); // Check if the application has been installed yet ---------------------------- if(!file_exists('Engine/config.php')){ session_write_close(); header("Location: install/index.php"); die(); }And I get a class not found error when I open the install/index.php session_start(1); // @todo: Disable this in the production version .... I already did this in the main index -- do I have to do this on all pages that may error? error_reporting(E_ALL & ~E_STRICT); ini_set("display_errors",1); // Because we jumped here, we have to reinstall the autoloader -- why? require_once '../Autoloader.php'; Autoloader::init();While I can understand I wouldn't want this if I was firing off to a completely different site, is there anyway to retain the settings within the same server environment or do I have to reset everything as above. I even tried using session in the hope that this would 'remember' but it didn't work. this little piece of code doesn't seem to work: Code: [Select] if($rs_teamcheck['team_id'] != $team{ header( "Location: http://domain/page.php" ) ;} If I replace the header location part with an echo the output is fine, so why isn't the redirect working? Hi! I'm not a very experienced PHPer. I keep getting this error... Warning: Cannot modify header information - headers already sent by (output started at /home/content/j/2/6/j26183102/html/referral.php:11) in /home/content/j/2/6/j26183102/html/referral.php on line 295 Any suggestions? It works on one server but not my customers godaddy hosting site. Hi Everyone, I'm having a bit of a problem if someone could help me with? I have a simple registration form with fields userid, username, password, clientaddress So when the user logs in with their username and password it will redirect to their client address but I cant get the redirect working. Here is my code: Code: [Select] $clientaddress = trim($_POST['clientaddress']); $_SESSION['start'] = time(); header("Location:$clientaddress"); exit; } also note if I add: Code: [Select] $clientaddress = 'http://www.google.com'; it redirects ok to google. It's getting the field from the database I think thats the problem Can somone help it just wont redirect to the client address Hello everyone. I want to use php to obtain the 'location' value from a header of a url. However, when I use get_headers() it automatically follows the redirect and gives me the header information of the new page. I don't want this, I need the headers of the original page. (I need the value of the 'location' variable in the header). Hope you can help me out. Hi, Im new to all this coding stuff but get by ok with help from the wealth of info on the internet however in this instance i cant solve a PHP redirect issue im having. Ive got a very simple php script to redirect to a secure paypal item link using the header function. header("Location:https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=XYX96W3MSFQZ6"); The problem is when the script is called upon in IE it loops endlessly however works perfectly in Chrome, Firefox, Opera and the Andriod stock browser. I originally tried the redirect directly within the meta tag although this failed on all browsers so now i have the meta tag point to this PHP file. (The meta tag is in a script that submits form data and displays a temporary 'redirecting...' page. Has anyone expirenced this problem before or know of ways to fix it for IE? Could it be an issue with security in IE because the paypal link is secure? Any help would be greatly appreciated. I've made a Login Script and I'm trying to make it re-direct me to the Homepage after the login is complete. However, it's doing nothing at all... Code: [Select] <?php require('./includes/header.php'); require('./includes/functions.php'); ?> <div id="loginHolder"> <div id="title"></div> <h2>Login</h2> <hr /> <?php if(@$_POST['submit_login']) { echo '<div id="loginBox">'; $username = protect($_POST['username']); $password = protect(encrypt($_POST['password'])); $loginCheckQ = mysql_query("SELECT * FROM `users` WHERE `username`='".$username."'"); $loginCheckF = mysql_fetch_assoc($loginCheckQ); $dbusername = $loginCheckF['username']; $dbpassword = $loginCheckF['password']; if($username == $dbusername && $password == $dbpassword) { $_SESSION['loggedUser']=$username; echo '<font color="green">You have successfully logged in as '.$username.'.</font>'; header('location: index.php'); } else { echo '<span>Incorrect Username or Password.</span>'; } echo '</div>'; } ?> <form action="login.php" method="POST" autocomplete="off"> <table cellspacing="0" cellpadding="0"> <tr> <td>Username: </td><td><input type="text" name="username" /></td> </tr> <tr> <td>Password: </td><td><input type="password" name="password" /></td> </tr> <tr> <td colspan="2"><input type="submit" value="Login" class="submit" name="submit_login" /></td> </tr> </table> </form> </div> <?php require('./includes/footer.php'); ?> It works perfectly fine on Localhost, but when I upload it, it doesn't work. I'm trying to rewrite the old jpmaster77 login script that I used back in the day quite extensively, but I'm having problems getting the $form->error messages to the correct page.
Login form, on the index.php:
<div> <h3>Login</h3> <form method="post" action="process.php" id="sublogin"> /* error message should be displayed here when username is empty or == username */ <p> <?php echo $form->error("user"); ?> <input class="loginside" type="text" name="user" value="username" /> ?> <br /> <input class="loginside" type="password" name="pass" value="password" /> <br /> <input type="hidden" name="sublogin" value="1"> <input type="checkbox" name="remember">Remember me <br /> <input class="sublogin" type="submit" value="login" style="border: 0; margin: 5px 0 0 1px;" /> </p> </form> Not registered yet? Sign up here! </div> process.php class Process { /* Class constructor */ function Process(){ global $session; /* User submitted login form */ if(isset($_POST['sublogin'])){ $this->procLogin(); } /** * Should not get here, which means user is viewing this page * by mistake and therefore is redirected. */ else{ header("Location: index.php"); } } function procLogin(){ global $session, $form; /* Login attempt */ $_POST = $session->cleanInput($_POST); $retval = $session->login($_POST['user'], $_POST['pass'], isset($_POST['remember'])); if($retval){ header("Location: correct.php"); } else{ $_SESSION['value_array'] = $_POST; $_SESSION['error_array'] = $form->getErrorArray(); header("Location: index.php"); } /* if instead the $_SESSION and header I enter echo $form->error("user") then the error message is displayed in process.php, and not in index.php */ } } $process = new Process; ?>But when instead the $_SESSION and the header location I enter here echo $form->error("user"); then all is fine. But the error message should not be displayed in the process.php, but rather above the login form on the index.php session.php <?php include "database.php"; include "form.php"; class Session { var $time; function Session(){ $this->time = time(); $this->startSession(); } function startSession(){ $session_name = 'sec_session_id'; // Set a custom session name $secure = true; // This stops JavaScript being able to access the session id. $httponly = true; // Forces sessions to only use cookies. if (ini_set('session.use_only_cookies', 1) === FALSE) { header("Location: ../error.php?err=Could not initiate a safe session (ini_set)"); exit(); } // Gets current cookies params. $cookieParams = session_get_cookie_params(); session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly); // Sets the session name to the one set above. session_name($session_name); session_start(); // Start the PHP session session_regenerate_id(true); // regenerated the session, delete the old one. } function login($subuser, $subpass, $subremember) { global $database, $form; /* username check */ $field = "user"; if(!$subuser || $subuser == "username") { $form->setError($field, "* Username incorrect"); } /* password check */ /* if e-mail welcome, check if user activated account */ /* Return if form errors exist */ if($form->num_errors > 0){ return false; } return true; } function cleanInput($post = array()) { foreach($post as $k => $v){ $post[$k] = trim(htmlspecialchars($v)); } return $post; } }; $session = new Session; $form = new Form; ?> form.php <?php /** * Form.php * * The Form class is meant to simplify the task of keeping * track of errors in user submitted forms and the form * field values that were entered correctly. * * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC) * Last Updated: August 19, 2004 */ class Form { var $values = array(); //Holds submitted form field values var $errors = array(); //Holds submitted form error messages var $num_errors; //The number of errors in submitted form /* Class constructor */ function Form(){ /** * Get form value and error arrays, used when there * is an error with a user-submitted form. */ if(isset($_SESSION['value_array']) && isset($_SESSION['error_array'])){ $this->values = $_SESSION['value_array']; $this->errors = $_SESSION['error_array']; $this->num_errors = count($this->errors); unset($_SESSION['value_array']); unset($_SESSION['error_array']); } else{ $this->num_errors = 0; } } /** * setValue - Records the value typed into the given * form field by the user. */ function setValue($field, $value){ $this->values[$field] = $value; } /** * setError - Records new form error given the form * field name and the error message attached to it. */ function setError($field, $errmsg){ $this->errors[$field] = $errmsg; $this->num_errors = count($this->errors); } /** * value - Returns the value attached to the given * field, if none exists, the empty string is returned. */ function value($field){ if(array_key_exists($field,$this->values)){ return htmlspecialchars(stripslashes($this->values[$field])); }else{ return ""; } } /** * error - Returns the error message attached to the * given field, if none exists, the empty string is returned. */ function error($field){ if(array_key_exists($field,$this->errors)){ return "<font size=\"2\" color=\"#ff0000\">".$this->errors[$field]."</font>"; }else{ return ""; } } /* getErrorArray - Returns the array of error messages */ function getErrorArray(){ return $this->errors; } }; ?>Does anyone know why the $form->error("user") variable cannot be transfered to the index.php? Is something wrong with the session_start or something? thanks in advance guys! Edited by dde, 07 January 2015 - 03:49 PM. Hi, I have a div which reloads every 10 seconds but I want it so that if it equals something then redirect the whole page when at the moment it just loads the whole page in in the div but need the div as it stores all my variables, anyone know of anything else I can use? Thanks I want the page to refresh on with the query string, but this isn't working for me... Code: [Select] header("Location: " . $_SERVER['php_self'] . "?" . $_SERVER['query_string'] ); I dont understand why my header(Location) isnt working. Does any one see why?
<?php include 'core/init.php'; logged_in_redirect(); include 'includes/overall/header.php'; if (empty($_POST) === false) { $required_fields = array('first_name', 'last_name', 'username', 'password', 'password_again', 'email'); foreach($_POST as $key=>$value) { if (empty($value) && in_array($key, $required_fields) === true) { $errors[] = 'All field are required'; break 1; } } if (empty($errors) === true) { if (user_exists($_POST['username']) === true) { $errors[] = 'Sorry, the user \'' . $_POST['username'] . '\' is already taken'; } if (preg_match("/\\s/", $_POST['username']) == true) { $errors[] = 'Your username can not have spaces'; } if (strlen($_POST['password']) < 6) { $errors[] = 'Your password must be at least 6 characters long'; } if ($_POST['password'] !== $_POST['password_again']) { $errors[] = 'Your passwords do not match'; } if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) { $errors[] = 'A valid email address is required'; } if (email_exists($_POST['email']) === true) { $errors[] = 'Sorry, the email \'' . $_POST['email'] . '\' is already is use. Please contact your site adimn is this is incorrect.'; } } } if (isset($_GET['success']) && empty($_GET['success'])) { echo '<div class="container"><div class="background-success text-center"><div class="alert alert-success center-background">You\'ve be registered successfully! Please check your email to activate your account</div><div class="center-background"><div class="center-text-background">if any issues occur please send us an email!! support@bettergamerzunited.com</div></div></div>'; } else { if(empty($_POST) === false && empty($errors) === true) { $register_data = array( 'first_name' => $_POST['first_name'], 'last_name' => $_POST['last_name'], 'username' => $_POST['username'], 'password' => $_POST['password'], 'email' => $_POST['email'], 'email_code' => md5($_POST['username'] + microtime()) ); register_user($register_data); header('Location: register.php?success'); exit(); } ?> <div class="container background"> <form action="" method="POST" class="form-horizontal" role="form"> <div class="form-group"> <label for="inputfirstname3" class="col-sm-2 control-label">First Name</label> <div class="col-sm-10"> <input type="text" name="first_name" class="form-control" id="inputfirstname3" value="" autocomplete="off" placeholder="First Name"> </div> </div> <div class="form-group"> <label for="inputlastname3" class="col-sm-2 control-label">Last Name</label> <div class="col-sm-10"> <input type="text" name="last_name" class="form-control" id="inputlastname3" value="" autocomplete="off" placeholder="Last Name"> </div> </div> <div class="form-group"> <label for="inputusername3" class="col-sm-2 control-label">Username</label> <div class="col-sm-10"> <input type="text" name="username" class="form-control" id="inputusername3" value="" autocomplete="off" placeholder="Username"> </div> </div> <div class="form-group"> <label for="inputemail3" class="col-sm-2 control-label">Email</label> <div class="col-sm-10"> <input type="email" name="email" class="form-control" id="inputemail3" value="" autocomplete="off" placeholder="Email Address"> </div> </div> <div class="form-group"> <label for="inputpassword3" class="col-sm-2 control-label">Password</label> <div class="col-sm-10"> <input type="password" name="password" class="form-control" id="inputpassword3" autocomplete="off" placeholder="Password"> </div> </div> <div class="form-group"> <label for="inputpassword_again3" class="col-sm-2 control-label">Validate Password</label> <div class="col-sm-10"> <input type="password" name="password_again" class="form-control" id="inputpassword_again3" autocomplete="off" placeholder="Validate Password"> </div> </div> <div class="form-group"> <div class="col-sm-10"> <p class="info">Please be aware that this does not mean that you are a member of Better Gamerz United. If you would like to be come a member please contuine with the registration and then fill out our application. Other wise you will have limited use of this site. Thank you Team BGU!! </p> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-primary pull-right register">Register</button> </div> </div> </form> </div> <?php } include 'includes/overall/footer.php'; ?> I'm using jQuery ajax for my login script. However my linked php file with ajax doesn't change the screen with header('location') whats a way to change the page on login using ajax? Thanks I have a form, where I'm collecting registration info - like name, address, email, password. I'm calling another php file at server side code, where it will check whether the email exists or not. Pretty simple, just receiving those post variables and check with the database. The issue, if I find a match, I want to go back to the registration.php page, using the following code: if ($email_already_use == "y") { $_SESSION['ERROR'] = "Error"; $_SESSION['MESSAGE'] = "This email address already used. Please try another"; header("location: ".$settings['site_url']."registration.php"); exit; } Now, I would like to place the user input at the registration.php file, but I do not want to use pass variable at URL like this: header("location: ".$settings['site_url']."registration.php?".name=$name&address=$address&email=$email; Is there anyway, I can retrieve those variables at registration.php, without specifying .name=$name&address=$address&email=$email ? Thanks for your help. I see some sites has similar implementation, but did not find anything like how to do it. Hello, When i want a custom site search i need to process like google "site:600host.net terms" however my php just pulls a blank page when trying to output this i think its to do with : Quote <?php $keywords = $_REQUEST["keywords"]; $keywords2 = "$keywords"; $lowerCase = strtolower($keywords2); header("Location: ".$lowerCase.".html"); ?> Thanks any help appreciated! Hi.. I have query for insert then I just want to add condition that after it save it will locate on the previous page: here is my code: Code: [Select] $sql = "INSERT INTO receiving_materials (sr_date, sr_number, si_num, s_name, po_num, qty, mat_code, mat_desc, wh_code, bin_loc) VALUES ('$sr_date', '$sr_number', '$si_num', '$s_name', '$po_num', '$qty', '$mat_code', '$mat_desc', '$wh_code', '$bin_loc') ON DUPLICATE KEY UPDATE sr_date = '$sr_date', sr_number = '$sr_number', si_num = '$si_num', s_name = '$s_name', po_num = '$po_num', qty = '$qty', mat_code = '$mat_code', mat_desc = '$mat_desc', wh_code = 'wh_code', bin_loc = '$bin_loc'"; $res_receiving = mysql_query($sql, $con) or die(mysql_error()); Thank you For SEO purposes I am told that either 301/302 redirects are better. I use header("Location: $url everywhere, is this 301 or 302 ? Also, I see somewhere that this is the proper way to do it. Code: [Select] header ('HTTP/1.1 301 Moved Permanently'); header ('Location: '.$location); .. what if I didn't use the first line (I have sites all over the place littered with header Location, but have only used the 2nd line)? Would it make a difference - it works that's for sure. |