i am creating a profile page and a login page where i store the session id and then in the profile file i check if isset or not but the problem that i get is that the system always display an error message and i used print_r($_SESSION); the browser display :
Important data are missingArray ( [first_name] => [email] => )
how to fix this error?????
login.php
<?php
session_start();
error_reporting(E_ALL);
require_once('include/connect.php');
$message = "";
if(!empty($_POST['email']))
{
$email = $_POST['email'];
$pass = $_POST['pass'];
$email = strip_tags($email);
$pass = strip_tags($pass);
$email = mysql_real_escape_string($email);
$pass = mysql_real_escape_string($pass);
//$pass = md5($pass);
$sql=mysql_query( "SELECT user_id, email_address, first_name FROM user WHERE email_address='$email'AND password='$pass'LIMIT 1") or die("error in user table");
$login_check = mysql_num_rows($sql);
if($login_check > 0)
{
$row = mysql_fetch_array($sql);
$id = $row['user_id'];
$_SESSION['user_id'] = $id;
$firstname = $row['first_name'];
$_SESSION['first_name']= $firstname;
$email = $row['email_address'];
$_SESSION['email_address']= $email;
mysql_query("UPDATE user SET last_log_date=now() WHERE user_id='$id'");
header("Location: profile.php");
}//close if
else
{
$message = "incorrect Email or Password!!";
//exit();
}
}//close if
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>RegisterPage</title>
<link href='http://fonts.googleapis.com/css?family=Oswald:400,300' rel='stylesheet' type='text/css' />
<link href='http://fonts.googleapis.com/css?family=Abel|Satisfy' rel='stylesheet' type='text/css' />
<link href="default.css" rel="stylesheet" type="text/css" media="all" />
</head>
<body>
<div id="loginborder">
<p style="color:#FF0000" align="left"><?php print("$message") ?></p>
<!--Login form where user submit his registered email and password-->
<form action="login.php" method="post">
email-address:<br />
<input type="text" name="email" placeholder="Email Adress" />
<br />
<br />
Password:<br />
<input type="password" name="pass" placeholder="Password" />
<br />
<br />
<input type="submit" name="login" value="Login" />
<strong> Register</strong>
</form>
</div>
profile.php
<?php
session_start();
require_once('include/connect.php');
if(isset($_GET['user_id']))
{
$id=$_GET['user_id'];
var_dump($id);
}
elseif(isset($_SESSION['user_id']))
{
$id= $_SESSION['user_id'];
}
else
{
print "Important data are missing";
print_r($_SESSION);
exit();
}
$sql = mysql_query("SELECT * FROM user WHERE user_id='$id'") or die(mysql_error());
$row = mysql_fetch_array($sql);
$firstname=$row['first_name'];
$lastname=$row['last_name'];
$birth_date=$row['birth_date'];
$registered_date=$row['registered_date'];
//***************for upload img*****************//
$check_pic="members/$id/image01.jpg";
$default_pic="members/0/image01.jpg";
if(file_exists($check_pic))
{
$user_pic="<img src=\"$check_pic\"width=\"100px\"/>";
}
else
{
$user_pic="<img src=\"$default_pic\">";
}
echo $id, $firstname, $birth_date;
?>
You need to changes several things
First : get first_name and email in your request
'SELECT user_id,email,first_name FROM user WHERE email_address='$email'AND password='$pass'LIMIT 1'
Second, remove while loop and do
$row = mysql_fetch_array($sql);
You are limiting to 1 result so no need to loop inside result
Change $id=$_SESSION['user_id']; to $_SESSION['user_id'] = $id;
Also, limit to 1 the result from profile and remove loop (user_id => UNIQUE => LIMIT 1)
all you need to do is just store a value in a session variable [$_SESSION['username']] after everything checks out then select the data from the mysql table using the value in the session
----------------------------------for example------------------------------------------------------
on login.php
if($login_check > 0)
{
$_SESSION['email']=$email;//storing variable in SESSION
header("Location: profile.php");
}
else
{
$message = "incorrect Email or Password!!";
die();// kill the script
}
on profile.php
<?php
session_start();// start session
require_once('include/connect.php'); //include connection file
$sql = mysql_query("SELECT * FROM user WHERE email='(mysql_real_escape_string($_SESSION['email']))'") or die(mysql_error());
$row = mysql_fetch_array($sql);
// then just echo all the data you need
?>
Related
login.php
I just want to prevent the user after the user logout and press the back button he will still logout... in the current state of my project after the user logout and press back button he will go back in the last page and still log in
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=MS932">
<title>Login Page</title>
<link rel ="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id ="frm">
<form action="process.php" method="post" >
<p>
<label>Username:</label>
<input type="text" id="email" name="user" required/>
</p>
<p>
<label>Password:</label>
<input type="password" id="pass" name="pass" required/>
</p>
<p>
<input type="submit" id="btn" value="Login"/>
</p>
</form>
</div>
</body>
process.php
<?php
$username = $_POST['user'];
$password = $_POST['pass'];
$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
mysql_connect("localhost","root","");
mysql_select_db("testproduct");
$result = mysql_query("SELECT * FROM tbluser where email = '$username' and pass='$password'")or die("Failed to query database".mysql_error());
$row = mysql_fetch_array($result);
if($row['email'] == $username && $row['pass'] == $password){
echo "<script>window.location.assign('index.php');</script>";
}else{
echo "<script>alert('Login was unsuccessful, please check your username and password')</script>";
echo "<script>window.location.assign('login.php');</script>";
return false;
}
?>
logout.php
<?php
session_start();
session_destroy();
$_SESSION = array();
header("location: login.php");
?>
Initialize session variable on user login and destroy it on logout. Everytime you go to index.php, you check if that session variable exists or there is a successful login.
http://php.net/manual/en/ref.session.php
process.php
<?php
session_start();
$username = $_POST['user'];
$password = $_POST['pass'];
$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
mysql_connect("localhost","root","");
mysql_select_db("testproduct");
$result = mysql_query("SELECT * FROM tbluser where email = '$username' and pass='$password'")or die("Failed to query database".mysql_error());
$row = mysql_fetch_array($result);
if($row['email'] == $username && $row['pass'] == $password){
$_SESSION['un'] = $username;
echo "<script>window.location.assign('index.php');</script>";
}else{
echo "<script>alert('Login was unsuccessful, please check your username and password')</script>";
echo "<script>window.location.assign('login.php');</script>";
return false;
}
?>
index.php
<?php
session_start();
if(!isset($_SESSION['un'])){
header("location:login.php");
}
...
?>
I am having index.php page as follow which have a login form, that calls login.php page. It creates session values over there.
<?php
session_start();
$con=mysqli_connect("localhost","root","","sam");
if (mysqli_connect_errno($con))
{
echo "Could not connect " . mysqli_connect_error();
}
$id = $_SESSION["id"];
$user_login = $_SESSION["user_login"];
$password_login = $_SESSION["password_login"];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Samsung Ops Guide</title>
<link href="css/index.css" rel="stylesheet" type="text/css" />
</head>
<body>
Tracker
<form action="login.php" method="post" id="login">
<input id="email" placeholder="T-ID" type="text" name="em" />
<input id="email" placeholder="Password" type="password" name="pwd"/>
<input id="loginButton" type="submit" value="Login" name="log" />
</form>
<div id="error1"></div>
</body>
</html>
<?php
if (isset($_SESSION["user_login"]) && isset($_SESSION["password_login"])) {
$query = mysqli_query($con,"select * from employees where Tid='$user_login' and password='$password_login'");
while($row = mysqli_fetch_array($query)){
$ptype = $row["designation"];
}
if($ptype=="agent")
{
header("location:/new/l1/");
}
if($ptype=="l2")
{
header("location:/new/l2/");
}
}
?>
Then having a login.php page which is called when the login form is called.
Login form calls and fetch values from the database and create session according to that.
login.php is as follows :
<?php
session_start();
include "inc_files/connection.php"; // it is only creating a connection with database nothing else
$user_login=$_POST['em'];
$password_login=$_POST['pwd'];
$password_login = md5($password_login);
if(empty($user_login) || empty($password_login))
{
die (retmsg(0,"Please fill T-ID and Password"));
}
$query = mysqli_query($con,"select * from employees where Tid='$user_login' and password='$password_login'");
$read = mysqli_num_rows($query);
if(!$read)
{
die (retmsg(0,"Incorrect T-ID or Password"));
}
else
{
while($row = mysqli_fetch_array($query)){
$id = $row["id"];
$ptype = $row["designation"];
}
$_SESSION["id"] = $id;
$_SESSION["user_login"] = $user_login;
$_SESSION["password_login"] = $password_login;
if (isset($_SESSION["user_login"]) && isset($_SESSION["password_login"]))
{
if ($ptype == "l1")
{echo retmsg(1,"l1");}
if ($ptype == "l2")
{echo retmsg(1,"l2");}
}
}
function retmsg($status,$txt)
{
return json_encode(array('status' => $status, 'txt' => $txt));
}
?>
i am getting an error that
$id = $_SESSION["id"];
$user_login = $_SESSION["user_login"];
$password_login = $_SESSION["password_login"];
are not defined. in index.php
Here, the session variables will be set only when you have logged in. At first time, they are not set and you are trying to access them in these lines (in index.php).
$id = $_SESSION["id"];
$user_login = $_SESSION["user_login"];
$password_login = $_SESSION["password_login"];
firstly you have to check whether they are set, and then access it like:
if(isset($_SESSION["id"]))
$id = $_SESSION["id"];
if(isset($_SESSION["user_login"]))
$user_login = $_SESSION["user_login"];
if(isset($_SESSION["password_login"]))
$password_login = $_SESSION["password_login"];
When you are using the same page for form submission, you can access
$user_login=$_POST['em'];
$password_login=$_POST['pwd'];
only if the form is submitted. ie, On page load the form won't be submitted, which means there won't be any POST variables in the page. So surely it will create problem (the same issue we have discussed above). So here, you have to make sure that the form variables are accessed only if the form is submitted. You can do it by the following lines,
if (!empty($_POST)) // if there are any posted variables
{
$user_login=$_POST['em'];
$password_login=$_POST['pwd'];
$password_login = md5($password_login);
..............................
}
Also make sure that you have added all the code for form submission inside this if condition.
I don't know the exact error. Let try with single quotes.
$id = $_SESSION['id'];
$user_login = $_SESSION['user_login'];
$password_login = $_SESSION['password_login'];**
Code as of 20 January 2014
<?php
session_start();
// connect to the database
include('connect.php');
$message = $_GET['message'];
// check if the form has been submitted then process it
if (isset($_POST['submit']))
{
// Get data from table
//set the id manually for test purposes
$id = "429";
$forename = mysql_real_escape_string(htmlspecialchars($_POST['forename']));
$surname = mysql_real_escape_string(htmlspecialchars($_POST['surname']));
$username = mysql_real_escape_string(htmlspecialchars($_POST['username']));
$email = mysql_real_escape_string(htmlspecialchars($_POST['email']));
$password = mysql_real_escape_string(htmlspecialchars($_POST['password']));
// check for empty fields and display error message
if ($forename == '' || $surname == '' || $username == '' || $password == '' || $email == '')
{
$message = "Please enter data in all fields" ;
header("Location: edit.php?message=$message");
}
else
{
// save the data to the table
mysql_query("UPDATE registration SET forename='$forename', surname='$surname', username='$username', email='$email', password='$password' WHERE id='$id'")
or die(mysql_error());
}
// redirecr and display message
$message = "Your changes have been saved";
header("Location: edit.php?message=$message");
exit;
}
$id=429;// this line could have been $id=$_SESSION['id'];
$result = mysql_query("SELECT * FROM registration WHERE id=$id LIMIT 1")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from the table
$forename = $row['forename'];
$surname = $row['surname'];
$username = $row['username'];
$email = $row['email'];
$password = $row['password'];
//dummy echo
print $message;
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="styles/all.css" />
<link rel="stylesheet" href="styles/forms.css" />
<script type="text/javascript" src="javascript/jquery-1.7.1.min.js"></script>
<link href='//fonts.googleapis.com/css?family=Cantora+One' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Voltaire' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Ubuntu:400,500' rel='stylesheet' type='text/css'>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
</head>
<div class="container">
<form action="" method="post" enctype="multipart/form-data" name="edit" id="editrecord">
<fieldset>
<legend><span class="headingreg">Edit Details</span></legend>
<div class="formreg">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<br style="clear:left;"/>
<label for="forename">Forename</label><div><input type="text" id="forename" name="forename" class="insetedit" value="<?php echo $forename; ?>"/><br/></div>
<label for="forename">Surname</label><div><input type="text" name="surname" class="insetedit" value="<?php echo $surname; ?>"/><br/></div>
<label for="forename">Username</label><div><input type="text" name="username" class="insetedit" value="<?php echo $username; ?>"/><br/></div>
<label for="forename">Password</label><div><input type="text" name="password" class="insetedit" value="<?php echo $password; ?>"/><br/></div>
<label for="forename">email</label><div><input type="text" name="email" class="insetedit" value="<?php echo $email; ?>"/><br/></div>
<input type="submit" name="submit" class="submit2" value="submit">
</div>
</fieldset>
</form>
<br style="clear:left;"/>
<br style="clear:left;"/>
</body>
</html>
INDENTS REMOVED
I am following a tutorial for editing and deleting stored records in a database.
http://www.falkencreative.com/forum/records/view.php
In the tutorial one page displays the records in a database and another is used to edit the records :
http://www.falkencreative.com/forum/records/edit.php?id=33004
The problem is all the records in the database are displayed. What changes do I need to make so that I can display and edit a record based on a specified id on a single page? e.g.
$id = "429";
Eventually I will use sessions but for testing purpose I want to set the id manually.
I tried putting the code in a single page but got numerous errors e.g. headers already sent.
Here's the edit.php page with my attempt to set the id manually.
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($id, $forename, $surname, $username, $password, $email, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit Record</title>
</head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>Forename: *</strong> <input type="text" name="forename" value="<?php echo $forename; ?>"/><br/>
<strong>Surname: *</strong> <input type="text" name="surname" value="<?php echo $surname; ?>"/><br/>
<strong>Username: *</strong> <input type="text" name="username" value="<?php echo $username; ?>"/><br/>
<strong>email: *</strong> <input type="text" name="password" value="<?php echo $password; ?>"/><br/>
<strong>password: *</strong> <input type="text" name="email" value="<?php echo $email; ?>"/><br/>
<p>* Required</p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = "429";
$forename = mysql_real_escape_string(htmlspecialchars($_POST['forename']));
$surname = mysql_real_escape_string(htmlspecialchars($_POST['surname']));
$username = mysql_real_escape_string(htmlspecialchars($_POST['username']));
$email = mysql_real_escape_string(htmlspecialchars($_POST['email']));
$password = mysql_real_escape_string(htmlspecialchars($_POST['password']));
// check that forename/surname fields are both filled in
if ($forename == '' || $surname == '' || $username == '' || $password == '' || $email == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $forename, $surname, $username, $password, $email, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE login SET forename='$forename', surname='$surname', username='$username', email='$email', password='$password' WHERE id='$id'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM login WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$forename = $row['forename'];
$surname = $row['surname'];
$username = $row['username'];
$email = $row['email'];
$password = $row['password'];
// show form
renderForm($id, $forename, $surname, $username, $password, $email, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
And the view.php page :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View Records</title>
</head>
<body>
<?php
/*
VIEW.PHP
Displays all data from 'players' table
*/
// connect to the database
include('connect-db.php');
// get results from database
$result = mysql_query("SELECT * FROM login")
or die(mysql_error());
// display data in table
echo "<p><b>View All</b> | <a href='view-paginated.php?page=1'>View Paginated</a></p>";
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>Forename</th> <th>Surname</th> <th>Username</th> <th>eMail</th> <th>Password</th></tr>";
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array( $result )) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['forename'] . '</td>';
echo '<td>' . $row['surname'] . '</td>';
echo '<td>' . $row['username'] . '</td>';
echo '<td>' . $row['password'] . '</td>';
echo '<td>' . $row['email'] . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
?>
<p>Add a new record</p>
</body>
</html>
REMOVED FUNCTION AND ERROR VARIABLE
<?php
include('connect.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data
$id = "429";
$forename = mysql_real_escape_string(htmlspecialchars($_POST['forename']));
$surname = mysql_real_escape_string(htmlspecialchars($_POST['surname']));
$username = mysql_real_escape_string(htmlspecialchars($_POST['username']));
$email = mysql_real_escape_string(htmlspecialchars($_POST['email']));
$password = mysql_real_escape_string(htmlspecialchars($_POST['password']));
// check empty fields
if ($forename == '' || $surname == '' || $username == '' || $password == '' || $email == '')
{
// generate error message
echo 'ERROR: Please fill in all required fields!';
}
else
{
// save the data to the database
mysql_query("UPDATE registration SET forename='$forename', surname='$surname', username='$username', email='$email', password='$password' WHERE id='$id'")
or die(mysql_error());
// Redirect
echo "Your changes have been saved";
header("Location: edit.php");
}
}
$id=429;// this line could have been $id=$_SESSION['id'];
$result = mysql_query("SELECT * FROM registration WHERE id=$id LIMIT 1")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$forename = $row['forename'];
$surname = $row['surname'];
$username = $row['username'];
$email = $row['email'];
$password = $row['password'];
//dummy echo
echo 'formatting is messed up';
}
?>
You will just need to replace the $_GET['id'] with the code that provides the id.
If you are using sessions for example, replace $_GET['id'] with $_SESSION['id']
In your code from the file edit.php:
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM login WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
Change to:
$id=429;// this line could have been $id=$_SESSION['id'];
$result = mysql_query("SELECT * FROM login WHERE id=$id LIMIT 1")
or die(mysql_error());
$row = mysql_fetch_array($result);
Of course, in order to get to the point of executing that code, you would need to remove the conditional statements, since you are no longer getting the information from the $_GET.
I also added a LIMIT 1 to the query, so that you only return one record; you probably would anyway, but if id didn't have a unique index (such as a primary key), it may return multiple records.
Also, in this example, you could nearly replace all of the deprecated mysql_ references with mysqli_. It won't protect you the way mysqli can with prepared statements, but it still should work.
Finally, the renderForm function is a poorly formed function. You can only have one <html> declaration per page, and if you called the function more than once, it would have multiple declarations.
I have a separate file called checklog.php which contains my session details
<?php
session_start();
if (!isset($_SESSION['logged'])){
$_SESSION = array();
header('location: login.php');
}
?>
and my main upload page where recipes are being uploaded to the database i'm trying to post the user id into the db but to no avail
<?php
require_once ("checklog.php");
require_once ("function.php");
include_once ("home_start_logged.php");
require_once ("db_connect.php");
//get form data//
$_SESSION['userid']== $_POST['userid'];
$upload = trim($_POST['Upload']);
$mealname = trim($_POST['mealname']);
$ingredients = trim($_POST['ingredients']);
$hours = trim($_POST['hours']);
$minutes = trim($_POST['minutes']);
$recipe = trim($_POST['recipe']);
echo $_SESSION['userid'];
if(trim($_POST['Submit']) =="Upload"){
if($db_server){
//clean the input now we have a db connection//
$mealname = clean_string($db_server, $mealname);
$ingredients = clean_string($db_server, $ingredients);
$hour = clean_string($db_server, $hour);
$minutes = clean_string($db_server, $minutes);
$recipe = clean_string($db_server, $recipe);
$ingredients = clean_string($db_server, $ingredients);
$image = clean_string($db_server,$image);
mysqli_select_db($db_server, $db_database) ;
//check whether the recipe exists//
$query= "SELECT mealname FROM `recipename` WHERE mealname='$mealname'";
$result = mysqli_query($db_server, $query);
if ($row = mysqli_fetch_array($result)){
$message = "Meal already exists. Please try again.";
}else{
//upload recipe to database//
$query = "INSERT INTO `recipename` (
mealname, ingredients, hours, minutes, recipe,
imagepath, userID) VALUES ('$mealname',
'$ingredients','$hours','$minutes','$recipe',
'$image','" . $_SESSION['userid'] . "')";
echo query;
mysqli_query($db_server, $query) or
die("Insert failed. ". mysqli_error($db_server));
}
my form looks like this:
<form method="post" action="upload.php" enctype="multipart/form-data">
<li>
Meal Name
<input type="text" name="mealname" />
</li>
<li>
Ingredients
<input type="text" name="ingredients" />
</li>
<li>
Cooking Time
<input type="number" name="hours" placeholder="Hours" />
<input type="number" name="minutes" placeholder="Minutes" />
</li>
<li>
Recipe
<input type="text" name="recipe"/>
</li>
<li>
Have you got a photo?
<input type="file" name="image" id="image" size="10"/>
</li>
<input type="submit" id="submit" name="Submit" value="Upload" />
</form>
this is my login form where I define $_SESSION
<?php
require_once ("function.php");
//get form data//
$username = trim($_POST['username']);
$password = trim($_POST['password']);
//start session//
if ($username&&$password) {
session_start();
require_once("db_connect.php");
//clean the input now we have a db connection//
$username = clean_string($db_server, $username);
$password = clean_string($db_server, $password);
$repeatpassword = clean_string($db_server, $repeatpassword) ;
mysqli_select_db($db_server, $db_database) ;
//check whether the username exists//
$query="SELECT * FROM Users WHERE Username='$username'";
$result=mysqli_query($db_server, $query) ;
if ($row = mysqli_fetch_array($result)){
$db_username = $row['Username'];
$db_password = $row['Password'];
$db_id = $row['userid'];
if ($username==$db_username&&salt($password)==$db_password){
$_SESSION['username']=$username;
$_SESSION['userid']=$db_id;
$_SESSION['logged']="logged";
header ('Location: phpdatabase.php');
}else{
$message = "<h1>Incorrect Password!</h1>";
}
}else{
$message = "<h1>That user does not exist!</h1>" .
"Please <a href='login.php'>try again</a>";
}
mysqli_free_result($result);
require_once ("db_close.php");
}else{
$message = "<h1>Please enter a valid username/password</h1>";
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Fud.</title>
<link rel="stylesheet" type="text/css" href="site.css" />
</head>
<h1>Login</h1>
<form action='login.php' method='post'>
Username:<input type='text' name='username'><br />
Password: <input type='password' name='password'><br />
<input type='submit' name='submit' value='Login' />
<input name='reset' type='reset' value='reset' />
<h4><a href='register.php'>Register</a></h4>
</form>
<?php echo $message; ?>
Nothing appears in your form named userid so when you set :
$_SESSION['userid']= $_POST['userid'];
$_POST['userid'] is empty, maybe somewhere else you have the user id set in $_SESSION already, if that is the case you don't need to set anything new, just use that.
No session_start(); in your second file.
To access the Session global you need to start the session.
use
$_SESSION['userid']= $_POST['userid'];
not
$_SESSION['userid']== $_POST['userid'];
You are saving value from $_POST array to $_SESSION but there is no such element as $_POST['userid'] in your requesting form.
Solution: It will be best to authenticate user by logging him/her in first. Once the user is logged in you can save userid in your session which will be accessible in every page throughout your session.
Assuming your login form has a text field name userid. Put this in your login check file after starting your session and validating user.
$_SESSION['userid'] = $_POST['userid'];
Now in your page where you are inserting data into database remove line saying
$_SESSION['userid'] = $_POST['userid'];
I'm creating a website that contains a login page, profile page and logout page. I'm using sessions but I have a problem with dealing with sessions and I cannot understand what the error is or where it is to fix it.
The error I get is in the profile.php **(("you need to be loged in to view profiles"))line 8**
anyone have an idea or a solution plz tel me
login.php
<?php
require_once('for members/scripts/global.php');
$message = "";
if(isset($_POST['email'])){
$email = $_POST['email'];
$pass = $_POST['pass'];
//error handeling
if((!$email)||(!$pass)){
$message = "please insert both fields";
}else{
// secure data
$email = mysql_real_escape_string($email);
$pass = sha1($pass);
$query = mysql_query("SELECT * FROM members WHERE email='$email'AND password='$pass'LIMIT 1")or die(mysql_error());
$count_query = mysql_num_rows($query);
if($count_query == 0){
$message = "the information was incorrect!";
}else{
//start the sessions
$_SESSION['pass']=$pass;
while($row = mysql_fetch_array($query)){
$username = $row['username'];
$id = $row['id'];
}
$_SESSION['username'] = $username;
$_SESSION['id'] = $id;
/* to create a cookie on the HDD OF THE user
if($remember == "yes"){
//create the cookies
setcookie("id_cookie", $id, time()+60*60*24*100,"/");
setcookie("pass_cookie", $pass, time()+60*60*24*100,"/");
}
*/
header("Location:profile.php");
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link href="style/stylesheet.css"rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="container center">
<p><?php print("$message") ?></p>
<form action="login.php" method="post">
<input type="text" name="email" placeholder="Email Adress" /><br />
<input type="password" name="pass" placeholder="Password" /><br />
<input type="submit" name="login" value="Login" />
<strong> Register</strong>
</form>
</div>
</body>
</html>
profile.php
<?php
ob_start();
session_start();
require_once('for members/scripts/global.php');
if($logged == 0){
echo("you need to be loged in to view profiles");
exit();
}
if(isset($_GET['id'])){
$id=$_GET['id'];
$id= preg_replace("#[^0-9]#","",$id);
}else{
$id=$_SESSION['id'];
}
//collect member information
$query = mysql_query("SELECT * FROM members WHERE id='$id'LIMIT 1") or die("could not collect user information ");
$count_mem = mysql_num_rows($query);
if($count_mem == 0){
echo("the user does not exit");
exit();
}
while($row = mysql_fetch_array($query)){
$username = $row['username'];
$fname = $row['firstname'];
$lname = $row['lastname'];
$profile_id= $row['id'];
if($session_id == $profile_id){
$owner = true;
}else{
$owner = false;
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php print("$fname"); ?> <?php print("$lname"); ?>'s profile</title>
<link href="style/stylesheet.css" type="text/css"/>
</head>
<body>
<div class="container center">
<h1><?php print("$username"); ?></h1>
<?php
if($owner == true ){
header("Location: profile.php");
?>
<!--
edit profile<br />
account settings<br />
-->
<?php
}else{
header("Location: index.php");
?>
<!--
private message<br />
add as friend<br />
-->
<?php
}
?>
</div>
</body>
</html>
<?php flush(); ?>
logout.php
<?php
session_start();
session_destroy();
/*
if(isset($_COOKIE['id_cookie'])){
setcookie("id_cookie", "", time()-50000,"/");
setcookie("pass_cookie", "", time()-50000,"/");
}
*/
if(isset($_SESSION['username'])){
echo("we could not log out try again!");
exit();
}else{
header("Location: home.php");
}
?>
global.php
<?php
if(!isset($_SESSION))
{
session_start();
}
require_once('connect.php');
//checking if sessions are set
if(isset($_SESSION['username'])){
$session_username = $_SESSION['username'];
$session_pass = $_SESSION['pass'];
$session_id = $_SESSION['id'];
//check if the member exist
$query = mysql_query("SELECT * FROM members WHERE id='$session_id' AND password='$session_pass'LIMIT 1")or die("could not ");
$count_count = mysql_num_rows($query);
if($count_count == 0){
//loged in stuff here
$logged = 1;
while($row = mysql_fetch_array($query)){
$session_username = $row['username'];
}
//create sessions
$_SESSION['username'] = $session_username;
$_SESSION['id'] = $session_id;
$_SESSION['pass'] = $session_pass;
}else{
header("Location: logout.php");
exit();
}
}
$logged = 0;
/*
elseif(isset($_COOKIE['id_cookie'])){
$session_id = $_COOKIE['id_cookie'];
$session_pass = $_COOKIE['pass_cookie'];
$query = mysql_query("SELECT * FROM members WHERE id='$session_id' AND password='$session_pass'LIMIT 1")or die("could not ");
$count_count = mysql_num_rows($query);
if($count_count > 0){
//loged in stuff here
$logged = 1;
}else{
header("Location: logout.php");
exit();
}
//if user is not log in
}
*/
?>
You're using $_SESSION without properly starting the session with line session_start() in your login.php page.
There are a few thing that can be wrong with what you have written. The $logged == 0 is defined in global.php I suppose. Is it starting the session in it as well (i.e., do you have session_start() in global.php)?
As far as I can see $logged could be whatever and thus you get the error. Starting the session in logging.php also should be fixed if not in global.php.
ok. Take everything out of global.php. If you want leave only session_start() but remove it from login.php and profile.php.
Then you have to move the sql query that checks the password and the username against the database to login.php instead of global.php and have it like this.
//check if the member exist
$query = mysql_query("SELECT * FROM members WHERE id='$session_id' AND password='$session_pass'LIMIT 1")or die("could not ");
$count_count = mysql_num_rows($query);
if($count_count == 0){
//loged in stuff here
$logged = 1;
header("Location: profile.php");
while($row = mysql_fetch_array($query)){
$session_username = $row['username'];
}
//create sessions
$_SESSION['username'] = $session_username;
$_SESSION['id'] = $session_id;
$_SESSION['pass'] = $session_pass;
}else{
$logged = 0;
header("Location: logout.php");
exit();
}
you do not need these in login.php (replace them with the code above)
$message = "";
if(isset($_POST['email'])){
$email = $_POST['email'];
$pass = $_POST['pass'];
//error handeling
if((!$email)||(!$pass)){
$message = "please insert both fields";
}else{
// secure data
$email = mysql_real_escape_string($email);
$pass = sha1($pass);
$query = mysql_query("SELECT * FROM members WHERE email='$email'AND password='$pass'LIMIT 1")or die(mysql_error());
$count_query = mysql_num_rows($query);
if($count_query == 0){
$message = "the information was incorrect!";
}else{
//start the sessions
$_SESSION['pass']=$pass;
while($row = mysql_fetch_array($query)){
$username = $row['username'];
$id = $row['id'];
}
$_SESSION['username'] = $username;
$_SESSION['id'] = $id;