Issue with PHP header function in Google Chrome - php

After a successful login (i.e when user clicks the login button after entering the username and password), based on the user type I want to send user to a specific page. Below is my code. (Here, if usertype is 'employee', he should be taken to "data-update.php" page after clicking 'login' button.)
This is the code in the index.php page:
// This file is the home page.
// Require the configuration before any PHP code as the configuration controls error reporting:
require ('config.inc.php');
// The config file also starts the session.
// Require the database connection:
require (MYSQL);
// If it's a POST request, handle the login attempt:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
include ('login.inc.php');
}
/* PAGE CONTENT STARTS HERE! */
?>
<!DOCTYPE html>
<html lang="en">
<head>
...
This is the code in the login.inc.php page:
<?php
// This is the login page for the site.
// It's included by index.php, which receives the login form data.
// Array for recording errors:
$login_errors = array();
// Validate the username:
// Validate the password:
if (empty($login_errors)) { // OK to proceed!
// Query the database:
$q = "SELECT id, type FROM users WHERE (username='$u' AND pass='" . get_password_hash($p) . "')";
$r = mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) == 1) { // A match was made.
// Get the data:
$row = mysqli_fetch_array ($r, MYSQLI_NUM);
// Store the data in a session:
$_SESSION['user_id'] = $row[0];
$_SESSION['username'] = $u;
if ($row[1] == 'employee') {
reset_sms_update_session();
header("Location: http://".BASE_URL."data-update.php");
exit;
}
elseif ($row[1] == 'client'){
header("Location: http://".BASE_URL."About.html");
exit;
}
...
And this is a partial code in "data-update.php" page:
// Start the session:
session_start();
function redirect_invalid_user($check = 'user_id', $destination = 'index.php', $protocol = 'http://') {
// Check for the session item:
if (!isset($_SESSION[$check])) {
$url = $protocol . BASE_URL . $destination; // Define the URL.
header("Location: $url");
exit(); // Quit the script.
}
} // End of redirect_invalid_user() function.
//Redirect to index.php if user not logged in
redirect_invalid_user( );
/* PAGE CONTENT STARTS HERE! */
?>
<!DOCTYPE html>
...
The problem is that, in Google Chrome when user clicks the login button, he is first taken to the index.php page (where the redirection occurs) and then he has to click login button again to be taken to "data-update.php" page.
Why is this happening in Google Chrome?
(FYI: this does not happen in XAMP testing environment in my local PC.)
This does NOT happen in Firefox or IE8 (i.e. user is taken to "data-update.php" first time login button is clicked).
Please help.

I solved this by setting a permanent redirect from CPanel in my webserver for http://example.com to http://www.example.com.

Related

implementing both session, cookie in a login form

i'm implementing session, cookie simple from with a remember me check box . i want to use the cookie so the user could see index.php(protected content) i closed the browser to end the session to check if the cookie working and i got the famous error ..redirected you too many . i searched a bit but still stuck so what should i do? and Is what is the best practice to for doing it?
authentication.php
if(mysqli_num_rows($rows) > 0){
$chck_pass = password_verify($clean_password,$user_arr["password"]);
if($chck_pass){
//log in the user
$_SESSION["id"] =$user_arr["id"];
$_SESSION["fristname"] = $user_arr["fristname"];
$_SESSION["email"] = $user_arr["email"];
$_SESSION["verified"]=$user_arr["verified"];
$_SESSION["message"]="Please verify Your Email to Complete Registration";
//make login-id cookie
if(isset($_POST["remmberme"])){
$user=$user_arr['id'];
setcookie("I_user",$user, time() + 1800);
}
header("location:index.php");
exit();
}else{
$errors["login_error"]="Wrong Password";}
}else{
$errors["login_error"]="Wrong Email";
index.php
<?php
include("Authentication.php");
if(!isset($_SESSION["id"]) || !isset($_COOKIE['I_user']) ){
header("location:login.php");
}
?>
login.php
<?php
require_once("config/db_connect.php");
require("Authentication.php");
if(isset($_COOKIE['I_user'])|| isset( $_SESSION['id'])){
header("location:index.php");}
So you login, close your browser. Then open it up again.
You go to index.php and the following line runs
if(!isset($_SESSION["id"]) || !isset($_COOKIE['I_user']) ){
$_SESSION["id"] isn't set, so you redirect to login.php.
On login.php
if(isset($_COOKIE['I_user'])|| isset( $_SESSION['id'])){
$_COOKIE['I_user'] is set, so you redirect to index.php
Repeat forever.

Redirect page after delete account in php

I need a little help here. I have a page profile.php and a option to delete the accound :
// DELETE THE ACCOUNT !!
$_SESSION["delacc"] = FALSE;
if (isset ($_POST ['deleteaccount'])) {
$deleteaccount = $_POST['deleteaccount'];
$delacc="DELETE FROM users WHERE username='$username'";
$resdelacc = mysqli_query($con,$delacc);
if ($resdelacc) {
header('Location: index.php');
$_SESSION["delacc"] = TRUE;
unset($_SESSION['username']);
} else {
echo "ERROR !!! Something were wrong !!";
}
}
the problem is in if ($resdelacc). If this is true, result that the account was deleted, unset session username (logout) and after this I want to redirect the page to index.php where I have the code :
if(isset($_SESSION["delacc"])) {
if($_SESSION["delacc"] == TRUE) {
echo "<b><font color='red'>YOUR ACCOUNT WAS SUCCESFULLY DELETED !!</font></b>";
$_SESSION['delacc'] = FALSE;
}
}
My only problem is that this line " header('Location: index.php');" (from profile.php) don't run in any case. When the user click the button "DELETE ACCOUNT", the page remain profil.php, then, if do refresh or access another page, is redirected and appear as guest.
Very easy .. The reason is after in the resulted output page you can't redirect. so you've prepare it to be redirected after some seconds enough for user to read the result message.
Like this:
if($_SESSION["delacc"] == TRUE) {
$_SESSION['delacc'] = FALSE;
echo '<!DOCTYPE html><html><head><meta http-equiv="refresh" content="7;url=http://'.$_SERVER['HTTP_HOST'].'/index.html"/>';
echo "</head><body>";
echo "<b><font color='red'>YOUR ACCOUNT WAS SUCCESFULLY DELETED !!</font></b>";
}
that change will redirect to the index.html after 7 seconds.
PS. The Generated HTML result page make it starts by this code after the POST handling direct. (before any echo) because echo will start generating the results page and the only logical place to redirect is inside the HEADER before any BODY elements
<meta http-equiv="refresh" content="0";url="/index.php"/>
The redirect (url) don't run for index.php because I have another redirect before :
if(isset($_SESSION['username'])==FALSE) {
header('Location: login.php');
}
but is ok, I put the message "DELETED SUCCESFULLY" in login.php and deleted from index.php . I set content=0, because after deleted, the user will be restricted for page profile.php and need to change immediatelly to another. Due of the verification of SESSION['username'] which can return profile.php, I can not redirect to another page ... is a conflict. I need a little to think better this code with redirects, I know can solve it better :D thanks for explanations and help

Php redirect after successful login

I'm having an issue with a simple verification file, it doesn't redirect to index page after successful login.
Basically the login.php file has the html form for login, the form calls auth.php file which already has the login data and decides if your login and password is correct or not. Now it should redirect to index.php after successful login but it doesn't , instead it just cleans up the form in the login.php file and you keep trying , BUT if you refresh the page ( after successful login ) you get auto redirected to index page.
Fixed! changed the code to something even simpler than that.
if($logindata[$_POST["username"]]==$_POST["password"])
This bit doesn't look correct; maybe you were looking for:
if($logindata[$_POST["password"]]==$_POST["password"])
Sometimes headers does not work well for some reasons, instead try to use a simple html redirect like this:
<?php
$usernames = array("user1", "user2");
$passwords = array("pass1", "pass2");
$page = "index.php";
for($i=0;$i<count($usernames);$i++){
$logindata[$usernames[$i]]=$passwords[$i];
}
$found = 0;
for($i=0;$i<count($usernames);$i++) {
if ($usernames[$i] == $_POST["username"]) {
$found = 1;
}
}
if ($found == 0) {
$redirect_url = "./login.php?login_error=1"
}
if($logindata[$_POST["username"]]==$_POST["password"]) {
session_start();
$_SESSION["username"]=$_POST["username"];
$redirect_url = "./index.php"
}
else {
$redirect_url = "./login.php?login_error=2"
}
echo "<center><br><br><br><p>You will be redirected in about 2 seconds. If not, click this link: <a href='$redirect_url'>Back</a></p></center>";
?>
<html>
<head>
<meta http-equiv="refresh" content="2;url='<?php echo "$redirect_url"; ?>'/>
<title>Redirecting...</title>
</head>
</html>
<?php
exit;
?>
I presumed the redirect location is in the same folder of the php file. Adjust the var $redirect_url path of they aren't.

echo out message after redirect?

I have a button on users profiles that allows another user to add a user to their favorites.
Once this button is clicked they are linked to the sql process file favorite.php.
Once the sql script has run it links the user back to the original profile page which is profile.php.
now what i want to do is find out how i can echo a message on the page profile.php after the sql has completed. I've tried the following but nothing happens.
can someone please show me what i'd need to do to get this working? thank you
favorite.php:
<?php
require_once('includes/session.php');
require_once('includes/functions.php');
require('includes/_config/connection.php');
session_start();
confirm_logged_in();
if (isset ($_GET['to'])) {
$user_to_id = $_GET['to'];
}
if (!isset($_GET['to']))
exit('No user specified.');
$user_id = $_GET['to'];
$result = mysql_query("INSERT INTO ptb_favorites (user_id, favorite_id) VALUES (".$_SESSION['user_id'].", ".$user_to_id.")")
or die(mysql_error());
header("Location: profile.php?id=" . $user_to_id['user_id'] . "added=1");
?>
profile.php:
<?
if (isset($_GET['added']) && $_GET['added'] == 1) {
$message = "<div class=\"infobox\">This user was successfully added to your favorites.</div>"; ?>
<? } ?>
Your redirected URL will look like this:
profile.php?id=123456added=1
# ^
Notice the missing & in the parameters. Adapt your header() call and include it before the "added=1" concat.
header("Location: profile.php?id=" . $user_to_id['user_id'] . "&added=1");
# ^
On a related note, you would have found out earlier if it wasn't for that isset:
if (isset($_GET['added']) && $_GET['added'] == 1) {
Leave it out, as this is a required param and you want to get a note for such occassions. Instead just turn of notices/warnings on your production server.

Login not redirecting properly

I'm trying to get a login on a website where it connects to the database, checks against it, but the redirect isn't working (login.php to loggedin.php). I am appalling at proof reading my own code and have been going round in circles for a while. If someone could assist I would be very grateful! Thank you in advance.
Login_page.inc.php
<?php # Script 11.1 - login_page.inc.php
// this page prints any errors associated with logging in
//and creates te entire login page, including the fom
//include the header:
$page_title = 'Login';
include ('includes/header.html');
//print any error messages if they exist:
if (!empty($errors))
{
echo '<h1>Error!</h1>
<p class="error">The following error(s) occurred:</br>';
foreach ($errors as $msg)
{
echo "- $msg</br>\n";
}
echo '</p><p>Please try again.</p>';
}
//display form
?>
<h1>Login</h1>
<form action=login.php" method="post">
<p>Email Address: <input type="text" name="email" size="20" maxlength="80"/></p>
<p>Password: <input type="password" name="pass" size="20" maxlength="20"/></p>
<p><input type="submit" name="submit" value="Login"/></p>
<input type="hidden" name="submitted" value="TRUE"/>
</form>
<?php //include the footer:
include ('includes/footer.html');
?>
Loggedin.php
<?php # loggedin.php
//this is where the user is directed from login.php
session_start();
//if no cookie is present redirect the user:
//if (!isset($_COOKIE['user_id']))
if (!isset($_SESSION['user_id']))
{
//the functions need to create an absolute url
require_once ('includes/login_functions.inc.php');
$url = absolute_url();
header("Location: $url");
exit(); //exit script
}
//set the page title and include the header
$page_title = 'Logged in.';
include ('includes/header.html');
//welcome message
echo "<h1>Logged in!</h1>
<p>You have successfully logged in, {$_SESSION['first_name']}!</p>
<p>Logout</p>";
include ('includes/footer.html');
?>
Login.php
<?php # login.php
//this page processes the login form submission
//upon successful login the user's redirected
//two include files are needed for this
//send nothing to the web browser prior to the setcookie() lines
//check if the form has been submitted:
if (isset($_POST['submitted']))
{
//for processing the login:
require_once ('includes/login_functions.inc.php');
//need the database connection:
require_once ('includes/mysqli_connect.php');
//check the login
list ($check, $data) = check_login($dbc, $_POST['email'], $_POST['pass']);
if($check)
{
/*ok, set cookies to last one hour after it is set
setcookie ('user_id', $data ['user_id'], time()+3600, '/', '', 0, 0);
setcookie ('first_name', $data ['first_name'], time()+3600, '/', '', 0, 0);*/
session_start();
$_SESSION['user_id'] = $data['user_id'];
$_SESSION['first_name'] = $data['first_name'];
//redirect
$url = absolute_url ('loggedin.php');
header("Location: $url");
exit(); //quit the script
}
else
{
//assign errors to $data for error reporting in the login_page.inc.php
$errors = $data;
}
mysqli_close($dbc); //close the database connection
} //end of main submit condition
include ('includes/login_page.inc.php');
?>
Login_functions.php
<?php #- login_functions.inc.php
//this page defines two functions used by the login/logout process.
/*this function determines and returns an absolte URL
*takes one argument: the page that concludes the URL
*the arguement defaults to index.php
*/
function absolute_url ($page = 'index.php')
{
//start defining the URL. . .
//URL is http:// plus the host name plus current directory:
$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
//remove any trailing slashes:
$url = rtrim($url, '/\\');
//adding the page. . .
$url.= '/' . $page;
//return to the url
return $url;
} //end of the absolute_url function
/* this function validates the form data (the email address and password)
*if both are present the database is queried
*this function requires a database connection
* the function returns an array of information. including:
* - a TRUE or FALSE variable indicating a success or failure
* - an array of either errors or the database return result
*/
function check_login($dbc, $email = '', $pass = '')
{
$errors = array(); //starting error array
//validate email address
if (empty($email))
{
$errors[] = 'You forgot to enter your email address.';
}
else
{
$e = mysqli_real_escape_string($dbc, trim($email));
}
//validate the password
if (empty($pass))
{
$errors[] = 'You forgot to enter your password.';
}
else
{
$p = mysqli_real_escape_string($dbc, trim($pass));
}
if (empty($errors))
{
/*if everything's okay
*retrieve the user_id and the first_name for that
*email+password combination:
*/
$q = "SELECT user_id, first_name FROM site_users WHERE email='$e' AND pass=SHA1('$p')";
$r = #mysqli_query ($dbc, $q); //run the query
//check the result and making sure that both fields are in the same row
if(mysqli_num_rows($r) ==1)
{
//fetch the record
$row = mysqli_fetch_array ($r, MYSQLI_ASSOC);
//return true and the record:
return array(true, $row);
}
else
{
//not a match
$errors[] = 'The email address and password entered do not match those on file.';
}
}//end of empty($errors) IF.
//return false and the errors:
return array(false, $errors);
} //end of check_login() function
?>
If any of the files contains any code that gets sent to the browser, PHP sends all the headers automatically. After the headers have been sent, you can no longer send new headers, and it drops your Location: header. PHP should be throwing a notice, look for it in your logs and/or set the correct error_reporting flags.
This includes newlines or spaces or whatever that is after an ?> tag block.
There is nothing wrong with your script from what i can see ... here but am not sure of the content of
includes/header.html
index.php
You need to also replace
<form action=login.php" method="post">
with
<form action="login.php" method="post">
If you can paste the error you are seeing .. maybe i can help you better
Thanks
:)
Don't include any blank line before your header('Location: $url'). Because this prevents sending header and you are not able to get redirect to place where you want to be.
The issue was within the SHA1 talking to the database, where by SHA1 is a (40) strong and the database was set to (20). An annoying issue but it has not been resolved. Var_dump was used to talk to the database to prove that the information being entered was correct, it did however show that the password held in the database was (20) and the password entered for login was (40).

Categories