PHP: $_SESSION doesn't set - php

Before setting as duplicate, I've spent 4 hours on researching about my problem, but I had no luck.
I am trying to make a signup/login system for my website. The main point that doesn't seem to work is that when I am signing up on my website, the session doesn't seem to start. The reason that I can see it is because, on my navbar, I have set it to change from signup to log out. Here is the piece of code for that:
<ul>
<li class="list1">Home</li>
<li class="list2">About</li>
<li class="list3">Portfolio</li>
<li class="list4">Blog</li>
<li class="list4">Contact</li>
<?php
if (isset($_SESSION['id'])){
echo "<li><a href='#'>SIGN OUT</a></li>";
}
else{
echo "<li><a onclick='signup(event)' href='#'>SIGN UP</a></li>";
}
?>
</ul>
To make that I have created three files. One is the mane page, one is the signup file itself, code below:
<?php
session_start();
include "../dbh.php";
$first = $_POST["first"];
$last = $_POST["last"];
$uid = $_POST["uid"];
$email = $_POST["email"];
$pwd = $_POST["pwd"];
$sql = "INSERT INTO users (first,last,uid,email,pwd) VALUES ('$first','$last','$uid','$email','$pwd')";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$_SESSION['id'] = $row['id'];
header("Location: ../index.php");
exit();
and the last one is the file which connects PHP to the database code below:
$conn = mysqli_connect("XXX","XXX","XXX","XXX");
if (!$conn){
die("Connection failed: ".mysqli_connect_error());
}
I believe that the session doesn't start because the main page reloads after the user hits signup on the form, but I have started the session on all of my files (except the database connection file where it's not needed). I used session start on all of my page and I placed it on the beginning of all pages with opening and closing PHP tags.
Any suggestions? I appreciate your answers and comments!
Sorry for the bad English but it's not my first language.

This:
$sql = "INSERT INTO users (first,last,uid,email,pwd) VALUES ('$first','$last','$uid','$email','$pwd')";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
^^^^^^^^^^^^^^^^^^
$_SESSION['id'] = $row['id'];
Insert queries do NOT return a result set, and you can NOT fetch() from them. That means mysqli_fetch_assoc() is failing, and returning a boolean FALSE. You then use that boolean false as if it was an array, and are basically doing the equivalent of
$_SESSION['id'] = null;
Note this:
php > $foo = false;
php > $id = $foo['id'];
php > var_dump($id);
NULL
You want
$_SESSION['id'] = mysqli_insert_id($conn);
instead.

It is an error with you SQL query.
$sql = "INSERT INTO users (first,last,uid,email,pwd) VALUES ('$first','$last','$uid','$email','$pwd')";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
The first line of the code is an INSERT command. The second line executes this command by sending it to the server. If query is properly processed then MySQL server doesn't return you anything, so $result will equal to true. It wil not contain any data from the database. So you can't fetch it, what you try to do in the third line. Need to make a separate query for data.

Related

empty session value when moving one page to other

