I have been working is a website I have been dealing with a problem from a while, and now I know why it is happening, but not how to solve it. Please help!!
Page 1:
In the first page, login page set the $_SESSION['user_id'] is stored the value that are fetch in database user id. In same page can print session and it work properly(the $_SESSION['user_id'] is print) and also navigate the next page(user home).
page 2:
In page 2(user home) the $_SESSION['user_id'] is turned into null value why this happen?
most probably see this problem in, forgot to set the session start but I was set session start both page...
page 1
<?php
if (isset($_POST['sub'])) {
$user = $_POST['user'];
$pass = $_POST['pass'];
$con = mysqli_connect("localhost", "root", "");
$db = mysqli_select_db($con, "Database");
$qry = "select * from TABLE where username='$user' and password='$pass'";
$res = mysqli_query($con, $qry) or die("could not connect to mysql");
$row = mysqli_fetch_array($res);
$len = mysqli_num_rows($res);
if ($len <= 0) {
echo "<script>";
echo "alert('Oops.Username Or Password Incorrect!');window.location.href='login.php';";
echo "</script>";
} else {
session_start();
$_SESSION['id'] = $row['id'];
$_SESSION['message'] = $user;
$_SESSION['logout'] = "";
$id = $_SESSION['id'];
echo "<script>";
echo "alert('log in Success $id ');window.location.href='login.php';"; //$id is print correctly
echo "</script>";
}
}
?>
page 2
<?php
ob_start();
session_start();
if (isset($_SESSION['id'])) {
$id = $_SESSION['id'];
echo "$user"; // not printed
}
if (isset($_SESSION['message'])) {
$msg = $_SESSION['message'];
$_SESSION['message'] = "";
}
if (isset($_SESSION['logout'])) {
$msg = $_SESSION['logout'];
if ($msg == 'logout') {
header("location:login.php");
$_SESSION['message'] = "you must login first";
exit(0);
}
}
?>
<?php
echo "welcome"; // only print this string the above session are not work
?>
I also use this code before some project and it work correctly then why this time the session value not working?
use session in the start in first page, like this. Hopefully this will work
<?php
session_start();
if (isset($_POST['sub']))
{
$user=$_POST['user'];
$pass=$_POST['pass'];
$con=mysqli_connect("localhost","root","");
$db=mysqli_select_db($con,"Database");
$qry="select * from TABLE where username='$user' and password='$pass'";
$res=mysqli_query($con,$qry)or die("could not connect to mysql");
$row=mysqli_fetch_array($res);
$len=mysqli_num_rows($res);
if($len<=0)
{
echo"<script>";
echo"alert('Oops.Username Or Password Incorrect!');window.location.href='login.php';";
echo"</script>";
}
else
{
$_SESSION['id']=$row['id'];
$_SESSION['message']=$user;
$_SESSION['logout']="";
$id=$_SESSION['id'];
echo"<script>";
echo"alert('log in Success $id ');window.location.href='login.php';"; //$id is print correctly
echo"</script>";
}
}
?>
Related
I am trying to store sessions in the local storage of the user when they log in, but the expiry of the session is short and it is deleted every time I route to another page, and I could not figure out what had gone wrong. Below is some snippet of my code.
connect.php
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "ezcar2";
$conn = mysqli_connect($host, $username, $password, $database);
?>
ct_home.php
<body>
<?php
include_once 'connect.php';
session_start();
if (!isset($_SESSION['username'])) {
header("Location: ct_login.php");
exit();
}
?>
</body>
Whenever I refresh the page, I would be redirected back to ct_login.php. I would like for the session to stay until the user logs out.
EDIT (ct_login.php && setting the sessions)
<?php
include_once 'connect.php';
session_start();
if(isset($_POST['btnlogin'])){
$c_username = trim($_POST['txtusername']);
$c_password = trim($_POST['txtpwd']);
$sql_query = "SELECT * FROM tblcustomer WHERE CT_USERNAME = '$c_username' AND CT_PASSWORD = '$c_password'";
$sql_role = "SELECT * FROM tblcustomer WHERE CT_USERNAME = '$c_username' AND CT_PASSWORD = '$c_password' AND CT_ROLE = 'CAR OWNER'";
$sql_status = "SELECT * FROM tblcustomer WHERE CT_USERNAME = '$c_username' AND CT_PASSWORD = '$c_password' AND CT_STATUS = 'APPROVED'";
if($result = mysqli_query($conn, $sql_query)){
$rows = mysqli_num_rows($result);
if($rows == 1) {
if ($status = mysqli_query($conn, $sql_status)) {
$row_ = mysqli_num_rows($status);
if($row_ == 1) {
if($role = mysqli_query($conn, $sql_role)){
$rows_ = mysqli_num_rows($role);
if($rows_ == 1) {
//store username & password in session variable
$rec = mysqli_fetch_row($role);
$_SESSION['username'] = $rec[7];
$_SESSION['role'] = $rec[9];
header("Location: ct_home.php");
// session_start();
} else {
$rec = mysqli_fetch_row($result);
$_SESSION['username'] = $rec[7];
$_SESSION['role'] = $rec[9];
header("Location: ct_home.php");
// session_start();
}
}
} else {
echo('<script>alert("Account request is still pending. Please wait for confirmation email.");</script>');
echo "<meta http-equiv='refresh' content='0'>";
exit();
}
}
} else {
echo('<script>alert("Invalid Credentials. Please try again!");</script>');
echo "<meta http-equiv='refresh' content='0'>";
exit();
}
}
}
?>
Edit (#1) : The database connection is used to validate user login
Please let me know what else I can provide to draw a clearer picture of the whole situation. Many thanks in advance.
This works perfectly well on my localhost but when i hosted online, it does not logon and it echo logged on successful and error free. Pls what can be the cause for this?
<?php
session_start();
$_SESSION['user_logged']=$user;
$_SESSION['user_password']=$password;
$user = $_POST["username"];
$password = $_POST["password"];
include("include/connect.php");
$msg = array();
if(isset($_POST['submit'])){
foreach($_REQUEST as $key=>$val){
$$key=$val;
}
if(count($msg)==0){
$sql="SELECT username, password FROM admin WHERE username='$username' && password='$password'";
$res=mysql_query($sql) OR die(mysql_error());
if(mysql_fetch_array($res)>0){
$_SESSION['user_logged']= $user;
$_SESSION['user_password']=$password;
header("location:dashboard.php");
echo "You looged in Successfully";
} else{
$msg[]='Incorrect username/password';
}
}
}
?>
Below is the dashboard.php which its suppose to redirect to.
<?php
include('include/connect.php');
include('include/function.php');
if(isset($_REQUEST['mode']) )
{
$mode=$_REQUEST['mode'];
if($mode == 1)
{
$id=$_REQUEST['id'];
$sql="DELETE FROM enquiry WHERE id='$id'";
$result=mysql_query($sql);
}
}
$msg=array();
if(isset($_POST['submit'])){
$title=$_POST['news'];
$news_item=$_POST['news'];
if(empty($news_item)){
$msg[]='You must enter news in the column!';
}
if(empty($title)){
$msg[]='News Title must not be empty!';
}
else {
$sql = "SELECT * FROM news_file WHERE title='$title' ";
$res = mysql_query($sql) or die(mysql_error());
$result = mysql_fetch_array($res);
if($result > 0){
$msg[] = 'News with the same title has been added already';
} else {
$sql = "INSERT INTO news_file (title,news,date) VALUES ('$title','$news_item',Now())";
$result = mysql_query($sql);
$msg[]='News was successfully added';
}
}
}
?>
Try this.
<?php
session_start();
/*
These should be the other way round, as you are setting
the session variables with variables which have not been
initialised yet
*/
$user = $_POST["username"];
$password = $_POST["password"];
$_SESSION['user_logged']=$user;
$_SESSION['user_password']=$password;
include("include/connect.php");
$msg = array();
if(isset($_POST['submit'])){
foreach($_REQUEST as $key=>$val){
$key=$val; // Removed Erroneous double $
}
if(count($msg)==0){
$sql="SELECT
username,
password
FROM
admin
WHERE
username='$username'
AND
password='$password'";
// MySql does not accept && as a comparison operator.
$res=mysql_query($sql);
if(!$res)
{
var_dump(mysql_error());
exit;
}
else
{
if(mysql_fetch_array($res)>0)
{
$_SESSION['post'] = $_POST;
while(mysql_fetch_array($res)>0)
{
$_SESSION['user_logged']= $user;
$_SESSION['user_password']=$password;
header("location:dashboard.php");
echo "You logged in Successfully";
}
}
else
{
msg[]='Incorrect username/password';
}
}
?>
Looking at the code you have provided for dashboard.php, you are expecting there to be $_POST data, for a page which you have redirected to. Where you have redirected to the page, there will be no $_POST data for you to retrieve from the server.
I have amended my script above, to store the $_POST data in the session, so using that, you should be able to call your news items by calling $_SESSION['post']['news'], or if this is too long winded, simply re-assign the POST data once inside your dashboard.php script like so.
$post = $_SESSION['post'];
Then you can call it by using $post['news'].
Well I am trying to create kind of a social network but there is a problem with my session. So I am not able to visit other users profile. This is my code for loginwebsite1.php
<?php
ob_start();
session_start();
$connection = mysqli_connect('localhost', 'root', '123456789', 'register');
if (isset($_POST['email1'])) {
$email = mysqli_real_escape_string($connection, htmlentities($_POST['email1']));
}
if (isset($_POST['password1'])) {
$password = mysqli_real_escape_string($connection, htmlentities($_POST['password1']));
}
if (!empty($email) && !empty($password)) {
$query = "select id from register where email='$email' and password='$password'";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result);
if ($row > 0) {
$_SESSION['id'] = $row;
$_GET['id'] = $row;
header('location: new.php');
} else {
echo "sorry but the email-id or password is wrong";
}
} else {
echo "please enter your email-id or password or there";
}
?>
My session code goes like this:
<?php
ob_start();
session_start();
if (isset($_SESSION['id']) && !empty($_SESSION['id'])) {
$id = $_SESSION['id'];
foreach ($id as $fn)
$connection = mysqli_connect('localhost', 'id', 'password', 'register');
$query = "select firstname,lastname from register where id='$fn'";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result);
$firstname = $row['firstname'];
$lastname = $row['lastname'];
} else {
header('location: loginwebsite1.php');
}
?>
But when I try to enter like profile.php?id=9 it still opens the profile of the user who is logged in.
$id=$_SESSION['id'];
This line is where you problem is I believe. Here you get the ID number for the profile page to load from the $_SESSION variable when you should be getting it from the $_GET variable.
It should read:
$id=$_GET['id'];
you should also check if the $_GET['id'] is also set like this
$connection=mysqli_connect('localhost','id','password','register');
if(isset($_SESSION['id']) && !empty($_SESSION['id']) || !empty($_GET['id']))
{
$id=!empty($_GET['id'])? $_GET['id']: $_SESSION['id'];
foreach($id as $fn){
$query="select firstname,lastname from register where id='$fn'";
$result=mysqli_query($connection,$query);
$row=mysqli_fetch_array($result);
$firstname=$row['firstname'];
$lastname=$row['lastname'];
}
}else{
header('location: loginwebsite1.php');
}
also set your $connection variable to connect only once to your database.
I'm trying to fix my login page...
It works fine on the login.php with redirecting but on the index it doesn't redirect even if the session is empty. Any pointers? I'm new to this, so forgive me if it's really obvious.
<?php
require_once('../includes/config.php');
session_start();
if(!isset($_SESSION['loggedin']) && $_SESSION['loggedin']=='no'){
// not logged in
header("location: login.php");
exit();
} else {
$_SESSION['loggedin'] = 'yes';
}
?>
<?php
include("../includes/config.php");
$error = NULL;
$atmpt = 1;
if (!isset($_SESSION)) {
session_start();
}
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin']=='yes'){
// logged in
header("location: index.php");
exit();
}
if(isset($_POST['login']))
{
/* get username and password */
$username = $_POST["username"];
$password = $_POST["password"];
/* MySQL Injection prevention */
$username = mysqli_real_escape_string($mysqli, stripslashes($username));
$password = mysqli_real_escape_string($mysqli, stripslashes($password));
/* check for user in database */
$query = "SELECT * FROM admin_accounts WHERE username = '$username' AND password = '$password'"; // replace "users" with your table name
$result = mysqli_query($mysqli, $query);
$count = $result->num_rows;
if($count > 0){
//successfully logged in
$_SESSION['username']=$username;
$_SESSION['loggedin']='yes';
$error .= "<div class='alert alert-success'>Thanks for logging in! Redirecting you..</div>";
header("refresh:1;url=index.php");
} else {
// Login Failed
$error .= "<div class='alert alert-danger'>Wrong username or password..</div>";
$_SESSION['loggedin']='no';
$atmpt = 2;
}
}
?>
The line
session_start();
should be the very first line in the php script.
Just modify first three lines.
As session_start() should be put before any output has been put on the browser (even space).
<?php
session_start();
require_once('../includes/config.php');
if (empty($_SESSION['loggedin']) && $_SESSION['loggedin']=='no') {
...
Okay, so I want to make a simple login page. I've created a register page successfully, but i can't get the login thing down.
login.php:
<?php
session_start();
include("mainmenu.php");
$usrname = mysql_real_escape_string($_POST['usrname']);
$password = md5($_POST['password']);
$con = mysql_connect("localhost", "root", "g00dfor#boy");
if(!$con){
die(mysql_error());
}
mysql_select_db("users", $con) or die(mysql_error());
$login = "SELECT * FROM `users` WHERE (usrname = '$usrname' AND password = '$password')";
$result = mysql_query($login);
if(mysql_num_rows($result) == 1 {
$_SESSION = true;
header('Location: indexlogin.php');
}
else {
echo = "Wrong username or password." ;
}
?>
indexlogin.php just echoes "Login successful." What am I doing wrong?
Oh, and just FYI- my database is "users" and my table is "data".
<?php
session_start();
include("mainmenu.php");
$usrname = mysql_real_escape_string($_POST['usrname']);
$password = md5($_POST['password']);
$con = mysql_connect("localhost", "root", "g00dfor#boy");
if (!$con) {
die(mysql_error());
}
mysql_select_db("users", $con) or die(mysql_error());
$login = "SELECT * FROM `users` WHERE (usrname = '$usrname' AND password = '$password')";
$result = mysql_query($login);
if (mysql_num_rows($result) == 1) {
$_SESSION['logged_in'] = true;
header('Location: indexlogin.php');
exit;
} else {
echo "Wrong username or password.";
}
?>
I added mysql_real_escape_string() to prevent SQL injection.
No, I didn't because you already had it.
I cleaned up the formatting of the code a bit.
I changed $_SESSION = true; (which doesn't make sense) into $_SESSION['logged_in'] = true;. Then, in indexlogin.php you can do something like if ($_SESSION['logged_in']) { echo $secret; }
I fixed echo = "Wrong username or password."; to echo "Wrong username or password.";
I added a closing bracket near mysql_num_rows($result) == 1.
You said:
my database is "users" and my table is
"data".
If this is correct, you will need to change SELECT * FROM users to SELECT * FROM data.
I don't think you can set $_SESSION = true, because $_SESSION is an array. Try $_SESSION['logged_in'] = true.