PHP Session won't start [closed] - php

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm having problem with starting a session in PHP. By looking around I wrote some code that should work but it doesnt. Can you please help me out because I don't know what's wrong here. This is my loging.php page
<?php
$host = "localhost";
$user = "usern";
$password = "gtest123";
$db = "test";
$errore = "Login info are wrong!`enter code here`";
mysql_connect($host,$user,$password);
mysql_select_db($db);
if(isset($_POST['username'])){
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "select * from utenti where username = '".$username."' AND Password = '".$password."' limit 1";
$result = mysql_query($sql);
if(mysql_num_rows($result)==1){
$_SESSION['username'] = $username;
header("location:index.php");
}
else{
echo "" .$errore;
}`enter code here`
}
?>
I than have my db with users on phpmyamin and the login it's working. The problem is when I load the index.php page.
<?php
session_start();
echo "Welcome" .$_SESSION[''];
?>
<html>
all the html code
I start this session because I want to be able to see which user do certian function in the website. However I get this error message:
Notice: Undefined index:
I know what the error means but I don't know how to fix it, any help?

So, firstly, I see you're using mysql_connect, which is a deprecated function because it's not secure at all, and it's replaced by mysqli_connect http://php.net/manual/en/book.mysqli.php for documentation. For even better security, and to protect against sql injection, you should use PDO, or prepared statements. In this example though, I have stuck to using mysqli because it's less of a learning curve.
Secondly, $_SESSION will only work if you first initialise the session using session_start(). This will have to be done on every page that you wish to read or write session data from.
<?php
//Since this page writes to a session, initialise it here
session_start();
//The values to connect to the database with
$host = "localhost";
$user = "usern";
$password = "gtest123";
$db = "test";
//Create a new mysqli connection to the database
$conn = mysqli_connect($host, $user, $password, $db);
//This is the error message that's displayed on unsuccessful login
$error = "Login info are wrong!`enter code here`";
//This is the error message if the username is not specified
$errorNoUsername = "You have not specified a username";
/**
* Now that we're using mysqli_connect(), we don't need this code.
* mysql_connect($host,$user,$password);
* mysql_select_db($db);
**/
//See if the user has submitted the form with the username parameter
if(isset($_POST['username'])){
//If they have, shortname the variable for username and password
$userUsername = $_POST['username'];
$userPassword = $_POST['password'];
//Build your select query. In production, you should use PDO or Prepared Statements to protect against injection
//I've removed your LIMIT 1 from the query, because I see you're checking for a distinct match later on with mysqli_num_rows==1
$sql = "SELECT * FROM utenti WHERE username='".$userUsername."' AND Password = '".$userPassword."'";
//run the query on the connection created earlier
$result = mysqli_query($conn, $sql);
//Check if there's a distinct match
if(mysqli_num_rows($result)==1){
//There is, good, initialise session with the user data
$_SESSION['username'] = $userUsername;
//Reload to your index.php page
header("location:index.php");
} else {
//Display the error message
echo $error;
}
} else {
echo $errorNoUsername;
}
?>
So now that we've done that, assuming a successful login, we have redirected the user back to index.php, since we are reading from session data, we need to initialise the session again, using session_start();, which you've already done, but your key $_SESSION[''] doesn't exist, so there is an error. Here, I have corrected.
<?php
session_start();
echo "Welcome, " . $_SESSION['username']; //Added keyname
?>
<html>
all the html code
</html>

Use session_start() in every page where you want to work with sessions and as you are setting $_SESSION['username'] in loging.php page so you need to change
echo "Welcome" .$_SESSION[''];
with
echo "Welcome" .$_SESSION['username'];
In this way, you will be able to get the session of username in index.php which you have set in loging.php page

Related

How to adapt my PHP Session into an Array

