1

I am trying to run my little test script, a login panel with PHP.

I want the index.php has a public part that anyone can view, but when a user logs should see the public page plus other data that I get from the database based on data session (for example, Username).

To better understand everything, I will attach a picture of how I want it to work my script (example):

enter image description here

My code is the following:

index.php

<!DOCTYPE html>
<html lang="es">
    <head>
        <title>PHP - Log in - test page</title>
        <style>
            .container{text-align:justify;width:300px;}
            span{font-size:22px;}

        </style>
    </head>
    <body>
    <div class="info">
        <h1>PHP TEST PAGE</h1>
<?php
    if ($login_session == null)
    {
        echo "<span><a href='loginpanel.php'>Log in</a></span>";
    }
    else
    {
        echo "<span>{$login_session}</span>";
        echo "<span><a href='loginpanel.php'>Log out</a></span>";
    }
?>
    <div class="container">
        <p>
            Lorem ipsum dolor sit amet, usu ei mazim exerci everti, quas numquam interesset sed te. Dicunt epicurei moderatius sed at. Integre detraxit quaerendum ut has. Sea ut viderer sensibus.
        </p>
        <p>
            Sed ad idque detraxit probatus, ne feugiat mediocrem eos. Quo an veniam iisque, ignota integre elaboraret vix ut. Et mea ludus aliquid legimus, nam te illud atqui cetero. Tempor feugiat delicatissimi pro ad.
        </p>
    </div>
</body>

loginpanel.php

<?php
    require_once('login.php');
    $error = isset($_GET['error']) ? $_GET['error'] : NULL; 
?>
<!DOCTYPE html>
<html lang="es">
    <head>
        <title>Log in panel</title>
    </head>
    <body>
        <form action="" method="POST">
            <input maxlength='64' name="username" type="user" placeholder="User" required>
            <input maxlength='64' name="password" type="password" placeholder="Pass" required>
            <button type="submit" name="submit">LOG IN</button>
        </form>
        <h4 style="color:crimson;"><?php if ($error == 1){echo "Wrong user or pass";} ?></h4>
    </body>
</html>

conexion.php

<?php
    $connection = new mysqli("127.0.0.1","root","myultrasecureandsecretpassword","mydatabase");
    if (mysqli_connect_errno())
    {
        echo "ERROR; THE APOCALYPSIS IS NEAR!: " . mysqli_connect_error();
    }
?> 

login.php

<?php
    require_once('conexion.php');
    session_start();//starting session
    $error=''; //variable to store error message
    if (isset($_POST['submit']))
    {
        if (empty($_POST['username']) || empty($_POST['password']))
        {
            $error = "user or pass wrong"; 
        }
        else 
        {
            // Define $username and $password 
            $username=$_POST['username']; 
            $password=$_POST['password']; 

            // To protect MySQL injection for Security purpose 
            $username = stripslashes($username);
            $password = stripslashes($password);
            $username = mysqli_real_escape_string($connection, $username);
            $password = mysqli_real_escape_string($connection, $password);

            //SQL query to fetch information of registerd users and finds user match.
            $query=$connection->query("SELECT usuario
                                FROM usuarios
                                WHERE usuario='{$username}' 
                                AND password='{$password}'
                                ");
            $fila=$query->fetch_row();
            $rows = mysqli_num_rows($query);
            if ($rows == 1)
            {
                $_SESSION['login_user']=$username;//Initializing Session
                header("Location: index.php");//Redirecting to other page
            }
            else 
            {
                header("Location: loginpanel.php?error=1");//Redirecting to other page
            }
            //Closing Connection
            mysqli_close($connection);
        }
    }
?>

session.php

<?php
    require_once('conexion.php');
    session_start();// Starting Session
    //Storing session
    $user_check=$_SESSION['login_user'];

    //SQL query to fetch complete information of user
    $ses_sql = $connection->query("SELECT usuario FROM usuarios WHERE usuario='{$user_check}'");
    $row = $ses_sql->fetch_assoc();

    $login_session=$row['usuario'];
    if(!isset($login_session))
    {
        //Closing Connection
        mysqli_close($connection);
        header('Location: index.php');//Redirecting to home page 
    }
?>

logout.php

<?php
    session_start();
    if(session_destroy()) //Destroying all sessions
    {
        header("Location: index.php"); //Redirecting to home page
    }
?>

That's just what I want! How do I can achieve it? What should I change to my code? In my actual code, there is the following error:

Notice: Undefined variable: login_session in C:\xampp\htdocs\testlogin\index.php on line 15

Thanks for reading!

candlejack
  • 1,189
  • 2
  • 22
  • 51
  • 1
    here smacks of arrogance, it's a shame that a site like StackOverflow have users who make such comments. On the other hand, luckily we have true professionals as @David and EricBouwers – candlejack Feb 23 '15 at 19:23
  • Honestly, how much time have you spent to go over your code with the missing variable declaration? Don't slap that "arrogance" declaration on me or anyone else for that matter. I'll take that slap with a grain of salt if you'd of tell us/me: *"I spent about an hour on this, but I still can't figure out why my code is failing on me. Can you guys tell me where I went wrong?"* and not just a simple "how do I do this?" You drop a mountain of code on us, what did you expect? – Funk Forty Niner Feb 23 '15 at 19:34

1 Answers1

3

Notice: Undefined variable: login_session in C:\xampp\htdocs\testlogin\index.php on line 15

Ok, so take a look at line 15 of index.php:

if ($login_session == null)

That's the first line of PHP code in that file. Nowhere is $login_session actually defined. So even without the notice, it's still never going to have a value.

Variables don't hold their value between script executions. Every time a script is executed, it starts from nothing. If you want to persist a value outside of that execution, you need to persist it somewhere. Judging by the name of the variable, you probably want to use a session value.

You'd likely check the value with something like this:

if (isset($_SESSION['login']))

(perhaps also adding a second check for the value itself and not just whether or not it exists)

And you'd write to it with something like this:

$_SESSION['login'] = $row['usuario'];

From one page to the next the code retains no memory of variables. Values need to be persisted somewhere by one page in order to be read by another.

David
  • 208,112
  • 36
  • 198
  • 279
  • 2
    In this case a `require("session.php");` before line 15 should already do the trick. – ebo Feb 23 '15 at 19:10
  • @EricBouwers In the first attempt worked well, but in doing F5, appeared the following error: "The page is not redirecting Properly Firefox has detected That the server is redirecting the request for this address in a way That will never complete This problem can be Caused by: sometimes disabling or Refusing to accept cookies. " – candlejack Feb 23 '15 at 19:26
  • @candlejack: Well, including `session.php` in `index.php` is a bit risky when `session.php` contains the line: `header('Location: index.php');`. It's best to separate common logic from response logic, and a redirect like that is response logic. It should ideally be page-level, not common-file-level. – David Feb 23 '15 at 19:31
  • I see, but then is not possible to do what I want? I want that part of the index public, (not requiring login), but I also want when a usaer log in, the username appearing. – candlejack Feb 23 '15 at 19:36
  • @candlejack: It's absolutely possible to do what you want. Just examine the `$_SESSION` value instead of using an uninitialized variable. – David Feb 23 '15 at 19:37