May be there are already solutions of my problem but I don't know what the exact name of my problem. So I can't search them now and I need post my problem here.
When I log in manually(mean putting username & password with my hand), my profile page shows all data correctly from my database. See the below picture....
Now I am logging out and again log in. This time I checked "Remember me box". Then I closed my browser without logging out. So next time I got access to my home page directly as cookies worked. All are fine till now. But the disaster come when I checked my profile page. See the below picture.... :(
I have used "Username" column to detect the row of table of my database. Because my code doesn't allow same username from another user. Here is the code of the profile page:
session_start();
$name = $_SESSION['username'];
$result = mysql_query("SELECT * FROM store WHERE Username='$name'");
while ($row = mysql_fetch_array($result)) {
$first = $row['Firstname'];
$last = $row['Lastname'];
$use = $row['Username'];
$pas = $row['Password'];
}
Then I just echo them (that four variables $first, $last, $use and $pas) in profile page. So what should I do now?
first make sure that session is set and not empty for that you cam use empty() it will explicit check isset()
session_start();
if (!empty($_SESSION['username'])) {
$name = $_SESSION['username'];
$result = mysql_query("SELECT * FROM store WHERE Username='$name'");
while ($row = mysql_fetch_array($result)) {
$first = $row['Firstname'];
$last = $row['Lastname'];
$use = $row['Username'];
$pas = $row['Password'];
}
}
NOTE 1 : your session is not secure you need to secure session for that there are some good read
PHP Security Guide: Sessions
Sessions and security
PHP Session Security
How safe are PHP session variables?
NOTE 2 : Use of mysql_* function are deprecated even it will generate E_DEPRECATED warning in php5.5 so use PDO or MySQLi instead
session_start();
$name = $_SESSION['username']; // here is the problem
$result = mysql_query("SELECT * FROM store WHERE Username='$name'");
while ($row = mysql_fetch_array($result)) {
$first = $row['Firstname'];
$last = $row['Lastname'];
$use = $row['Username'];
$pas = $row['Password'];
}
you can see by checking that session is set or not by this statement
if (isset($_SESSION['username'])) {
echo "Session is Set";
} else {
echo "Session is not Set";
}
i think error is due to session because it will not be set!
Related
Good day.SO i am having an issue in that, when i create a session via a login and a user is authenticated, once i leave that page to say a different page, i am not whether the session is destroyed or not created in the first place, i require this page to hold the session so i can be able to query the users email from it, and use it to query the database to determine the username.
This is my submit.php, called once the user clicks login on the page.
<?php
session_start();
require_once('connect.php');
if(isset($_POST) & !empty($_POST)){
$email = mysqli_real_escape_string($connection, $_POST['email']);
$password =$_POST['password'];
$sql = "SELECT * FROM `USERS` WHERE EMAIL='$email' AND ENCRYPTEDPWD='$password'";
$result = mysqli_query($connection, $sql);
$count = mysqli_num_rows($result);
if($count == 1){
$_SESSION['email'] = $email;
header("Location: Landing page.php");
exit();
}
else{
header("Location: customerportal.php?login=invalid");
exit();
}
}
?>
it redirects to the next page, the landing page.
This page should check email from the session, and then display a username.
<?php
session_start();
$_SESSION['email'] = $email;
$sql = "SELECT * FROM users WHERE EMAIL='$email';";
$result = mysqli_query($connection,$sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0){
while($row = mysqli_fetch_assoc($result)){
echo $row['username'];
}
}
else{
echo "No User.";
}
?>
Please help.
You have an issue with the landing page in below line:-
$_SESSION['email'] = $email;// here you are assigning to SESSION
It needs to be:-
$email = $_SESSION['email'];//assign value from SESSION to variable
So code needs to be like this:-
$email = $_SESSION['email'];
$sql = "SELECT * FROM users WHERE EMAIL='$email'";
Note:- Your code is wide-open for SQL INJECTION. Try to use prepared statements to prevent it.
mysqli::prepare
In your landing page, invert the line after session_start(): You are assigning an empty variable to overwrite your already saved session variable
$email = $_SESSION['email'];
If your query causes you problems after that, try concatenating $email
$sql = "SELECT * FROM users WHERE EMAIL='".$email."';";
So a couple days ago i had trouble creating a login, one person on that thread recommended me using prepared statements instead.
So I started looking up prepared statements using PDO and I've managed to create the register script with it. However, my login redirects me back to index.php everytime.
file1.php:
<?php
$username=$_POST['username'];
$password=$_POST['password'];
$db = new PDO('mysql:host=localhost;dbname=ismsite', 'db_username', 'db_password'); //this works
$result = $db->prepare("SELECT * FROM users WHERE username=:username AND password=:password");
$result->bindParam(':username', $username);
$result->bindParam(':password', $password);
$result->execute();
$row = $result->fetch(PDO::FETCH_NUM);
if($row > 0) {
session_start();
$_SESSION['userid'] = $row['user_id']; // Initializing Session
$_SESSION['voornaam'] = $row['Voornaam']; // Initializing Session
$_SESSION['achternaam'] = $row['Achternaam'];
$_SESSION['adres'] = $row['adres'];
$_SESSION['email'] = $row['email'];
$_SESSION['username'] = $row['username'];
$_SESSION['password'] = $row['password'];
}
header("location: profile.php");
exit();
?>
On profile.php i have a small bit of code checking if the session with user_id exists. if it doesn't you'll be reverted back to index.php. This would indicate my userid session not being set while i am setting it right there. Either selecting doesn't work the same way as inserting or i have a stupid error.
Can anyone help?
Looks like i made the mistake of using FETCH_NUM instead of using FETCH_ASSOC in:
$row = $result->fetch(PDO::FETCH_ASSOC);
used to be
$row = $result->fetch(PDO::FETCH_NUM);
I'm trying to display the users first name after they login. They login using their email and password. Though, I would like to collect their first name and display it. Their name is in the same table that the email/password are in. Traditionally, I would use a session ID like this below.
<?php
session_start();
$_SESSION['first'] = $first;
?>
But this typically is for submitted data in a form and is used after the form has been authenticated. My question is, how would I gather data from the mySQl table rather than collecting it from the form and be able to have it has a session ID?... if that makes sense
In your script where they login...just fetch the row and store into session...
Im using PDO, because thats much safer than the deprecated mysql_* functions you use in your login example.....
//start the session
session_start();
//Get their credentials, as follows...
$name = $_POST['username'];
$pass = md5($_POST['password']);
$stmt = $db->prepare("SELECT * FROM admin WHERE username=? AND password=?");
$stmt->execute(array($name, $pass));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row > 0 ) {
//Store users info in a session
$_SESSION["username"] = $row["username"];
$_SESSION["firstname"] = $row["firstname"];
$_SESSION["auth"] = "set";
//Redirect to the user area, where you can echo their name
header ("Location: /app");
//Once in the user area, you can just echo their name like so...
//echo "Hello ".$_SESSION['username'].", Welcome to my site";
} else {
//Redirect back to login if their info is incorrect
header('location: /login');
//whatever your login page name might be...
}
But heres the code, if you don't wanna bother changing your site to utilizing PDO...
include("db.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$username=mysql_real_escape_string($_POST['username']);
$password=md5(mysql_real_escape_string($_POST['password']));
$sql="SELECT id, username, firstname FROM admin WHERE username='$username' and passcode='$password'";
$result=mysql_query($sql);
$row = mysql_fetch_row($result);
if(count($row)>0)
{
$_SESSION['auth'] = 'set';
$_SESSION['username'] = $row['username'];
$_SESSION['firstname'] = $row['firstname'];
header ("Location: /app");
}
else
{
$error="Your Hngout credentials are incorrect";
}
}
Select the first name (and any other fields you desire) when checking the user name and password match.
if (!isset($_SESSION)) session_start();
$sql=sprintf("SELECT email, firstname FROM users WHERE email=%s AND password=%s",
$_POST["email"], $_POST["password"]);
//You'd better use parameterized query
$result = mysqli->query($sql);
$row = $result->fetch_assoc();
if(mysqli->num_rows > 0)
{
$_SESSION["email"] = $row["email"];
$_SESSION["firstname"] = $row["firstname"];
}
else
{
//operation for no matches
}
I have this php member page which will show a very basic information from the mysql database.
The issue that i noticed is that if you are logged out and visit the members page i.e. http://www.mywebsite.co.uk/member.php?id=17 and refresh the page from the browser, it will log you into the users account. and it doesn't really matter where and who it is. it will just logs the visitors into that account with id 17 or any other id on PAGE Refresh!!
this is my code for member.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<?php
session_start(); // Must start session first thing
// See if they are a logged in member by checking Session data
$toplinks = "";
if (isset($_SESSION['id'])) {
// Put stored session variables into local php variable
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '' . $username . ' •
Account •
Log Out';
} else {
$toplinks = 'Register • Login';
}
?>
<?php
// Use the URL 'id' variable to set who we want to query info about
$id = preg_replace("[^0-9]", "", $_GET['id']); // filter everything but numbers for security
if ($id == "") {
echo "Missing Data to Run";
exit();
}
//Connect to the database through our include
include_once "config/connect.php";
// Query member data from the database and ready it for display
$sql = "SELECT * FROM members WHERE id='$id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$count = mysqli_num_rows($query);
if ($count > 1) {
echo "There is no user with that id here.";
exit();
}
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$username = $row["username"];
$_SESSION['username'] = $username;
$userid = $row["id"];
$_SESSION['id'] = $userid;
// Convert the sign up date to be more readable by humans
$signupdate = strftime("%b %d, %Y", strtotime($row['signupdate']));
}
?>
anyone can spot the reason why this is happening?
Thanks
Because obviously you're making them logged in. Checkout this line;
$_SESSION['id'] = $userid;
What's your main purpose with this line ?
// Use the URL 'id' variable to set who we want to query info about
$_SESSION['id'] = $userid;
That's the issue right there. Don't pull in data from the url if you want your application to be secure.
After you've checked that their username and password are correct set a variable equal to their user ID and use that value to log them in.
I am trying to do a simple login with PHP and mysql, and using Sessions as well. I have the code, which should work in theory, however it keeps redirecting me to the login page (refreshing it) instead of taking me to the profile.
$username = $_POST['username'];
$query = "SELECT `confirmcode` FROM `fb_network` WHERE `username` = '$username' AND `status`='Confirmed' ";
$result = mysql_query($query);
if (mysql_num_rows($result) == 1){
$result2 = mysql_query($query);
$row = mysql_fetch_row($result2);
$_SESSION['conf_code'] = $row[0];
$uid = $row[0];
session_register($uid);
header('location:profile.php?conf='.$row[0]);
}
else{
echo 'Wrong username';
}
no it shouldn't work in theory
try this
<?php
$username = mysql_real_escape_string($_POST['username']);
$query = "SELECT `confirmcode` FROM `fb_network`
WHERE `username` = '$username' AND `status`='Confirmed' ";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
if ($row = mysql_fetch_row($result)){
session_start();
$_SESSION['conf_code'] = $row[0];
header('Location: profile.php');
exit;
} else {
echo 'Wrong username';
}
but there can be other issues, from code you didn't post here r other reasons.
as a matter of fact, only debugging can tell you what's the problem for sure
I would use a user defined function and make it to check the login credentials and return true or false from the function.
you can use something like this.
function check_login ($username, $password) {
$query = "SELECT `confirmcode` FROM `fb_network` WHERE `username` = '$username' AND `status`='Confirmed' ";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if( mysql_num_rows($result) == 0) {
return false;
}
if( mysql_num_rows($result) == 1) {
$_SESSION['loggedin'] = "true";
header('location:profile.php?conf='.$row[0]);
return true;
}
}
and then call the function easily and display the appropriate message.
check the following code..
<?php
session_start();
/** If the User is already Logged in then redirect to login.php **/
if(isset($_SESSION['loggedin'])){
header("Location: login.php");
}
else {
if( check_login($_POST['username'], $_POST['password'])) {
header('location:profile.php?conf='.$row[0]);
}
}
althoough the code is not exact but this might be enough to get you going.
I see that your code has only two options - display "wrong code" or redirect to the other page. no place where you are redirecting to the login page?
You need to initiate the session by sessions_start() before the rest of the code.
If you have any sort of 'test' script on the profile page that re-directs you if you're not logged in, it may be that the above code logs you in, but does not carry the session variable correctly to the profile page...and subsequently sends the user back to log in again.
Make sure the session is properly initiated on each page using the variable and make sure they match on both ends.
You have two main problems:
You are not using session_start to tell PHP to start tracking sessions
You are using session_register. session_register requires register_globals to be on, which it hopefully is not in your environment. It also expects its argument to be a string which is the name of the variable you wish to store. You should instead use $_SESSION['uid'] = $row[0];
You should also read about SQL injection, a very serious and common security flaw that your code exhibits.
Here is a corrected version of your code:
<?php
session_start(); //it's fine to just do this by habit at the top of every page
$username = $_POST['username'];
//I added mysql_real_escape_string - please read about "sql injection", as it is a very serious and common problem!
$query = "SELECT `confirmcode` FROM `fb_network` WHERE `username` = '".mysql_real_escape_string($username)."' AND `status`='Confirmed' ";
$result = mysql_query($query);
if (mysql_num_rows($result) == 1) {
$result2 = mysql_query($query);
$row = mysql_fetch_row($result2);
$_SESSION['conf_code'] = $row[0];
//not sure if this is what you weree going for or not
$_SESSION['uid'] = $row[0];
header('location:profile.php?conf='.$row[0]);
}
else {
echo 'Wrong username';
}
Then in profile.php, to check if someone is logged in:
<?php
session_start();
if( ! isset($_SESSION['uid']))
//Not logged in!
if( $_SESSION['uid'] != $_GET['conf'])
//trying to access someone else's page!