Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

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

Posted on 2012-04-05
7
Medium Priority
?
368 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 3

Accepted Solution

by:
tobyweston earned 1600 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 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 400 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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

This article discusses how to implement server side field validation and display customized error messages to the client.
Q&A with Course Creator, Mark Lassoff, on the importance of HTML5 in the career of a modern-day developer.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.
Suggested Courses

564 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