PHP Loggin System Session - php

So I'm new to PHP and atm i try to code a simple LogIn System. I set up a Sign up Site and linked it with the sql server. In the log in file i got this if statement.
if (!$row = mysqli_fetch_assoc($result)) {
echo "Your username or Pw is incorect!";
} else {
$_SESSION['id'] = $row['id'];
}
I did test this (i put a 'echo' tag in the else part and it worked. )
so on my index page i got this
<?php
if (isset($_SESSION['id'])) {
echo $_SESSION['id'];
}else {
echo "ur not logged in";
}
?>
This should give me the User id, but nothing comes out. Anyone spottet a mistake i made ?

Related

Login / Logout Session Issue

I am creating some kind of a login/registration system right now. Registration form, email confirmation and login is already working. I now have problems with my sessions. Please keep in mind that this project is just a test project. I know that I should use PDO but for this testing purposes I need to find out why it is not working they way I did it.
Here is my login.php PHP code:
<?php include ('inc/database.php');
if (isset($_POST['submit'])) {
// Initialize a session:
session_start();
$error = array();//this aaray will store all error messages
if (empty($_POST['email'])) {//if the email supplied is empty
$error[] = 'You forgot to enter your Email ';
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['email'])) {
$Email = $_POST['email'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['passwort'])) {
$error[] = 'Please Enter Your Password ';
} else {
$Password = $_POST['passwort'];
}
if (empty($error))//if the array is empty , it means no error found
{
$query_check_credentials = "SELECT * FROM user WHERE email='$Email' AND password='$Password' AND activation IS NULL";
$result_check_credentials = mysqli_query($connect, $query_check_credentials);
if(!$result_check_credentials){//If the QUery Failed
echo 'Query Failed ';
}
if (#mysqli_num_rows($result_check_credentials) == 1)//if Query is successfull
{ // A match was made.
$row = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);
$_SESSION['email'] = $row["email"];
//Assign the result of this query to SESSION Global Variable
header("Location: index.php");
}else
{ $msg_error= 'Either Your Account is inactive or Email address /Password is Incorrect';
}
} else {
echo '<div> <ol>';
foreach ($error as $key => $values) {
echo ' <li>'.$values.'</li>';
}
echo '</ol></div>';
}
if(isset($msg_error)){
echo '<div>'.$msg_error.' </div>';
}
/// var_dump($error);
} // End of the main Submit conditional.
?>
Here is the beginning of my protected index.php
<?php
ob_start();
session_start();
if(!isset($_SESSION['email'])){
header("Location: login.php");
}
include 'header.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
.....
There must be a problem with my session and I do not know why. Is it wrong to use the email as session? Am I using the email as session? What other options do I have?
Problem is right now, that if I click on Login, nothing happens. I will be redirected to login.php instead of index.php!
Any suggestions?
As Fred -ii- already mentioned in comments above, your $_SESSION['email'] is never set, and therefor you are re-directed to your login-page every time.
It's also worth noting that when using header("Location: ...");, you can not have any output prior to the header! Otherwise the header will fail. Output is generally any HTML, echo, whitespace (see this SO).
So, once you make sure that your header("Location: index.php"); actually works, move on to fixing your $_SESSION.
$_SESSION = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC); does not set $_SESSION['email'] (as already stated by Fred -ii-). To fix this, you need to fix your results from the database.
$row = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);
$_SESSION['email'] = $row["email"];
The code above will return the row "email" from the result in the database, and set it to the session of "email", which later is checked when you are trying to access index.php.
A couple of side-pointers (not really your current problem, but a few tips to make your code better).
You should use exit; after using header("Location: ..."); (See this SO)
You are not hashing your password, so it's stored in plain-text in your database (big no-no)
Indenting your code properly makes it a lot easier to read, and in turn easier to troubleshoot
If you do the above, and it still doesn't work, we'd need some more information to help troubleshoot further (like what happens when you're logging in (is it as expected?), what results are returned, and so forth).
try to change,
$_SESSION = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);
to
$results = mysqli_fetch_row($result_check_credentials, MYSQLI_ASSOC);
$_SESSION['email']=$results['email'];
and try to check your "activation" field in database for null while login...

Seeking advice on Simple profile system

