Solved

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

Posted on 2012-04-05
7
358 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
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 
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 109

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

ScreenConnect 6.0 Free Trial

Check out the updates in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI that improves session organization and overall user experience. See the enhancements for yourself!

Question has a verified solution.

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

This article describes how to create custom column layout styles for Bootstrap. The article uses 5 columns to illustrate the concept, but the principle can be extended to any number of columns.
Is your Office 365 signature not working the way you want it to? Are signature updates taking up too much of your time? Let's run through the most common problems that an IT administrator can encounter when dealing with Office 365 email signatures.
In this tutorial viewers will learn how to style elements, such a divs, with a "drop shadow" effect using the CSS box-shadow property Start with a normal styled element, such as a div.: In the element's style, type the box shadow property: "box-shad…
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…

803 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