I have this PHP code which I'm using to trigger the user log in. For a successful log in, the user uses their registered email and password. My current PHP code allows the username to be echoed on whatever pages use the $_SESSION['loggedin'] = $dbusername. What I'm now trying to do is to adapt this PHP code to put an Array into the 'loggedin' session. I want the array to hold user registration details i.e firstname, lastname, company and email, aswell as their username (dbusername). This is to enable me to echo such details on a 'user account page'
My code:
<?php
session_start();
$email = $_POST['email'];
$password = $_POST['password'];
if ($email&&$password)
{
$connect = mysql_connect("*****","***","**********") or die ("Login failed!");
mysql_select_db("dbname") or die ("Could not connect to Database");
$query = mysql_query("SELECT * FROM regusers WHERE email='$email'");
$numrows = mysql_num_rows($query);
if($numrows !=0)
{
while ($row = mysql_fetch_assoc($query))
{
$dbemail = $row['email'];
$dbpassword = $row['password'];
$dbusername = $row['username'];
}
if ($email==$dbemail&&$password==$dbpassword)
{
include 'loginIntro.php';
$_SESSION['loggedin']=$dbusername;
}
else
echo "Incorrect Password";
}
else
die ("That email doesn't exist");
}
else
die ("Enter a registered email and password");
?>
Then on my 'user account page' I have this :
<?php
session_start();
$dbusername = $_SESSION['loggedin'];
?>
For the purposes of echoing the username this PHP code works fine, as all I have to do is : any time I want to display the users username. So going back to my original question - Please impart the necessary knowledge to adapt this PHP code to hold the users registration details so I can echo such details on whatever page(s) use the session in question. Please forgive my lack of knowledge and understanding, I've scratched my head so hard I've got cradle cap - which only babies get, but in this PHP game I'm an embryo. Thanks for whatever help comes
$_SESSION is a array
You can simply save a associative array inside of it.
$_SESSION['id'] = $x;
$_SESSION['username'] = $y;
$_SESSION['realname'] = $z;
or a nested array
$_SESSION['user']['id'] = $x;
$_SESSION['user']['username'] = $y;
$_SESSION['user']['realname'] = $z;
Beware
You are using deprecated functions.
There is no validation on data passed.
There is a risk (looks like 100%) of SQL injection.
As bwoebi said, you may not save password in clear text.
Suggested reading
http://php.net/manual/en/function.error-reporting.php
http://php.net/manual/en/language.types.array.php
http://www.php.net/manual/en/session.examples.basic.php
http://php.net/manual/en/filter.examples.validation.php
http://php.net/manual/en/faq.passwords.php
http://php.net/manual/en/security.database.sql-injection.php
http://php.net/manual/en/intro.pdo.php
If you want to use an Array as a Session variable, you have to serialize it first. (http://php.net/manual/en/function.serialize.php).
Then you can add it to $_SESSION, and unserialize (http://php.net/manual/en/function.unserialize.php) it on the other pages.
Now here are two advices : hash your passwords using sha1 (http://us2.php.net/manual/en/function.sha1.php), and don't use mysql_* functions, which are outdated. Consider using mysqli ou PDO.

PHP session not persisting between screens

I have come across an issue that has confused me a lot.
I am working on a login screen using PHP and MySQL. I manage to validate the username and password against an existing user in the database and after this, I initiate a session, and set the session variable username to the username provided in the login screen.
$username = html($_POST['username']);
$password = html($_POST['password']);
$result = $pdo->prepare('SELECT * FROM users WHERE username = :username AND password = :password');
$result->bindValue(':username', $username);
$result->bindValue(':password', $password);
$result->execute();
foreach($result as $user)
{
$count = $count + 1;
}
if ($count == 1)
{
session_start();
$_SESSION['username'] = $username;
` //if I do an echo $_SESSION['username'] it displays the correct user
header('Location: .');
exit();`
}
However when it transfers me to the index.php page the $_SESSION['username'] variable has disappeared and I do not understand why. This is the code I use in index.php to check for the username:
<p>View all tasks</p>
<p>Add your own task</p>
<p>Welcome, <?php echo $_SESSION['username']; ?></p>
however I get the following error: Notice: Undefined variable: _SESSION in C:\xampp\htdocs\abcabcabc\index.php on line 16
All advice will be greatly appreciated guys
Add sesssion_start() to all of your scripts that use the session
You must use session_start(); at the beginning of index.php file.
The first 2 answers are correct. You must start session on each page. I usually just put it in a file that is "included" in every page already (like a header file) so I don't have to think about it.

PHP MySQLI (OOP?) - The code doesn't work at all

I'm kinda new to the OOP(? If this IS OOP, I don't know) language, and I'm trying to make a simple login-proccess, with MySQLi. The problem are, that the code doesn't work. I can't login (and It's not showing me any errors) and I can't register an new account (same problem) - It's like the code are dead or something.
I'm not sure I've done it right, but this is my best, so far. 'cause I'm new to OOP(?).
Index.php:
<?php
if(isset($_POST['submit'])) {
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string(md5($_POST['password']));
$userControl = "SELECT * FROM users WHERE username='".$username."' AND password='".$password."'";
$userControlResult = $mysqli->query($userControl);
if($mysqli->num_rows($userControlResult) > 1) {
$userRow = $mysqli->fetch_assoc($userControlResult);
$dbid = $userRow['id'];
$dbuser = $userRow['username'];
$_SESSION['id'] = $dbid;
$_SESSION['username'] = $dbuser;
header("location: me.php");
die();
} else {
echo "<div class='errorField'>Användarnamnet eller lösenordet är fel!</div>";
}
}
?>
I suppose that if I can solve the first error, I can solve the second too.
Thanks!
Many things I would recommend changing about your code:
Don't use mysql_real_escape_string() if you're using mysqli. You can't mix these APIs.
No need to escape a string returned by md5(), because it's guaranteed to contain only hexadecimal digits.
Don't use mysqli_real_escape_string() anyway -- use parameters instead.
Always check if prepare() or execute() return false; if they do, then report the errors and exit.
You can get a mysqli result from a prepared statement using mysqli_stmt_store_result().
Don't SELECT * if you don't need all the columns. In this case, you already have $username so all you really need to fetch is the id column.
No need to check the number of rows returned, just start a loop fetching the rows (if any). Since you exit inside the loop, your "else" error clause will be output only if the loop fetches zero rows.
Consider using a stronger password hashing function than MD5. Also, add a salt to the password before hashing. Read You're Probably Storing Passwords Incorrectly.
Example:
<?php
if(isset($_POST['submit'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
$userControl = "SELECT id FROM users WHERE username=? AND password=?";
if (($userControlStmt = $mysqli->prepare($userControl)) === false) {
trigger_error($mysqli->error, E_USER_ERROR);
die();
}
$userControlStmt->bind_param("ss", $username, $password);
if ($userControlStmt->execute() === false) {
trigger_error($userControlStmt->error, E_USER_ERROR);
die();
}
$userControlResult = $userControlStmt->store_result();
while($userRow = $userControlResult->fetch_assoc()) {
$_SESSION['userid'] = $userRow["id"];
$_SESSION['username'] = $username;
header("location: me.php");
die();
}
// this line will be reached only if the while loops over zero rows
echo "<div class='errorField'>Användarnamnet eller lösenordet är fel!</div>";
}
?>
A good command to enter at the top of the script (under the
ini_set('display_errors', 1);
This will display any errors on your script without needing to update the php.ini (in many cases). If you try this, and need more help, please post the error message here and I'll be able to help more.
Also, if you are using $_SESSION, you should have
session_start();
at the top of the script under the
Make sure your php is set to show errors in the php.ini file. You'll need to do some research on this on your own, but it's fairly easy to do. That way, you'll be able to see what the error is and go from there.

Pass the login details to another page using session PHP

I need the login details in another page for retrieving the data from the database. Basically, I need to display the editable form with the details of the user logged in. I tried session_register() for storing the username in login.php page. But for some reason I am not able to display the username using $_SESSION[] in my edit.php page. I am doing this after the function session_start() as well.
I am new to php, so don't know whether I misunderstood session! Or is there any other way to pass the login details?
Thanks in advance
My code:
**Login.php**
<?php
$userName = $_POST['username'];
$password = $_POST['password'];
//Connect to the database
//query the database
if($rows==1)
{
session_start();
$_SESSION['user']=$userName;
header("location:edit_user.php");
}
else
{
echo 'Data Does Not Match <br /> Re-Enter UserName and Password';
}
?>
**In edit.php**
<?php
session_start();
if(!isset($_SESSION['user']))
{
header("location:login_form.php");
}
else
{
echo $_SESSION['user'];
}
?>
First of all make sure that you place session_start() at the very beginning of any script you use it in. There can be no output to the browser before you call session_start() and that includes spaces or new-lines before the opening <?php tag.
So:
<?php
session_start();
...
Second, make sure you terminate your script after a redirect, for example:
header("location:edit_user.php");
exit();
That makes sure that no code after the redirect gets executed, so sessions won't get unset or session variables changed by accident.
session_register() is a deprecated function. Just use $_SESSION["bar"] = "foo" to store something.
for future references, please post parts of your code when you are asking questions. It helps everyone to give you an answer in more specific cases.
<?php
session_start();
if(!isset($_SESSION['Foo']))
{
$_SESSION['Foo'] = "Bar";
}
?>
Source : http://php.net/manual/en/features.sessions.php
you can retrive data from the database like this
//start connection
$connect = mysql_connect(DB_SERVER,DB_USER,DB_PASSWORD);
if(!$connect){
die("Database connection Error".mysql_error());
}
//select database
$db = mysql_select_db(DB_NAME);
if(!$db){
die("Database selection Error".mysql_error());
}
//get data
$login = mysql_query("SELECT * FROM TABLENAME where user_id={$_SESSION['user_id']}");
$login_data = mysql_fetch_array($login);
now $login_data array has the user details which you can point to form text field values..
the $_session['user_id']=$login_data['user_id'] value has to be assigned earlier which stays in the $_SESSION global variable through out the session

How to echo out info from MySQL table in PHP when sessions are being used.

I am using sessions to pass user information from one page to another. However, I think I may be using the wrong concept for my particular need. Here is what I'm trying to do:
When a user logs in, the form action is sent to login.php, which I've provided below:
login.php
$loginemail = $_POST['loginemail'];
$loginpassword = md5($_POST['loginpassword']);
$con = mysql_connect("xxxx","database","pass");
if (!$con)
{
die('Could not connect: ' .mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("SELECT * FROM Members
WHERE fldEmail='$loginemail'
and Password='$loginpassword'");
//check if successful
if($result){
if(mysql_num_rows($result) == 1){
session_start();
$_SESSION['loggedin'] = 1; // store session data
$_SESSION['loginemail'] = fldEmail;
header("Location: main.php"); }
}
mysql_close($con);
Now to use the $_SESSION['loggedin'] throughout the website for pages that require authorization, I made an 'auth.php', which will check if the user is logged in.
The 'auth.php' is provided below:
session_start();
if($_SESSION['loggedin'] != 1){
header("Location: index.php"); }
Now the point is, when you log in, you are directed BY login.php TO main.php via header. How can I echo out the user's fullname which is stored in 'fldFullName' column in MySQL on main.php? Will I have to connect again just like I did in login.php? or is there another way I can simply echo out the user's name from the MySQL table? This is what I'm trying to do in main.php as of now, but the user's name does not come up:
$result = mysql_query("SELECT * FROM Members
WHERE fldEmail='$loginemail'
and Password='$loginpassword'");
//check if successful
if($result){
if(mysql_num_rows($result) == 1){
$row = mysql_fetch_array($result);
echo '<span class="backgroundcolor">' . $row['fldFullName'] . '</span><br />' ;
Will I have to connect again just like I did in login.php?
Yes. This is the way PHP and mysql works
or is there another way I can simply echo out the user's name from the MySQL table?
No. To get something from mysql table you have to connect first.
You can put connect statement into some config file and include it into all your scripts.
How can I echo out the user's fullname which is stored in 'fldFullName' column in MySQL on main.php?
You will need some identifier to get proper row from database. email may work but it's strongly recommended to use autoincrement id field instead, which to be stored in the session.
And at this moment you don't have no $loginemail nor $loginpassword in your latter code snippet, do you?
And some notes on your code
any header("Location: "); statement must be followed by exit;. Or there would be no protection at all.
Any data you're going to put into query in quotes, must be escaped with mysql_real_escape_string() function. No exceptions.
so, it going to be like this
include $_SERVER['DOCUMENT_ROOT']."/dbconn.php";
$loginemail = $_POST['loginemail'];
$loginpassword = md5($_POST['loginpassword']);
$loginemail = mysql_real_escape_string($loginemail);
$loginpassword = mysql_real_escape_string($loginpassword);
$query = "SELECT * FROM Members WHERE fldEmail='$loginemail' and Password='$loginpassword'";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
if($row = mysql_fetch_assoc($result)) {
session_start();
$_SESSION['userid'] = $row['id']; // store session data
header("Location: main.php");
exit;
}
and main.php part
session_start();
if(!$_SESSION['userid']) {
header("Location: index.php");
exit;
}
include $_SERVER['DOCUMENT_ROOT']."/dbconn.php";
$sess_userid = mysql_real_escape_string($_SESSION['userid']);
$query = "SELECT * FROM Members WHERE id='$sess_userid'";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
$row = mysql_fetch_assoc($result));
include 'template.php';
Let me point out that the technique you're using has some nasty security holes, but in the interest of avoiding serious argument about security the quick fix is to just store the $row from login.php in a session variable, and then it's yours to access. I'm surprised this works without a session_start() call at the top of login.php.
I'd highly recommend considering a paradigm shift, however. Instead of keeping a variable to indicate logged-in state, you should hang on to the username and an encrypted version of the password in the session state. Then, at the top of main.php you'd ask for the user data each time from the database and you'd have all the fields you need as well as verification the user is in fact logged in.
Yes, you do have to reconnect to the database for every pageload. Just put that code in a separate file and use PHP's require_once() function to include it.
Another problem you're having is that the variables $loginemail and $loginpassword would not exist in main.php. You are storing the user's e-mail address in the $_SESSION array, so just reload the user's info:
$safe_email = mysql_real_escape_string($_SESSION['loginemail']);
$result = mysql_query("SELECT * FROM Members
WHERE fldEmail='$safe_email'");
Also, your code allows SQL Injection attacks. Before inserting any variable into an SQL query, always use the mysql_real_escape_string() function and wrap the variable in quotes (as in the snippet above).

Categories