PHP - getting user first name from mysql database (session.php) - php

I'm trying to show welcome message with user name. I have a session setted up, everything is working without errors, however I can't make user name appear next to "welcome". I read loads of posts, most of the suggestions were asking to add session_start(); before echo. Still nothing..
Here is code for session.php if someone could help me:
<?php
session_start();
$message="";
if(count($_POST)>0) {
$conn = mysql_connect("**.***.***.***", "*********", "*********");
mysql_select_db("*********",$conn);
$result = mysql_query("SELECT * FROM WebsiteUsers WHERE user_name='" . $_POST["fname"] . "' and password = '". $_POST["password"]."'");
$row = mysql_fetch_array($result);
if(is_array($row)) {
$_SESSION["UserID"] = $row[user_id];
$_SESSION["fname"] = $row[user_name];
} else {
$message = "Invalid Username or Password!";
}
}
if(isset($_SESSION["user_name"])) {
header('Location: login.php');
}
?>
And here is code for the profile page where user name should appear:
<?php
include('session.php'); //file shown above
?>
<!DOCTYPE html>
<html>
<head>
<title>Your Home Page</title>
</head>
<body>
<div id="profile">
<b id="welcome">Welcome : <i>
<?php
session_start();
echo $_SESSION['fname'];
?>
</i></b>
<b id="logout">Log Out</b>
</div>
</body>
</html>
I'm just learning PHP and this is a basic test.
Thank You for any information.
Hava a nice day !
UPDATE:
loginscript.php
<?php
session_start();
$error='';
if (isset($_POST['submit'])) {
if (empty($_POST['uname']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
$uname=$_POST['uname'];
$password=$_POST['password'];
$conn = mysql_connect("**.***.***.***", "*********", "*********");
$uname = stripslashes($uname);
$password = stripslashes($password);
$uname = mysql_real_escape_string($uname);
$password = mysql_real_escape_string($password);
$db = mysql_select_db("*********", $conn);
$query = mysql_query("select * from WebsiteUsers where password='$password' AND uname='$uname'", $conn);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$uname;
header("location: profile.php");
} else {
$error = "Username or Password is invalid";
}
mysql_close($conn);
}
}
?>
logout.php:
<?php
session_start();
if(session_destroy())
{
header("Location: login.php");
}
?>

You need to quote your array keys, for example you have:
$_SESSION["UserID"] = $row[user_id];
But this should in fact be
$_SESSION["UserID"] = $row['user_id'];
Note the single quotes around the array key in $row. I see you use double quotes and I think there are minor differences but the point is, use quotes around array key strings. Please read https://stackoverflow.com/a/2317969/3536236 .
There also might be an issue that you set the value with double quotes and then call the value with single quotes --
$_SESSION["fname"] = $row['fname'];
print $_SESSION['fname'];
But that's just a theory there.
Further debugging:
Print_r($_SESSION); <== what does this give you after the values are set?
Use MySQLi or PDO rather than MySQL_ as this is now deprecated and should no longer be used.
Add exit; after your header relocation calls. Because the rest of the script will still execute before the relocation header call is run, so you need to tell the script to stop executing as soon as you reach the header(location: ) point.
Be consistent and have all single ' or all double " quotes in your array key identifiers.
Remove session_start() from inside your HTML, this function call MUST be at the very start/ top of the page, and nowhere else. You can replace this session_Start with the print_r referenced above, for debugging purposes.
Debugging
First step, you need to enable errors on your page, so whatever page you're working on add this code to the top:
error_reporting(E_ALL);
ini_set('display_errors', 1);
This will output any errors the code fines to your browser when you run the page. Extremely useful and informative.
Next, I will show you the process you need to establish where in the logic chain the data is being "lost".
$result = mysql_query("SELECT * FROM WebsiteUsers WHERE user_name='" . $_POST["fname"] . "' and password = '". $_POST["password"]."'");
print_r($result) <== should return something like "this is a type 4 element". False shows your DB is empty or your MySQL code is bad.
$row = mysql_fetch_array($result);
var_dump($row) <== should return the values from the DB. It should also tell you what data type this variable is, as you demand an array, below:
if(is_array($row)) {
$_SESSION["UserID"] = $row[user_id];
$_SESSION["fname"] = $row[user_name];
}
else {
die("This will display if the IF statement does not show TRUE.");
}
The die statement above would show you that the error is not in the session but more in your handling of the MySQL output,
I reaffirm you should use single quotes on all your array keys everywhere! Keep it consistent!!
Restructure your MySQL to be more this shape:
mysql_query($query) or print_r("line ".__LINE__.": ".mysql_error());
So that if there is any issue with your MySQL code it is found and shown to you. Much of programming is about finding where the error comes from, rather than the error itself.

