Home > OS >  PHP submitting a form is destroying my sessions
PHP submitting a form is destroying my sessions

Time:10-26

Hello I am trying to make a form in the page where I created a session so when I submit the form the sessions gets destroyed here is my code:

<form method="post">
<h5>Name</h5>
<input type=text name="name" >
<br>
<br>
<input type="submit" name="namesearch" ></input>
</form>';

PHP code to start the session :

<?php
if(isset($_POST['s']))
{
    $a=$_POST['uid']; //accessing value from the text field
    $enteredpass = $_POST['pwd']; //accessing value from the text field
$client = new MongoDB\Client('xxxx');

$companydb = $client->test;
$jsons = $companydb->jsons;

$ownerid = $jsons->findOne(
    ['ID' => $a]
);

$idcoded = $ownerid->ID;

if (empty($idcoded)) {
    echo "<h1>empty</h1>";
} 

if (!empty($idcoded)) {
    $passcoded = $ownerid->pass;
    if ($passcoded == $enteredpass) {
        session_start();    
    }
}
}
?>

CodePudding user response:

Make sure you have session_start(); at the top of all the PHP scripts

So, put the session_start(); at the top of the script and set say $_SESSION["uid"] when the user has correctly entered the credentials

A normal practice is to set $_SESSION["uid"]=""; (set initial value) before the user logs in the system, and then use this session variable to determine whether the user has successfully logged in.

So

<?php

session_start(); 

if(isset($_POST['s']))
{
    $a=$_POST['uid']; //accessing value from the text field
    $enteredpass = $_POST['pwd']; //accessing value from the text field
$client = new MongoDB\Client('xxxx');

$companydb = $client->test;
$jsons = $companydb->jsons;

$ownerid = $jsons->findOne(
    ['ID' => $a]
);

$idcoded = $ownerid->ID;

if (empty($idcoded)) {
    echo "<h1>empty</h1>";
} 

if (!empty($idcoded)) {
    $passcoded = $ownerid->pass;
    if ($passcoded == $enteredpass) {
    $_SESSION["uid"]=$_POST['uid'];     
    } else {
    $_SESSION["uid"]="";
    }
}
}
?>
  • Related