php - header() not redirecting to another index page automatically -
when click login.. doesn't automatically redirect me home.php, have refresh page redirect me. i'm guess first header() working fine bc responding page refresh. what's not working second header() inside if statement. doing wrong? thank help.
login.php
<?php session_start(); if($_session['user']!=""){ header("location: home.php"); } include_once 'db.php'; if(isset($_post['login'])){ $uname = mysqli_real_escape_string($conn, $_post['uname']); $upass = mysqli_real_escape_string($conn, $_post['upass']); $sql = "select * users username='$uname'"; $result = $conn->query($sql); $row = $result->fetch_assoc(); if($row['password']==$upass){ $_session['user'] = $row['username']; header("location: home.php"); } else{ echo "unable log in, please try again."; } } ?> <html> <head> <meta charset="utf-8"> </head> <body> <form method="post"> <input type="text" name="uname" placeholder="user name" required /><br> <input type="text" name="upass" placeholder="password" required /><br> <button type="submit" name="login">login</button> </form> </body> </html>
home.php
<?php session_start(); if(isset($_post['logout'])) { session_destroy(); unset($_session['user']); header("location: index.php"); } ?> welcome <?php echo $_session['user'];?> <html> <head> <meta charset="utf-8"> </head> <body> <form method="post"> <button type="submit" name="logout">sign out</button> </form> </body>
db.php
<?php $conn = new mysqli(); $conn->connect('localhost', 'singta', 'lante1', 'wuzzdb'); if ($conn->connect_errno) { echo "failed connect mysql: (" . $conn->connect_errno . ") " . $mysqli->connect_error; } ?>
index.php
<?php session_start(); if($_session['user']!=""){ header("location: home.php"); }else{ echo "you're not logged in"; } ?> <html> <head> <meta charset="utf-8"> </head> <body> <br><br><br> <a href="login.php">login here</a> </body>
a header()
function call sends header browser telling go, not stop execution of php script. after header()
call used redirection should in cases put exit;
directly after it.
<?php session_start(); if($_session['user']!=""){ header("location: home.php"); exit; }
also on second header()
call.
additional note
you should checking $_session['user']
exists before attempting test this
session_start(); if( isset($_session['user']) && $_session['user']!=""){ header("location: home.php"); exit; }
this needs doing whereever test user
in session if not logged in wont exist.
this 1 of problems learning php on live server display of errors turned off. while learning or after, while developing script on live server remember add these 2 lines top of scripts developing
<?php error_reporting(e_all); ini_set('display_errors', 1);
but remember remove when a script working bad form show user kind of error.
Comments
Post a Comment