0

Sorry for a duplicate question, but its not working for me;

access page only if logged in with php

i have to access display.php page if someone loggedin, if they enter the url directly it need to redirect to login.php page, i tried sessions but its not working for me, please help me to debug it.

display.php

    <?php
    session_start();
            if(!isset($_SESSION['loggedin']))
            {
                  header("location: login.php");
            }
    $conn=mysqli_connect("localhost","root","zaq12345","testdb");
    if(!$conn)
    {
    die("Connection failed: " . mysqli_connect_error());
    }
    $disp = "select * from formdata order by user_id desc";
    $result = mysqli_query($conn,$disp);
    ?>
           <button onclick="location.href='formnew1.html';">Add</button>
           <table border="2" cellpadding="0" cellspacing="0">
                  <tr>
                         <th> ID </th>
                         <th> Name </th>
                         <th> Email </th>
                         <th> Age </th>
                         <th> Gender </th>
                         <th> Address </th>
                         <th> City </th>
                         <th> Skills </th>
                         <th>Action</th>
                  </tr>
                  <?php
                         //$rows = mysqli_fetch_assoc($result);
                          while ($row = $result->fetch_assoc())
                          {
                                $id = $row['user_id']; ?>
                                <tr>
                                <td><?php echo $row['user_id']?> </td>
                                <td><?php echo $row['name'] ?></td>
                                <td><?php echo $row['email']?></td>
                                <td><?php echo $row['age']?></td>
                                <td><?php echo $row['gender']?></td>
                                <td><?php echo $row['address']?></td>
                                <td><?php echo $row['city']?></td>
                                <td><?php echo $row['skill']?></td>
                                <td>
                                <a id="edit" href="edit1.php?id=<?php echo $row['user_id']; ?>">Edit</a>
                                <a href="#" id= "<?php echo $row['user_id'] ?>" onclick="deleteRow(this)">Delete</a>
                                </td>
                                </tr>
                     <?php  }  ?>  
           </table>
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
           <script>
           function deleteRow(obj){
                  conf=confirm('Are you sure to delete the Data');
                  if(conf){
                         var tr = $(obj).closest('tr');
                         $.post("delete1.php", {id: obj.id}, function(result){
                               tr.fadeOut('slow', function(){
                               $(obj).remove();
                               });
                         });
                  }
           }
    </script>
    <?php
    if (isset($_SESSION['success']))
    {

            echo '<script> alert("Data Added Successfully");</script>';
            }
    else if (isset($_SESSION['fail'])){
           echo '<script> alert("Failed to Store");</script>';
           //header("Location: /training/formnew.html");
    }
    mysqli_close($conn);
    ?>

login.php

<?php session_start(); ?>
<!DOCTYPE html>
<html>
     <head>
     <style>
        div {
                color: rgb(255,0,0);
            }
       form {
               max-width: 425px;
               margin: 10px auto;
               padding: 10px 20px;
               background: #ff994580;
               border-radius: 10px;
            }
     fieldset {
               margin-top: 100px ;
               margin-bottom: 500px;
               border: none;
               }
     h2        {
            margin: 0 0 30px 0;
            text-align: center;
            font-family: 'Calibri';
            font-size: 40px;
            font-weight: 300;
                }
     label        {

            font-family: 'Calibri';
            font-size: 16px;
            font-weight: 50;
                }
    .submit {
    background-color: #4CAF50;
    border-radius: 10px;
    color: white;
    padding: 10px 40px 10px;
    text-align: center;
    font-size: 16px;
    cursor: pointer;
}
.reset {
    background-color: #ff3333;
    border-radius: 10px;
    color: white;
    padding: 10px 40px 10px;
    text-align: center;
    font-size: 16px;
    cursor: pointer;
}
    </style>
     </head>
<body>
     <fieldset>
<form id="myform" name="myform" method="POST" action="validate.php">
  <H2> LOGIN </H2>
  <table width="60%" cellpadding="10">
        <tr>
            <td>
                <label>User ID</label>
            </td>
            <td>
                <input type="text" id="user_id" name="user_id"placeholder="Enter your User ID" required="required"/> 
            </td>
        </tr>
        <tr>
            <td>
                <label>User Name</label>
            </td>
            <td>
                <input type="text" id="user_name" name="user_name" placeholder="Enter your Username" required="required"/>
            </td>
        </tr>
        <tr>
            <td>
                <label>Password</label>
            </td>
            <td>
                <input type="password" id="password" name="password" placeholder="Enter your Password" required="required"/>
            </td>
        </tr>       
        <tr>
            <td>
                <input type="submit" class="submit" name="submitbtn" value="Login">
            </td>
            <td>
                <input type="reset" class="reset"/>
            </td>
        </tr>
    </table>
