10now
10now

Reputation: 397

Get value from php file to another

I have a php file called file1.php with a lot of code including this:

$username = $_SESSION['user_name'];

If I echo $username, it shows the name of the logged in user. I created a button where users should register for an event if they click it. That code is in another file. This second file is triggered by file1.php like this:

<form action="file2.php" method="post">
<input type="submit" name="use_button" value="Register for next event" class="btn btn-default"/>
</form>

In file2.php if I check echo $username I don't get the username of the current user. I tried this with sessions and it won't work.

How can I echo the $username in file2.php?

Upvotes: 0

Views: 50

Answers (3)

James Anderson
James Anderson

Reputation: 27478

Each http request is completely independent of any previous or following request.

Once you send your response to the browser your current php program and all its variables are gone.

There are three exceptions to this:-

  • Your $_SESSION variables will persist as long as the browser maintains a session with the web server. But you have to retrieve them on each request.
  • Any cookies you sent out on a previous request should be echoed back to you.
  • Any data you set out in http form fields, providing the user has not altered it.

Upvotes: 0

10now
10now

Reputation: 397

It works now with

session_start();
echo $_SESSION['user_name'];

I could swear I tried this code before and it didn't work :)

Upvotes: 0

Joe Majewski
Joe Majewski

Reputation: 1641

Make sure that you have the session_start(); function being called before headers get sent, and make sure that you are re-populating the value for $username before trying to echo it.

So:

<?php
session_start();
$username = $_SESSION['username'];
echo $username;
?>

That should work.

When you load up the page, you will get access to anything set in the $_SESSION array (assuming you added the session_start() function call).

Thus, you won't be able to persistently store the value in the $username variable between pages (as far as I know); you need to first set it equal to $_SESSION['username']. One way around this is to include a file at the top of each page that handles this kind of thing, that way you don't always need to make that assignment manually in each page.

Upvotes: 2

Related Questions