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.
Related
Please could someone give me some much needed direction...
I have a registration form, however I need to add a condition that if the username is already in the table, then a message will appear. I have a had a few goes except it just keeps adding to the SQL table.
Any help would be much appreciated. Here is my current code:
Thanks in advance!
<?php
session_start();session_destroy();
session_start();
$regname = $_GET['regname'];
$passord = $_GET['password'];
if($_GET["regname"] && $_GET["regemail"] && $_GET["regpass1"] && $_GET["regpass2"] )
{
if($_GET["regpass1"]==$_GET["regpass2"])
{
$host="localhost";
$username="xxx";
$password="xxx";
$conn= mysql_connect($host,$username,$password)or die(mysql_error());
mysql_select_db("xxx",$conn);
$sql="insert into users (name,email,password) values('$_GET[regname]','$_GET[regemail]','$_GET[regpass1]')";
$result=mysql_query($sql,$conn) or die(mysql_error());
print "<h1>you have registered sucessfully</h1>";
print "<a href='login_index.php'>go to login page</a>";
}
else print "passwords don't match";
}
else print"invaild input data";
?>
User kingkero offered a good approach. You could modify your table so that the username field is UNIQUE and therefore the table cannot contain rows with duplicate usernames.
However, if you cannot modify the table or for other reasons want to choose a different approach, you can first try to run a select on the table, check the results and act accordingly:
$result=mysql_query('SELECT name FROM users WHERE name="'.$_GET['regname'].'"');
$row = mysql_fetch_row($result);
You can then check $row if it contains the username:
if($row['name']==$_GET['regname'])
If this statement returns true, then you can show the user a message and tell him to pick a different username.
Please note
Using variables that come directly from the client (or browser) such as what might be stored in $_GET['regname'] and using them to build your SQL statement is considered unsafe (see the Wikipedia article on SQL-Injections).
You can use
$regname=mysql_escape_string($_GET['regname'])
to make sure that its safe.
Firstly, there is some chaos on the second line:
session_start();session_destroy();
session_start();
Why you doing it? Just one session_start(); needed.
Then you can find users by simple SQL query:
$sql="SELECT * FROM users WHERE name = '$regname'";
$result=mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
//...echo your message here
}
When you got it, I suggest you to rewrite your code with use of PDO and param data binding, in order to prevent SQL injections and using of obsolete functions.
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.
I looked all over. I cannot figure this out.
<?php
session_start();
if (!empty($_POST[username]))
{
require_once("connect.php");
// Check if he has the right info.
$query = mysql_query("SELECT * FROM members
WHERE username = '$_POST[username]'
AND password = '$_POST[password]'")
or die ("Error - Couldn't login user.");
$row = mysql_fetch_array($query)
or die ("Error - Couldn't login user.");
if (!empty($row[username])) // he got it.
{
$_SESSION[username] = $row[username];
echo "Welcome $_POST[username]! You've been successfully logged in.";
exit();
}
else // bad info.
{
echo "Error - Couldn't login user.<br /><br />
Please try again.";
exit();
}
if($isadmin["admin"]==1)
{
echo $admin;
}
else
{
}
}
$admin = <<<XYZ
<div id="admintab">
Admin »
<div id="admin">
ADMIN PANEL
<div id="exitadmin">
</div>
<div id="artistline" />
</div>
</div>
XYZ;
?>
I do know that the $admin value is working. I have tested it. Basically, I have a register system. By default, it sets your admin value to '0'. But let's say i want to add an admin. I change the '0' to a '1' via mysql. I want to know how to make php find users with their admin value set to '1' that are in the database (row name: admin), and display the admin panel to them only.
Why have you used
if($isadmin["admin"]==1)
as you have
$row = mysql_fetch_array($query)
so convert
if($isadmin["admin"]==1)
to
if($row["admin"]==1)
you should check the value before insert and select the data and also use
mysql_real_escape_string($_POST['username'])
so that sql injection not apply
You need to change if($isadmin["admin"]==1) to if($row['admin'] == 1) -- you can leave out the == 1 part if 1 & 0 are the only answers as 1 will always be true and 0 will be false.
Obligitarily, I need to mention that storing passwords in your database in plain text is a bad idea, you should be at the very least hashing them before you store them. Something like $password = hash('sha256', $salt.$_POST['password']) at the registration and login stages.
I should also point out that you shouldn't feed naked values into your database with a query, you don't need to worry about password if you're hashing it, but you do if you're not and you need to do username anyway otherwise anyone can run SQL queries in your database:
$username = mysql_real_escape_string($_POST['username'])
Firstly, I am obligated to point out that not filtering $_POST (and $_GET and $_COOKIE and so on) is very dangerous, because of SQL injection. Secondly, the variable $isadmin doesn't magically exist until you've defined it.
I would suggest designing a more capable user group system, but just to answer the question, the variable you want to check is $row["is_admin"], given that is_admin is a valid column in the table. Also, you don't need to do if ($row["is_admin"] == 1) - 1 evaluates to TRUE in PHP.
I'm creating an e-commerce website. I am working on an admin page that lets the "store manager" log in to do things like add or remove products. In my database, I created a table called admin, with these fields:
id
password
time_last_logged_in
I inserted a row for my store manager, I can see the username and password so I know the person exists in the database, but when I try to log in it echoes out the error below.
admin_login.php
<?php
session_start();
if (isset($_SESSION["manager"])) {
header("location: index.php");
exit();
}
?>
<?php
if (isset($_POST["username"]) && isset($_POST["password"])) {
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["username"]); // filter everything but numbers and letters
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password"]); // filter everything but numbers and letters
// Connect to the MySQL database
include "../scripts/connect_to_mysql.php";
$sql = mysql_query("SELECT id FROM admin WHERE username='$manager' AND password='$password' LIMIT 1"); // query the person
// ------- MAKE SURE PERSON EXISTS IN DATABASE ---------
$existCount = mysql_num_rows($sql); // count the row nums
if ($existCount == 1) { // evaluate the count
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
}
$_SESSION["id"] = $id;
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
header("location: index.php");
exit();
} else {
**echo 'That information is incorrect, try again Click Here';**
exit();
}
}
?>
I use a connect_test.php script to verify that it's connecting to the database and that there's no problem connecting.
index.php
<?php
session_start();
if (!isset($_SESSION["manager"])) {
header("location: admin_login.php");
exit();
}
// Be sure to check that this manager SESSION value is in fact in the database
$managerID = preg_replace('#[^0-9]#i', '', $_SESSION["id"]); // filter everything but numbers and letters
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["manager"]); // filter everything but numbers and letters
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["password"]); // filter everything but numbers and letters
// Run mySQL query to be sure that this person is an admin and that their password session var equals the database information
// Connect to the MySQL database
include "../scripts/connect_to_mysql.php";
$sql = mysql_query("SELECT * FROM admin WHERE id='$managerID' AND username='$manager' AND password='$password' LIMIT 1"); // query the person
// ------- MAKE SURE PERSON EXISTS IN DATABASE ---------
$existCount = mysql_num_rows($sql); // count the row nums
if ($existCount == 0) { // evaluate the count
echo "Your login session data is not on record in the database.";
exit();
}
?>
Why might my code return That information is incorrect, try again Click Here'; instead of a successful validation?
The Problem(s?)
The way I see it, there are several problems with your code. I'll try to address each one and tell you how to solve each issue.
Issue #1: You are using REGEX To strip your code.
There are much better alternatives, the best of which is prepared statements which you should obviously use. Sadly, mysql_* functions don't support it. Which get's me to the next issue:
Issue #2: You are using mysql_* functions.
You shouldn't be using functions like mysql_query() and mysql_num_rows(), instead, consider moving to a better and more secure alternative, such as MySQLi (Good) or PDO (Awesome).
Issue #2.5: You are not using prepared statements.
A Prepared statement is automatically escaped and any malicious code or characters is render useless, same goes for SQL injections. You should use a better database handler that supports it (See Issue #2).
Issue #3: You are testing specifically.
You seem to test only if the row count is equal to exactly one. But what if there are (by accident) 2? Instead of testing what should be, test for what should not be:
if ($existCount != 0) { ...
Issue #4: You are not selecting the correct fields.
You only select the id field in your query, where instead you should be selecting all of the relevant fields (like username and password), in order to receive information.
Issue #5: You are not using secure storing.
If someone were to steal your database, they would have easy access to all your passwords. Consider using an encrypting method like sha1().
Issue #6: You are not testing for errors.
Errors can and will occur, you should test for them, with mysql_query() you should probably do something like
mysql_query("SELECT....") or die(mysql_error());
In PDO that would be something like
if (!$stmt->execute()) { throw new Exception("Execution failed.` . var_export($stmt->errorInfo(), true)); }
Try to correct those, and tell us if your problem persists.
Good luck :)
Try doing:
$sql = mysql_query("SELECT ... LIMIT 1") or die(mysql_error());
Your code assumes the query succeeds, which is very bad form. Always check for error conditions. You may have failed to connect to the database. perhaps your DB is malformed and you've got 2 or more records with the same username/password combo, etc...
I'm new to PHP myself, but I noticed that your select statement in the first code sample above selects only the id. That might be the problem. You should change it to select * and see if that makes any difference.
Good luck
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).