</form>
</fieldset>
</script>
</body>
</html>

validate.php

<?php
session_start();
$conn=mysqli_connect("localhost","root","zaq12345","testdb");
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
     $userid=$_POST['user_id'];
     $username=$_POST['user_name'];
     $password=$_POST['password'];
     $qz = "SELECT * FROM userdata WHERE user_id = '$userid' AND user_name = '$username' AND password = '$password'";
     $result=mysqli_query($conn,$qz);
     if(mysqli_num_rows($result) == 1 )
     {
            $_SESSION['loggedin'] = true;
            $_SESSION['user_id'] = $userid;
            header('location: display1.php');  
     }
     else{
          $_SESSION['loggedin'] = false;
          echo '<script> alert("ERROR: Please Check Credentials OR SignUp!!!"); window.location.href="login.php"; </script>';
     }
}
mysqli_close($conn);
?>
Community
  • 1
  • 1
Joseph
  • 11
  • 8
  • i can do login validation with these files. but if i enter the url directly it shows the content – Joseph Apr 12 '17 at 13:19
  • 1
    in validate.php don't use `$_SESSION['loggedin'] = false` just remove it, because you set it even if its false but it is set – M A SIDDIQUI Apr 12 '17 at 13:19
  • Alternatively, you can do `if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] == false)` (since you set it to false in your validate.php if the validation failed). Or, you can do set it to `null` instead of `false`. – Qirel Apr 12 '17 at 13:23
  • *Curious:* Are you going live with this? Edit: I sure hope not. – Funk Forty Niner Apr 12 '17 at 13:23
  • 1
    **Don't store your passwords in plain-text!** This is not secure *at all!* PHP has built-in functions which you should use to handle storing of passwords, see the [`password_hash()`](http://php.net/manual/en/function.password-hash.php) function which is a lot more secure! – Qirel Apr 12 '17 at 13:23
  • You should also take advantage of parameterized queries, which `mysqli_*` offers. Take a look at `mysqli::prepare()` – Qirel Apr 12 '17 at 13:24
  • Where are you destroying that SESSION['loggedin'] information? Because once it'll get set in SESSION array it'll be available throughout the application as long as we'll not destroy it explicitly or restart the the system. – Suresh Apr 12 '17 at 13:24
  • You will also need and `exit;` after the `header()` as a `header()` does not terminate the scripts execution – RiggsFolly Apr 12 '17 at 13:25
  • @Fred-ii- it looks live – Rotimi Apr 12 '17 at 13:26
  • Your script is at risk of [SQL Injection Attack](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Have a look at what happened to [Little Bobby Tables](http://bobby-tables.com/) Even [if you are escaping inputs, its not safe!](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) Use [prepared parameterized statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) – RiggsFolly Apr 12 '17 at 13:26
  • @Akin Well, it probably won't be for long :-( – Funk Forty Niner Apr 12 '17 at 13:26
  • prepared statements have been introduced for a while now and yet @Fred-ii- – Rotimi Apr 12 '17 at 13:27
  • 1
    Surely it cannot be LIVE, OP is using `root` as the user account. **Surely nobody would do that in a LIVE system** :) – RiggsFolly Apr 12 '17 at 13:27
  • @Akin and `password_hash()` / `password_verify()` just to name a few more ;-) – Funk Forty Niner Apr 12 '17 at 13:27
  • @RiggsFolly You'd be surprised – Rotimi Apr 12 '17 at 13:28
  • @RiggsFolly well, maybe they chose their localhost setting to be set as live, who knows. – Funk Forty Niner Apr 12 '17 at 13:28
  • yes its not live, im using in local server – Joseph Apr 12 '17 at 13:30
  • and where to unset sessions – Joseph Apr 12 '17 at 13:30
  • back to the question. Leaving other errors like storing passwords in plain text and others, on the page, why dont you just check if session loggedin is true or false. – Rotimi Apr 12 '17 at 13:39
  • In validate.php you are redirecting the user to display1.php using the function : header('location: display1.php'); . Should it be display.php ? – Nadir Latif Apr 13 '17 at 03:29

1 Answers1

0

Either remove the line $_SESSION['loggedin'] = false; in your validate.php file.

Or change the if statement in your display.php file to be

if (!isset($_SESSION['loggedin'] || !$_SESSION['loggedin'])

You are setting the loggedin to be false, so when you call isset it returns true, because it is set even though it is set to false.

Henry
  • 564
  • 3
  • 22