1

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"><a href="logout.php">Log Out</a></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");
}
?>
Martin
  • 22,212
  • 11
  • 70
  • 132
TaZz
  • 652
  • 7
  • 20
  • 1
    show your session.php file. I have tested your code and it is running fine – LOKESH Dec 16 '15 at 12:11
  • Where the user logins in? Also there is a strange thing on your code here: `if(isset($_SESSION["user_name"]))` if the user_name is ON the session you redirect the user to the login page. It should be the other way around right? like `if( !isset($_SESSION["user_name"]) )` – Jorge Campos Dec 16 '15 at 12:18
  • session.php is the first bit of code. – TaZz Dec 16 '15 at 12:30
  • @user2387628 I have updated my answer for you. Let me know what you find – Martin Dec 16 '15 at 13:00

4 Answers4

2

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.

Community
  • 1
  • 1
Martin
  • 22,212
  • 11
  • 70
  • 132
  • 1
    Print_r($_SESSION); is giving me this : Welcome : Array ( [login_user] => pkirst ) which seems to be ok as I used "pkirst" as my login. – TaZz Dec 16 '15 at 12:42
  • @user2387628 ok so then that means the value is not being saved to the session infact, the code you posted doesn't have that session value in it, so where did `login_user` value get set? – Martin Dec 16 '15 at 12:45
  • @user2387628 change your double quote arrays to single quote arrays and then after the line setting `$result` do: `var_dump($row);` to see what data is actually returned from the MySQL – Martin Dec 16 '15 at 12:48
  • just checked all the files and I think it's from login.php What should I change it to ? So sorry.. I'm new to PHP.. – TaZz Dec 16 '15 at 12:49
  • I changed it all however its not displaying any errors or info. does it matter if I login.php has session set to login_user? – TaZz Dec 16 '15 at 13:13
  • @user2387628 no I was just confused where that value came from, but I then saw your updates. What you should do now is go through your code so that all array keys are wrapped in quotes (single or double), I think that's causing a hiccup for you. – Martin Dec 16 '15 at 13:14
  • got it! by mistake I went from uname to fname. Changed it all and it's working now. Thank you so much! have a nice day mate. – TaZz Dec 16 '15 at 13:31
  • @user2387628 awesome. Glad you found it! – Martin Dec 16 '15 at 13:39
0

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

Alexander Wigmore
  • 3,157
  • 4
  • 38
  • 60
Vipin Singh
  • 543
  • 2
  • 8
  • 24
0
<?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');
}
?>
0

Try something like this:

    $db_result  = mysql_fetch_array($result); $row = $db_result[0];

instead of :

$row  = mysql_fetch_array($result);