Try something like this:
$db_result = mysql_fetch_array($result); $row = $db_result[0];
instead of :
$row = mysql_fetch_array($result);

<?php
session_start();
$message="";
if(count($_POST)>0) {
$conn = mysql_connect("**.***.***.***", "*********", "*********");
mysql_select_db("*********",$conn);
$result = mysql_query("SELECT * FROM WebsiteUsers WHERE user_name='" . $_POST["fname"] . "' and password = '". $_POST["password"]."'");
if(mysql_num_rows($result)>0) {
$row = mysql_fetch_array($result);
$_SESSION["UserID"] = $row[user_id];
$_SESSION["fname"] = $row[user_name];
} else {
$message = "Invalid Username or Password!";
}
}
if($_SESSION["fname"]=="") {// changed from $_SESSION['user_name'],checks if sesison is empty , will redirect to login page.
header('Location: login.php');
}
?>

You have to use session_start(); in the start of the profile.php

Related

debug some PHP code

I am trying to make login with angularjs and PHP. But hitting problem I cannot understand why?
<?php
date_default_timezone_set("Asia/Bangkok");
session_start();
$data = json_decode(file_get_contents("php://input"));
$email = mysql_real_escape_string($data->email);
$password = mysql_real_escape_string($data->password);
{
$con=mysqli_connect("localhost","root","thanh03021986","erp");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = mysqli_query($con,"SELECT email, password FROM user WHERE email = '$email'");
$numrow = mysqli_num_rows($query);
if($numrow > 0){
while($rows = mysqli_fetch_array($query))
{
$dbemail = $rows['email'];
$dbpassword = $rows['password'];
}
$con->close();
if($email==$dbemail && $password == $dbpassword){
$_SESSION['uid'] = $email;
header('location:/A.php');
}
}
}
?>
When the If() return true the $_SESSION['uid'] = $email works but the header('location:/A.php'); does not work. I try to put header('location:/A.php'); out of IF(), header works ??? Please help and explain?
The session_start function must be called first as well as the header function must me called before any HTML code.
See the headerfunction manual
The redirection with header, you must be sure that there's nothing in the html already (not even the <html> tag), and an absolute path. So, you should do this in order to work:
header('Location: http://pathblablabla.bla/A.php');
Also, note that I put Location, not location. Not sure if it's case-sensitive, but just in case...

Geting ID from table in SQL through PHP

I am trying to create a logout page using session_destroy() but all i get is a blank page.
This is my code about logging in(I assume the problem has to be somewhere here but i am a beginner at this).
What i thought it will work is creating a session for the username since it is used at isset() but apparently its not working.
<?php
session_start();
$dbhost = "";
$dbuser = "";
$dbpassword = '';
$db= 'system_dev';
mysql_connect($dbhost,$dbuser,$dbpassword);
mysql_select_db($db);
include 'test.php';
if (isset($_POST['username'] )) {
$username=$_POST['username'];
$password=$_POST['password'];
$_SESSION['username']=$username;
$sql ="Select * FROM Company WHERE username='".$username."'AND password = '".$password."'LIMIT 1";
$sqlid = "Select CompanyId FROM Company WHERE username='".$username."'";
$result = mysql_query($sql);
$resultid= mysql_query($sqlid) or die('Query failed: '. mysql_error());
while ($row =mysql_fetch_array($resultid,MYSQL_ASSOC) ) {
echo "<tr>\n";
foreach ($row as $col_value){
echo "$col_value\n";
}
}
$company = mysql_free_result($resultid);
$_SESSION['CompanyId'] = $col_value;
}
if ( mysql_num_rows ($result)==1){
header ("Location: webdesign.php");
exit();
}
else {
echo "Invalid input";
exit();
}
?>
On the code of "logout.php" I have only written this:
<?php
session_start();
session_destroy();
header ("website.php");
?>
Thanks in advance and sorry if the answer is not how it should be. I have read the rules but this is the 2nd post so far. I believe i will get better someday :)
You should use Location in your header argument like header("Location: page.php");
you can place this header after you destroyed the session, that should not give any problems.
As Dorco said:
You should use Location in your header
So the logout function should looks like this:
session_destroy();
session_regenerate_id(TRUE);
header("Location: login.php");
die();
And I strongly suggest you, so not simply insert the post value into the SQL query. That will cause a SQL injection. Use prepare statement instead. PHP: Prepared Statement

