-2

I made a site with PHP that the user enters I wanted to do something with cookies in PHP so that when the user enters another header is displayed

<?php
include "database/pdo_connection.php";
$error="";
$errorFild="";

if(
    isset($_POST['phone']) && $_POST['phone'] !== '' 
    && isset($_POST['password']) && $_POST['password'] !== '' 
 )
    {
if(isset($_POST['sub'])){
    $phone=$_POST['phone'];
    $password=$_POST['password'];
    $smt=$conn->prepare("SELECT `password` FROM users WHERE `phone`='$phone' ");
    $smt->execute();
    $result=$smt->fetchAll();
    if(password_verify($password,$result[0]['password'])){
        $result=$conn->prepare("SELECT * FROM users WHERE phone=? ");
        $result->bindValue(1,$phone);
        $result->execute();
        $users=$result->Fetch(PDO::FETCH_ASSOC);
        $_SESSION['id']=$users['id'];
        $_SESSION['role']=$users['role'];
        $_SESSION['phone']=$users['phone'];
        **setcookie("phone", $users['phone'], time()+89000);**
        header('location:index.php');
    }
    else{
        $error=true;
    }

}


    }
    else{
        if( !empty($_POST)){
     $errorFild =true;}
    }
?>

This is the login page code

  <li class="nav-item me-0">
              <a class="nav-link mt-3 mt-lg-0" href="/login.php">
                <i class="fa fa-sign-in ms-1"></i>
                <span>login</span>
              </a>
            </li>

            <li class="nav-item me-0">
              <a class="nav-link mt-3 mt-lg-0" href="/register.php">
                <i class="fa fa-user-plus ms-1"></i>
                <span>register</span>
              </a>
            </li>


           
            </li>

            <li class="nav-item me-0">
              <a class="nav-link mt-3 mt-lg-0" href="/codeyadproject2/logout.php">
                <i class="fa fa-sign-in ms-1"></i>
                <span>logout</span>
              </a>
            </li>

           


            <li class="nav-item me-0">
              <a class="nav-link mt-3 mt-lg-0" href="/codeyadproject2/PANEL/index.php">
                <i class="fa fa-sign-in ms-1"></i>
                <span>login to panel</span>
              </a>
            </li>

and index header
my Question: I want him not to bring me another header when he comes in For example, instead of logging in and registering, it should log in to the panel, or if it doesn't log in, it won't log in to the panel anymore What code should I put? (with cookies)

M. Eriksson
  • 13,450
  • 4
  • 29
  • 40
seyed ata
  • 1
  • 3
  • _Side note:_ Your first `prepare()` is _wide open_ for SQL injections since you're not actually binding any parameters, but are injecting the phone directly into the query. You're doing it correctly in the second query though. You also don't need to make the query twice. Just select all columns you need in the first query and reuse the result if the password matches. You should also check if you actually got a result. Your code will throw errors if the phone number invalid/not found. – M. Eriksson Jan 14 '23 at 11:25
  • 1
    You're trying to use sessions, but you haven't called `session_start()` yet (put it immediately after ` – zanderwar Jan 14 '23 at 11:29
  • It's hard to be specific when we don't know anything about your application. Are you using some templating engine? Some specific front end framework? If not, there's no need to set that cookie since you have the state in the session. Just check if the session is set, then show the logged in header. If it isn't set, then show the other (it's a simple `if/else`). However, you need to start the session, as @zanderwar pointed out. – M. Eriksson Jan 14 '23 at 11:34
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/32391315) – Dharman Jan 14 '23 at 12:09

1 Answers1

1

Your script has a couple of issues:

  • Firstly, you're trying to use sessions, but sessions are not accessible until you call session_start().
  • You are executing the same query twice, it would be more efficient to consolidate these into the one.
  • You're using unprepared statements, which are vulnerable to SQL injection attacks (such attacks could lead to your entire database being deleted, or worse; leaked)
  • Cookies are not necessary for the purpose of logging in.
  • The fetchAll() command can be replaced with fetch() because you only need a singular record.

This is what that would look like with those things fixed:

login.php:

<?php
session_start();
include "database/pdo_connection.php";
$error = "";

if (isset($_POST['phone'], $_POST['password'], $_POST['sub'])) {
    $phone = $_POST['phone'];
    $password = $_POST['password'];
    $stmt = $conn->prepare("SELECT * FROM users WHERE `phone` = :phone");
    $stmt->bindParam(':phone', $phone);
    $stmt->execute();
    $result = $stmt->fetch();

    if ($result && password_verify($password, $result['password'])) {
        $_SESSION['id'] = $result['id'];
        $_SESSION['role'] = $result['role'];
        $_SESSION['phone'] = $result['phone'];        
    } else {
        $_SESSION['error'] = 'Your username or password was invalid';
    }
    
    header('location:index.php');
}

index.php:

<?php
session_start();

if (isset($_SESSION['error'])) {
    $errorMsg = $_SESSION['error'];
    unset($_SESSION['error']);
}
?>
<?php if (isset($errorMsg)) { ?>ERROR: <?=$errorMsg?><?php } ?>
<?php if (isset($_SESSION['phone'])) { ?>
  <h1>Welcome back, <?php echo $_SESSION['phone']; ?></h1>
<?php } else { ?>
  <h1>Welcome</h1>
<?php } ?>

(personally though I hate mixing HTML and PHP, but that should be enough to get you out of your writers block)

zanderwar
  • 3,440
  • 3
  • 28
  • 46