I want to create simple profile system. I want to display data of user from the database on the profile page. I dont want to make setting page. I just simply want to display it.
There are three columns in db right now, Id,username and password. I am adding first name,lastname, about me and about me to database.
I want to improve on my current php page and dont want to create new page. Please give me advice on how can i create simple profile system?
Here is my code of index.php
<?php
session_start();
if(isset($_SESSION['user'])){
header("location: profile.php");
echo "Welcome ".$_SESSION['user']." !";
}
else{
display_form();
}
function display_form(){
?>
<form action="verify.php" method="POST">
Name:<input name = "username" type = "text" />
Pass:<input name = "password" type = "text" />
<input name = "submit" type="submit" />
</form>
<?php
}
?>
My code of profile.php
<?php
session_start();
if (isset($_SESSION['user'])){
$loggeduser = $_SESSION['user'];
echo "Welcome ".$loggeduser." !";
?>
Log out now!
<?php
//Start displaying profile
}
else
header("location: index.php");
?>
Code of verification page
<?php
session_start();
//Make sql connection and select databases
$database_connect = mysql_connect('localhost','root','');
if(!$database_connect){
die('Could not connect to databse');
}
else{
echo "Connected to database successfully!<br/>";
}
$db_table_connect = mysql_select_db('selftest');
if(!$db_table_connect){
echo "Connection to table failed";
}
else{
echo "Connected successfully to table!<br/><br/>";
}
//Begin with user verifications
if(isset($_POST['submit'])){
$username = $_POST['username'];
$userpass = $_POST['password'];
$sql = "SELECT * FROM users WHERE username = '$username' and password = '$userpass'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count == 1){
echo "Successfully logged in!";
$_SESSION['user'] = $username;
header("refresh:5;url=profile.php");
}
else{
echo "Failed to log in!";
header("refresh:5;url=index.php");
}
}
Such questions are not acceptable in SO Read This.
But i'll try to help.
1) Never trust user input, always sanitize it. you are inputting login information directly in query. Thats a SQL injection right there. Read prevent SQL injection
2) mysql API is deprecated, means its production will stop soon. make habit of using new API which is mysqli. there is not much difference 90% same. Or PDO which is kind of same thing as mysqli.
3) Try to make use of classes for database interaction. That way you can easily get query information and show within same page.
For now, you can put the information the result variable of select query in session, do following:
//Code of verification page
if($count == 1){
echo "Successfully logged in!";
$_SESSION['user'] = $username;
$_SESSION['user_info'] = mysql_fetch_array($result);
header("refresh:5;url=profile.php");
}
//Start displaying profile
echo $_SESSION['user_info'][name];
echo $_SESSION['user_info'][aboutme];

PHP Page isn't storing cookies

I am new to php and I am making a basic login script.
All I want to do is log in and have the cookie for my user_id stored.
It works on all of my other pages, except my index page which is one directory up.
So on my index page, I have this if statement:
<?php
if (!isset($_COOKIE['user_id'])) {
sign_in();
} else {
echo "You're already logged in!";
}
?>
No matter what I do, the sign_(); function always shows.
But here's the kicker:
On my login script, the whole thing goes through as if I successfully logged in.
I send it back to this page using:
header("Location: ../index.php");
(It is up one directory)
However, when I make it link to a page in the same directory, it registers the cookie and everything is alright.
header("Location: show_user.php");
If you want a hands on view, you can go to http://patti-bee2.dcccd.edu/coleman/wonder%20penguin/php/signup.php to make your account. And http://patti-bee2.dcccd.edu/coleman/wonder%20penguin/php/show_user.php to view it. And notice how the index page doesn't register the cookie.
How I tried to set the cookie:
if (isset($_POST['usernamelogin'])) {
$user_login = $_REQUEST['usernamelogin'];
$pass_login = $_REQUEST['passwordlogin'];
$pass_login = trim(crypt($pass_login, $user_login));
$login_query = sprintf("SELECT username, user_id FROM user WHERE username = '%s' and password = '%s';", mysql_real_escape_string($user_login), mysql_real_escape_string($pass_login));
$loginresult = mysql_query($login_query, $dbConn);
echo $login_query;
if (mysql_num_rows($loginresult) == 1) {
$userinfo = mysql_fetch_array($loginresult);
$username = $userinfo['username'];
$userid = $userinfo['user_id'];
setcookie('username', $username);
setcookie('user_id', $userid);
header("Location: show_user.php");
exit();
} else {
echo "Couldn't find your account!";
}
}
Please excuse my unrefined page and amateur mistakes. I have a lot to learn.
Any ideas?
Thank you for your time.
Check if you have the cookie with the following
<?php
var_dump($_COOKIE);
//if (!isset($_COOKIE['user_id']))
if (empty($_COOKIE['user_id']))
{
sign_in();
}
else {
echo "You're already logged in!";
}
?>

PHP File cannot recover session variable across pages