mySQL statement not working inside of php

Im trying to do a login system for my website and I changed around how it is implemented and it broke, whenever I try to login with a correct login it fails to take me to the next page, here is my php:
<?php
//finds the correct database
$sql_link = mysqli_connect("localhost", "root" , "12buckle", "GameData");
if (mysqli_connect_errno())
{
echo "Failed to connect to databse: " . mysqli_connect_error();
}
if (isset($_POST['Username']))
{
$username = mysql_real_escape_string($_POST['Username']);
$password = mysql_real_escape_string($_POST['Password']);
//checking to see if password and username can be found in student database
//loading in correct data
$login = mysqli_query($sql_link,"SELECT * FROM tblStudents WHERE UserName='$username' AND Password='$password'");
if ($login['Password'])
{
$_SESSION['name'] = $login['StudentFirstName'];
$_SESSION['ClassID'] = $login['ClassID'];
$_SESSION['ID'] = $login['StudentID'];
header ("Location: index.php");
}
else
{
$login = mysqli_query($sql_link,"SELECT * FROM tblTeacher WHERE Username='$username' AND Password='$password'");
if ($login['Password'])
{
$_SESSION['name'] = $login['TeacherSurname'];
$_SESSION['title'] = $login['Title'];
$_SESSION['ID'] = $login['TeacherID'];
header ("Location: TeacherSide.php");
}
else
{
echo 'Login details incorrect';
}
}
}
Also if it helps when I ran it last night im sure it worked, but I was half awake so I may have been testing the old version
Your logic is faulty. mysql_query returns a result HANDLE. it does not return any actual data. You need to fetch a row first, before checking for actual data:
$result = mysqli_query($sql_link, "SELECT * FROM tblStduents ....");
if (mysqli_num_rows($result) > 0) {
... got a student record
$row = mysqli_fetch_assoc($result);
echo $row['StudentFirstName'];
} else {
... no student rows, repeat with teachers
}
I've had issues in the past where variables aren't read properly the way you have them in your SQL statements.
Try Username='" . $username . "' AND instead and see what happens.

Variable out of scope when accessed in if/else statement in PHP

I am new to PHP scripting and come from Java background. Here is a trivial thing which has turned into a brainteaser for me as of now. So here is the problem, I assigned a variable some value and when try to use that value inside if/else statement that variable actually doesn't posses the previous assigned value to it. Here is the code:-
<?php
session_start();
$email = $_POST["Email"];
$password = $_POST["Password"];
$db_username="root";
$db_password="root";
$database="mydb";
$localhost = "mysql";
$con = mysql_connect($localhost,$db_username,$db_password);
mysql_select_db($database,$con) or die( "Unable to select database");
$query = "select * from photobook.users where email ='$email' and password ='$password';" ;
$result = mysql_query($query);
$num=mysql_num_rows($result);
if($num == 1){
while($row = mysql_fetch_array($result))
{
$_SESSION['email'] = $row['email'];
$_SESSION['username'] = $row['username'];
}
header("location: home.php");
}
else{
include "photoBookProtocol.php";
print "<br>email value after photobookprotocol file include is $email";
print "<br>password value after photobookprotocol file include is $password";
$obj=new Protocol();
$var = $obj->loginCheck($email,$password);
print "value of var received is $var";
if($var == 0){
session_destroy();
print "<br>user does not exist";
//header("location: login.php");
}
else{
$_SESSION['email'] = $var[0];
$_SESSION['username'] = $var[1];
print "<br>user exists";
header("location: home.php");
}
}
mysql_close($con);
?>
So when I pass the $email and $password in loginCheck($email, $password) inside "else" clause there is nothing passed. Any idea why this is happening?
There is nothing wrong with your variable scope, so either:
There is nothing in the POST data
The include overwrites the two variables
loginCheck() is receiving the correct variables but there is a bug within the function
As a side note, since your script depends on POST data, you should have a condition to check if the required data is present before proceeding:
if(isset($_POST['Email'], $_POST['Password']))
{
// something posted
}

PHP MYSQL question

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!

Categories