Solved

How do I display a php session variable within my html?

Posted on 2012-04-05
7
357 Views
Last Modified: 2012-04-06
I am making a simple website that a user can log into a look at some pictures. I'm doing this with php, but no mysql at the moment. I'm trying to print out a message above the website images that says "welcome prebek." "prebek" is the username and "wow" is the password. As you can see, the website just says "Welcome ." at the moment. I'm trying to use the code below to display the welcome message but the $username variable isn't being accessed correctly. I also pasted the process_login.php file below which shows the creation of a session when the user logs in. Any idea why the username won't display correctly?

echo "<span id='loginSpanText'>Welcome <php?$username?>.</span>";


<? ob_start(); ?>
session_start();

<?php 
	$fh = fopen("users492831.txt", 'r') or die("can't open file");
	$wordArray = explode(';', implode(';', array_map('trim', file('users492831.txt')))); //trim removes /n at end of each line
	
	$username = $_POST["username"];
	$password = $_POST["password"];
	$exists = false;
	$loggedin = false;
	
	for($i=0;$i<count($wordArray);$i++)
		{
		if($wordArray[$i] == trim($username) && $wordArray[$i+1] == trim($password))
			{$exists = true;}
		}
	fclose($fh);
	
	if($exists == true){ //save cookie if login works
		session_start();
		$_SESSION["loggedin"] = true;
	    $username = trim($_POST['username']);
	    $password = trim($_POST['password']);
		$loggedin = true;
        header("Location: pictures.php");
	}	
	else{
        header("Location: login.php");		
	}
?>
<? ob_flush(); ?>

Open in new window

0
Comment
Question by:shampouya
7 Comments
 
LVL 3

Expert Comment

by:tobyweston
ID: 37814212
If the text you posted is already in <?php tags then you will not need them around the variable.

<?php

echo "<span id='loginSpanText'>Welcome $username .</span>";


?>

Open in new window

0
 
LVL 4

Expert Comment

by:Red_Tech
ID: 37814292
echo "<span id='loginSpanText'>Welcome '. $username .'.</span>";
0
 

Author Comment

by:shampouya
ID: 37814375
Hmm those changes didn't seem to work. Do lines 20-25 of the code above need to be changed in order to access $username?
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 3

Accepted Solution

by:
tobyweston earned 400 total points
ID: 37814413
Change:

 
$username = trim($_POST['username']);

Open in new window


To:

 $_SESSION['username'] = trim($_POST['username']);

Open in new window


Then on the pictures page do:

$username = $_SESSION['username'];

echo "<span id='loginSpanText'>Welcome $username .</span>";

Open in new window

0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 100 total points
ID: 37814527
@shampouya: I thought we talked about this before. NEVER put session_start() inside a conditional construct like under an if() statement.  That is like driving on the wrong side of the road.  You can get away with it some of the time, but common sense argues against it, and eventually it will cause you a great deal of trouble.  You now have two session_start() statements in your script.  Do you know what that will do?  Neither does anyone else.

Going back to the script we had earlier, you were using redirection to different pages.  Here is that script.  See line 28.
<?php // RAY_temp_shampouya.php
error_reporting(E_ALL);

// ALWAYS START THE SESSION UNCONDITIONALLY ON EVERY PAGE
session_start();

// THIS SIMULATES READING THE FILE INTO A STRING VARIABLE
// $url = 'users492831.txt';
// $str = file_get_contents($url);
$str = 'prebek;wow;';

// BREAK THE STRING INTO AN ARRAY
$arr = explode(PHP_EOL, $str);

// PROCESS EACH OF THE ARRAY ELEMENTS INTO A USER NAME AND PASSWORD
foreach ($arr as $udata)
{
    // PUTS USER IN ARRAY[0] AND PWD IN ARRAY[1]
    $x = explode(';', $udata);

    // IF USER NAME MATCHES
    if ($x[0] == $_POST['username'])
    {
        // IF PASSWORD ALSO MATCHES
        if ($x[1] == $_POST['password'])
        {
            // SET THE USER NAME IN THE SESSION
            $_SESSION["loggedin"] = $x[0];

            // REDIRECT
            header("Location: pictures.php");
            exit;
        }
    }
}
// IF WE GET HERE, THERE WAS NO MATCH FOR THE LOGIN
header("Location: login.php");
exit();

Open in new window

Now you can find the user name in $_SESSION["loggedin"] and all you need to do is
echo "WELCOME " . $_SESSION["loggedin"];

Open in new window

0
 
LVL 2

Expert Comment

by:eechincs
ID: 37815613
Hi shampouya,

When the password is correct, assign the user name to the session variable, and print out the session variable at the page you want to display

       <?php        
        session_start();

      $fh = fopen("users492831.txt", 'r') or die("can't open file");
      $wordArray = explode(';', implode(';', array_map('trim', file('users492831.txt')))); //trim removes /n at end of each line
      
      $username = $_POST["username"];
      $password = $_POST["password"];
      $exists = false;
      
      for($i=0;$i<count($wordArray);$i++)
      {
            if($wordArray[$i] == trim($username) && $wordArray[$i+1] == trim($password))
                  {$exists = true;}
      }
      fclose($fh);
      
      if($exists == true){ //assign the username to session variable if login works
            
          $_SESSION["user_name"] = trim($_POST['username']);
            header("Location: pictures.php");
      }      
      else{
            header("Location: login.php");            
      }
        ?>




and in the pictures.php, just print out the user name as following:

<?php
if(isset($_SESSION['user_name'])){
   echo 'Welcome '.$_SESSION['user_name'];
} else {
   echo 'You are not logged in.';
}
?>

BR,
eechincs
0
 

Author Closing Comment

by:shampouya
ID: 37818190
thanks guys
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Not sure what the best email signature size is? Are you worried about email signature image size? Follow this best practice guide.
Finding original email is quite difficult due to their duplicates. From this article, you will come to know why multiple duplicates of same emails appear and how to delete duplicate emails from Outlook securely and instantly while vital emails remai…
In this tutorial viewers will learn how to embed Flash content in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <object> tag to embed Flash content.: To specify that the object is Flash content, d…
The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…

912 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now