Solved

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

Posted on 2012-04-05
7
356 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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
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.
In this tutorial viewers will learn how to style transparent/translucent elements using alpha transparency in CSS Start with a normal styled element, such as a div.: Define its "background-color" property as "rgba (255, 255, 255, .5): The numbers in…
In this tutorial viewers will learn how to code links for mobile sites that, once clicked, send a call or text to a specified number. For a telephone link (once clicked, calls a number), begin with a normal "<a href=" link tag. For the href, specify…

743 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

11 Experts available now in Live!

Get 1:1 Help Now