Im having a problem of accessing the session variable value.
im creating a login page and this were i set the values of my session variables.
index.php
<?php
session_start();
$result=mysql_query("select * from myuser where id='".$id ."' and password='".$password."'");
if(mysql_num_rows($result) > 0){
$user = mysql_fetch_assoc($result);
$_SESSION['SESS_ID'] = $user['id'];
$_SESSION['SESS_UNAME'] = $user['username'];
$_SESSION['SESS_PASS'] = $user['password'];
header("location:home.php");
exit();
}
?>
home.php
<?php
session_start();
if(!isset($_SESSION['SESS_ID']) || (trim($_SESSION['SESS_ID'])) == ''){
header("location:index.php");
exit();
}
?>
<html>
<body>
<p>Login Successful</p>
<?php echo $_SESSION['SESS_ID'] ; ?>
</body>
</html>
the problem here is i have no value in $_SESSION['SESS_ID']..so how do i get or access the value of this session variable in my home.php?
Edit: my query for the SQL is
select * from myuser where id='".$id ."' and password='".$password."'
Some points about why you have this issue:
the values you populate the $_SESSION array with come directly from the database, but you have no database SQL query - instead you have
"!--query written here --"
If you can replace this placeholder with a query that returns your id, username and password values then your code should execute as expected.
I'm not certain if your syntax is wrong as such, but it is not the shape I would ever lay it out, my own shape would be:
$result = mysqli_query($connection, $sql);
while ($outputrow = mysqli_fetch_array($result)){
// In here $outputrow is an array of ONE row of your database, so
// $outputRow['id'] = the id from one row. ordered by the ORDER BY in your SQL query.
}
Add a mysqli_error($connection) clause to your SQL query to detect errors. such as :
Here:
$result=mysqli_query($connection, "<!--query written here -->") or die("error :".mysqli_error($connection));
As I have used across these examples, please, please STOP using MySQL and use at least MySQLi or even PDO. There are a host of improvements and bug fixes and lots of info on this transition on SO.
Also, never, ever compare passwords as strings, passwords saved to a database should as a minimum be saved as hashes with PHP function password_hash(). Never have the line if($_POST['pwd'] == $row['pwd']){.
Finally, as rightly mentioned by Fred-ii- in comments, add error logging and checking into your script so that you know what's going on:
Such as:
error_reporting(E_ALL);
ini_set('display_errors', 1);
Add these to the very top of your PHP page and they will display your errors and warnings to you so you can see what is and is not working.
EDIT:
From your edit there are two biq questions, your statement is that:
"select * from myuser where id='".$id ."' and password='".$password."'
so where does the value $id and $password come from? is the <?php at the top of the page, if so, these variables will always be empty, you need to apply a value to these variables.

PHP $_GET method not working /Follow system

i am having a problem with the get method in php, i try to get a variable($profile_id) from one php page to another, the variable is working in this page
<?php
$follow="";
$loggedinid=$_SESSION['userid'];
$sqll = "SELECT id FROM Follow WHERE user_one='$loggedinid' AND user_two='$profile_id'";
if($profile_id != $_SESSION["userid"]){
$check= mysqli_query($db_conx, $sqll);
if(mysqli_num_rows($check) == 1){
$follow='Unfollow';//This is where i try to put the variable, so i can call it with the get method on followaction.php
}else{
$follow='Follow';
}
}
?>
but then in the followaction.php when i call the profid, It returns $profile_id(sting) instead of the number it should be representing
<?php
include_once("php_includes/check_login_status.php");
$followaction=$_GET['followaction'];
$profileid = $_GET['profid'];
$loggedinid = $_SESSION['userid'];
$loggedinusername = $_SESSION['username'];
if($followaction == 'follow'){
mysqli_query($db_conx, "INSERT INTO Follow VALUES('','$loggedinid','$profileid')");
}
if($followaction == 'unfollow'){
$sql = "DELETE FROM Follow WHERE user_one='$loggedinid' AND user_two='$profileid'";
mysqli_query($db_conx, $sql);
}
?>
How can i fix this, everything is working but i cant transfer the profile_id to this page....
This does not work
$follow='Unfollow';
If you do
echo $follow;
You will get something like this (Notice $profile_id has not been replaced)
Unfollow
You need to use double quotes if you want variable replacement
$follow="Unfollow";

Fecthing information from mysql

I really got a problem now. I tried for decades and I can't find why it is not working. I want to get the user that is logged in to see their email on a specific page. I tried a new code now and i get this error: Notice: Undefined variable: row in
The code I use is:
<?
$username = $_SESSION['username'];
$sql = "select * from users where username=" . $username . "";
echo $sql;
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
}
?>
AND
<?php echo $row['email']; ?>
<?php
$username = $_SESSION['username'];
$query = mysql_query("select * from users where username='".$username."'");
while ($row = mysql_fetch_array($query)) {
$email=$row["email"];
}
echo $email;
?>
try this.
don't use mysql_* functions
I think... Problem is in SQL query. I propose your column "username" is something like VARCHAR(50). So you have to add quote.
$sql = "select * from users where username='" . $username . "'";
I see a bug, and a design problem.
You've designed your script so that you're printing whatever was last assigned to $row in the condition of your while loop.
You're getting the error because the query is not returning anything and the loop is not running. Therefore, $row is never assigned. That being said, you probably don't want to use a while-loop if all you're trying to do is display the value of the "email" column in the first record returned. If you did want to, then stop it.
Call mysql_fetch_assoc() on your $result (doesn't return as much data), and check that it doesn't return FALSE (one or more records weren't found).
if((row = mysql_fetch_assoc($result)) === false)
die("Error.");
?>
Email:

trying to set session variable

if(isset($_SESSION['admin'])) {
echo "<li><b>Admin</b></li>";
}
<?php
session_name('MYSESSION');
session_set_cookie_params(0, '/~cgreenheld/');
session_start();
$conn = blah blah
$query2 = 'Select Type from User WHERE Username = "'.$_SESSION['user'].'" AND Type =\'Admin\'';
$result2 = $conn->query($query2);
if($result2->num_rows==1) {
$_SESSION['admin'] = $result2;
}
?>
Hi, I'm trying to set this session variable but it doesn't seem to be setting, and i'm wondering if anyone can help. If session['admin'] isset it should echo the admin button.
But i'm not quite sure why? (I do have session start and everything on everypage, it's not a problem with that or any of the "You don't have php tags" I have checked the mysql query, and it does return something from my table. Any ideas please?
Your session_start(); should be at the top of the page before anything to do with the session variables.
From the docs:
When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers.
Edit from comments:
<?php
session_name('MYSESSION');
session_set_cookie_params(0, '/~cgreenheld/');
session_start();
// Moved to start after answer was accepted for better readability
// You had the <?php after this if statement? Was that by mistake?
if(isset($_SESSION['admin']))
{
echo "<li><b>Admin</b></li>";
}
// If you have already started the session in a file above, why do it again here?
$conn = blah blah;
$query2 = 'Select Type from User WHERE Username = "'.$_SESSION['user'].'" AND Type =\'Admin\'';
// Could you echo out the above statement for me, just to
// make sure there aren't any problems with your sessions at this point?
$result2 = $conn->query($query2);
if($result2->num_rows==1)
{
$_SESSION['admin'] = $result2;
// It seems you are trying to assign the database connection object to it here.
// perhaps try simply doing this:
$_SESSION['admin'] = true;
}
?>
Edit 2 from further comments:
You have to actually fetch the fetch the data like this - snipped from this tutorial which might help you out some more:
$query = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "Name :{$row['name']} <br>" .
"Subject : {$row['subject']} <br>" .
"Message : {$row['message']} <br><br>";
}
But having said that, while we are talking about it, you would be better off moving away from the old mysql_* functions and move to PDO which is much better.
Move session_start(); to the top of the page. You are trying to retrieve sessions, where it's not loaded.
EDIT: Try echoing $_SESSION['admin'], if it even contains something. Also try debugging your if($result2->num_rows==1) code by adding echo('its working'); or die('its working'); inside it, to check if $result2 contains exactly 1 row, since currently it seems $result2 contains either more than 1 row or no rows at all.

login function is not working properly

Hello I facing a strange problem; I am using this code to check the login data with my db
include("includes/config.php");
include("includes/database.php");
$name = $_POST['username'];
$pass = $_POST['password'];
$sql = "SELECT * FROM info_user WHERE user_name = '$name' AND password = '$pass'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
echo $row['user_name']. " - ". $row['password'];
if (mysql_num_rows($sql)) {
echo "success";
}
else
{
echo "failed";
}
here, when i succeed it shows success but any blank input or wrong input is not showing the failed message why? and how can I solve it? is there any better way to check the login? please help
Thanks in advance
First off:
$row = mysql_fetch_array($result) or die(mysql_error());
If you pass along a wrong username or password, mysql_fetch_array() will return FALSE, because there is no rows to take from. This results in your or die(mysql_error()) part being executed, which means your script dies and outputs nothing since mysql didn't fail - which again means that mysql_error() has nothing to return to you.
Secondly, you are using mysql_num_rows() on the $sql string, not on the $result variable which actually contains a mysql resource that you should be using.
You should also check the mysql_num_rows() before using mysql_fetch_array() so that you don't try to pull out some data you don't have available.
Lastly, your solution is full of security flaws. You are passing along raw post data to your mysql database which makes you vulnerable to sql injection and you are storing your passwords as plain text values in your database (not plain text files, just plain text values).
You should google sql injection and password hashing to improve your security.
Try this:
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
echo "success";
} else {
echo "failed";
}

Categories