?
Solved

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

Posted on 2012-04-05
7
Medium Priority
?
363 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
WordPress Tutorial 3: Plugins, Themes, and Widgets

The three most common changes you will make to your website involve the look (themes), the functionality (plugins), and modular elements (widgets).

In this article we will briefly define each again, and give you directions on how to install them.

 
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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
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 videos in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <video> tag to insert a video. Define the src as the URL of your video; this is similar to …
Suggested Courses

770 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