Okai, so I attempted to post this a bit earlier, although my question has changed slightly.
I have identified the problem to be in between my login.php (where I assign the $_SESSION value) and my members.php page (where I try to pick up the $_SESSION variable again, but fail to recover it). The way I identified this problem was by running a var dump on session in my members.php file which gave me 0. I also did this after I asign the value in login.php and I got the asigned value as an outcome.
If you help me out I will really appreciate it!
This is my login.php page:
<?php
session_start();
require('connect.php');
$username = $_POST['username'];
$password = $_POST['password'];
if (isset($username) && isset($password))
{
$query = mysql_query("SELECT * FROM login WHERE username='$username' AND password='$password'");
$result = mysql_num_rows($query);
if($result > 0)
{
echo "You have been logged in. <a href='members.php'>Go to the members page</a>";
$username = $_SESSION['login'];
}
else
{
echo "Password is incorrect. Try again.";
}
}
else
{
echo "You have to enter your username and password. Try again";
}
?>
This is my members.php page:
<?php
session_start();
if (isset($_SESSION['login']))
{
echo "Welcome " . $login . " | <a href='logout.php'>Logout</a>";
}
else
{
header('Location: index.php');
}
?>
Solved in Chat:
Turns out var_dump(is_writable(session_save_path())); returned bool(false).
The session_save_path() was /var/php_sessions/.
realpath(dirname(__FILE__)); was /hermes/bosoraweb124/b185/dom.gjertgjersundcom/public_html.
I tried moving the session save path -- however for some reason the folder within public_html couldn't be written, same with read (couldn't read). In any case, it's a bad idea to have sessions in the public folder for everyone to see anyway.
I recommended the OP contact their host provider to run the command of chmod 766 -R /var/php_sessions/.
Solved: The staff at his webhost applied the permissions and it works fine now.
Your session "login" variable is not set because you never set it in your login file...
You should specifically set it with $_SESSION['login'] = "blah";
I assume your problem is you meant to set login and not the username when you log in the user...
swap
if($result > 0)
{
echo "You have been logged in. <a href='members.php'>Go to the members page</a>";
$username = $_SESSION['login'];
}
with
if($result > 0)
{
echo "You have been logged in. <a href='members.php'>Go to the members page</a>";
$_SESSION['login'] = $username;
}
Then you should be able to access your "login" session variable from your member page.
Also on your member page I do not see you set your $login variable. So I assume that would be a blank space and you meant to echo your session login variable with $_SESSION['login'].

When I successfully login an extra function.session-start is displaying and how to check session for sign-in-action page

I have a sign-in-action-form page which accept username and password from sign-in-form. Now most of things are working fine like on sign-out if I press back button logout display and session is destroyed. But I am facing a very strange problem. When I login and if login is successful a link function.session-start is shown on this page. I have not make any href like this I don't know from where this link come but it is disturbing my page. What is this error and how I can remove it. Second thing is there any method to check session for this page. I know there would be, but listen we are starting session and assigning value to session variable when our username and password are valid and if I apply checking for this page on the onload event it will show logged out because onload I have not started session done some thing like this. I don't know much about this. But I think I have explained my problem.
sign-in-action-form.php
$con=mysql_connect("localhost","root","");
if(!$con)
{
die('Could Not Connect:'.mysql_error());
}
mysql_select_db("tcs",$con);
$usr=$_POST["username"]; //pick username from login page
$pwd=hash('sha1',$_POST['password']); //pick password from login page and use hash algorithm to encrypt it
$query="select * from employee where Username='$usr' and Password='$pwd'"; //serch that single row in which both r found
$result=mysql_query($query,$con);
if ($result)
{
$row=mysql_fetch_array($result);
if (($row["Username"]==$usr) && ($row["Password"]==$pwd))
{
session_start();
$_SESSION['employee']['id']=$row['User Id'];
$_SESSION['employee']['username']=$row['Username'];
echo "<font color=red>"."<h3 align=center>"."Welcome ".$_SESSION['employee']['username']."</h3>"."</font>";
echo "<br />"."<a href='upload_file.php'>"."<font color='white'>"."<h4>"."Up-Load Files"."</h4>"."<font>"."</a>";
echo "<br />"."<br />"."<a href='list_files.php'>"."<font color='white'>"."<h4>"."List All Up-Loaded Files"."</h4>"."<font>"."</a>";
}
else
{
echo "Login Not Successfull";
}
}
}
else
{
echo 'Error! Username & Password were not sent!';
}
?>
</font>
<font color="white"><h3 align="right">Sign Out</h3></font>
<font color="white">
</body>
</html>
session.php
<?php
session_start();
if(!isset($_SESSION['employee']))
{
echo "Your are Logged Out";
exit;
}
else
{
echo "<blink>"."Welcome Mr.".$_SESSION['employee']['username']."</blink>";
}
?>
Implement a middle step like, "You have been logged out, redirecting you to front-page"

Categories