Domanda

I have a very simple login script.

<?php
    $username = "######";
    $password = "######";
    $hostname = "######";

    $dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");

    $selected = mysql_select_db("logindashboard", $dbhandle);

    $myusername = $_POST['user'];
    $mypassword = $_POST['pass'];

    $myusername = stripslashes($myusername);
    $mypassword = stripslashes($mypassword);

    $query = "SELECT * FROM logindashboard.login WHERE user='$myusername' and pass='$mypassword'";
    $result = mysql_query($query);
    $count = mysql_num_rows($result);

    mysql_close();

    if($count==1){
        $seconds = 5 + time();
        setcookie(loggedin, date("F jS - g:i a"), $seconds);
        header("location:index2.php");
    }else{
        echo 'Incorrect Username or Password';
    }
?>

When users log in and are taken to my homepage. They log in, however the page is set to refresh after 45 seconds using meta refresh.

<META HTTP-EQUIV="REFRESH"CONTENT="45;URL=index2.php">

The only problem with this is, after 45 seconds they appear to be get taken back to the login screen rather than the page they are already on.

This is what I use on the index2.php file at the very top of the page.

<?php require_once('../../../.config2.php'); 
if(!isset($_COOKIE['loggedin'])){
        header("location:index.php");
    }
?>  

Any help would be great!

È stato utile?

Soluzione

first of all your problem is that you don't wrap your loggedin in apostrophes. the line should be look like this, to set the login cookie correctly

setcookie('loggedin', date("F jS - g:i a"), $seconds);

now to your script logic. don't use cookies to check if a user is flagged as loggedin. i don't know any user/password combination and can bypass your script simple by setting manually a cookie with the name loggedIn.

try to use sessions to check if a user is loggedIn. session data is stored server-side and can't manually edited by the client.

like this

// here connect to you db mysql_connect(...
// mysql_select_db(...

$user = mysql_real_escape_string( $_POST['user'] );
$pass = mysql_real_escape_string( $_POST['pass'] );

//query if user and pw is valid
$result = mysql_query("SELECT * FROM logindashboard.login WHERE user='".$user."' and pass='".$pass."'");    

if( mysql_num_rows($result) == 1 ) {

    $_SESSION['loggedIn'] = true;
    header('Location: index2.php');
}

your index2.php would look like this

<?php
session_start();
if( ! $_SESSION['loggedIn'] ) {
    // not logged in redirect direct to login page
    header('Location: loginPage.php');
}

this is much more safer then using cookies. as you see you don't need a meta tag to redirect users. use the php header function to redirect directly users

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top