-1

I am new to php and I am facing this problem i tried to solve this but was unable please need your help. I want to make users first login and then access other pages they should not directly access the other pages. when i add the code it is not making users to access other pages without logging in it redirect user to login but it is not working in traditional way like when i put login info it brings back login page.. sorry for bothering here is the code

 <?php
// Start of Login Alert Code
if (!isset($_SESSION['user'])) {
    $_SESSION['msg'] = "You must log in first";
    header('location: login.php');
  }

  if (isset($_GET['logout'])) {
    session_destroy();
    unset($_SESSION['user']);
    header("location: login.php");
  }
  ?>

and here is code of login.php

<?php

if(isset($_POST['Login']))
{
    $user = $_POST['uid'];
    $pwd = $_POST['pass'];
    $query = "SELECT * FROM users WHERE userid='$user' && password='$pwd'";
    $data= mysqli_query($con,$query);
    $total = mysqli_num_rows($data);
if($total==1)
{

 $_SESSION ['user_id']= $user;
    header('location:home.php');


   }

else {
    header('location:error.php');

}

}
?>
  • 1
    Where is `session_start()` – ArtisticPhoenix Feb 05 '19 at 19:40
  • 1
    Make sure you have started a session with session_start() or setting session.auto_start in the php.ini . https://code.tutsplus.com/tutorials/how-to-use-sessions-and-session-variables-in-php--cms-31839 – fbas Feb 05 '19 at 19:40
  • There cannot be __any__ characters before the opening ` – RToyo Feb 05 '19 at 19:40
  • i added session_start() still issue remains same – MaryBeauty2020 Feb 05 '19 at 19:44
  • @RToyo i did'nt get this point of no space before – MaryBeauty2020 Feb 05 '19 at 19:46
  • You should use die or exit after doing a header redirect. Otherwise, the script will continue running. – Robin K Feb 05 '19 at 19:47
  • @MaryBeauty2020 Sure, the space is only in your frist code example. I'll use an underscore to show where the space is: you have `_ – RToyo Feb 05 '19 at 19:52
  • @RToyo thanks! i removed the space can you please help in sorting out this issue.. what is the solution. – MaryBeauty2020 Feb 05 '19 at 19:55
  • @MaryBeauty2020 If that didn't do it, I can't see anything else in your code that looks bad. At this point we're starting to get into the realm of troubleshooting your code, which is outside the scope of StackOverflow (see #1: https://stackoverflow.com/help/on-topic). I would suggest making sure that all errors are being displayed to you (take a look at this answer for how to get errors to display in your script, using `error_reporting` and `ini_set`: https://stackoverflow.com/a/5438125/4458445). Hopefully you'll see an error message that will give you some clues. – RToyo Feb 05 '19 at 20:02
  • I did what was told now it is redirecting but access is open now. – MaryBeauty2020 Feb 05 '19 at 20:05
  • **WARNING**: Writing your own access control layer is not easy and there are many opportunities to get it severely wrong. Please, do not write your own authentication system when any modern [development framework](http://codegeekz.com/best-php-frameworks-for-developers/) like [Laravel](http://laravel.com/) comes with a robust [authentication system](https://laravel.com/docs/master/authentication) built-in. At the absolute least follow [recommended security best practices](http://www.phptherightway.com/#security) and **never store passwords as plain-text** or a weak hash like **SHA1 or MD5**. – tadman Feb 05 '19 at 20:08
  • **WARNING**: When using `mysqli` you should be using [parameterized queries](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to add any data to your query. **DO NOT** use string interpolation or concatenation to accomplish this because you have created a severe [SQL injection bug](http://bobby-tables.com/). **NEVER** put `$_POST`, `$_GET` or data *of any kind* directly into a query, it can be very harmful if someone seeks to exploit your mistake. – tadman Feb 05 '19 at 20:08
  • Note: The object-oriented interface to `mysqli` is significantly less verbose, making code easier to read and audit, and is not easily confused with the obsolete `mysql_query` interface. Before you get too invested in the procedural style it’s worth switching over. Example: `$db = new mysqli(…)` and `$db->prepare("…")` The procedural interface is an artifact from the PHP 4 era when `mysqli` API was introduced and ideally should not be used in new code. – tadman Feb 05 '19 at 20:08
  • 1
    Please try to define both the problem and the desired outcome in clear English. Also try to clearly state the context of both code snippets, and how they are related to each other. – PDiracDelta Feb 05 '19 at 20:36

2 Answers2

1

You are using two different session variables

 isset($_SESSION['user'])

vs

 $_SESSION ['user_id']= $user;

A couple more things to be aware of: your SQL string there is perfect for SQL injection and you should hash the password stored in the database (check the php function password_hash).

David Hayes
  • 196
  • 8
  • Also, the comment from @Harish. – David Hayes Feb 05 '19 at 19:44
  • i added still no change – MaryBeauty2020 Feb 05 '19 at 19:48
  • @MaryBeauty2020: While it's unlikely that the session is what is causing the redirect problem, David brings up a good point about your SQL string. In addition to hashing passwords, you should never pass user input directly into a query (eg don't pass `$_POST['user']`). Instead, you should learn the concept of prepared statements (they're easier than they may first appear). If you google the term you'll find all sorts of helpful articles, but here's one of the first results I've grabbed off Google: https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection – RToyo Feb 05 '19 at 19:56
  • thanks @RToyo but first I want to solve redirecting issue than I will do a brief research on prepared statement. – MaryBeauty2020 Feb 05 '19 at 20:01
0

try with this code:

error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();

if ( !isset($_SESSION['user_id']))
{
    $_SESSION['msg'] = "You must log in first";
    header('location: login.php');
}

if (isset($_GET['logout']))
{
    unset($_SESSION['user_id']);
    session_destroy();
    header("location: login.php");
}

For login.php

error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();

if(isset($_POST['Login']))
{
    $user = $_POST['uid'];
    $pwd = $_POST['pass'];
    $query = "SELECT * FROM users WHERE userid='$user' && password='$pwd'";
    $data= mysqli_query($con,$query);
    $total = mysqli_num_rows($data);

    if($total==1)
    {

        $_SESSION ['user_id']= $user;
        header('location:home.php');
    }
}
else 
{
    header('location:error.php');
}
Harish
  • 462
  • 6
  • 13