John Davidson

sqlite - Create PHP $_SESSION['x'] on login using sqlite3 db hosted locally

0 comments
Message:


I am writing an application that includes a login page (as the index page), which i would like to assign a $_SESSION['user'] variable when login is valid in order to secure restricted pages using an auth script. I have everything working correctly without the session being set, however as soon as i try to start the session from index.php, everything stops working. Can someone please explain to me what is going on? I have been reading & trying different things for 2 days now..


db.php


<?php
$con = new SQLite3("db/test.db");

if(!$con){
echo "Failed to connect to the Hosts Database";
}
?>

auth.php


<?php
if(!isset($_SESSION['user'])){
header('Location: index.php');
}
?>

index.php


<?php
session_start();
?>

<!DOCTYPE html>
<head>
<title>App</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<?php
require("db/db.php");
if(isset($_POST["login"])){
$username = $_POST["username"];
$passwd = $_POST["upass"];

$sql = "SELECT * FROM access WHERE (user='".$username."' AND pass='".md5($passwd)."');";
$r = $con->query($sql);
if($r){
$_SESSION['user'] = $username;
echo "<script>window.location.replace('access.php');</script>";
}
} else {
?>
<form name="loginForm" id="loginForm" method="POST" action="">
<center>
<input type="text" name="username" id="username" placeholder="Username" required/>
<input type="password" name="upass" id="upass" placeholder="Password" required />
<br />
<input type="submit" name="login" value="Login" />
</center>
</form>
<?php
}
?>
</body>
</html>

Then in access.php it has include('db/auth.php'). As i say it works fine if i remove session_start & remove setting the variable, i did actually have this working before on another script but lost it & am now genuinely confused as to why it doesnt work when trying to redo it...



My Answer:
To create a PHP $_SESSION variable in SQLite, you can use the following code:

php
// Start the session
session_start();

// Set the $_SESSION variable
$_SESSION['key'] = 'value';


This code will create a session variable with the key 'key' and the value 'value'. You can then access this variable throughout your PHP script by using `$_SESSION['key']`.

Rate this post

5 of 5 based on 2935 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us