Reputation: 885
Does anyone know what's wrong with the code below that prevents me from printing in File2.php
the variable $myusername
from File1.php
.
I simply wanna print the variable $myusername
, or if you know any other way of how to pass that variable that would be very helpful for me.
Here is my example:
File1.php
<?php
$myusername=$_POST['myusername'];
function getusername()
{
return $myusername;
}
?>
File2.php
<?php
require_once('File1.php');
getusername();
?>
Upvotes: 1
Views: 2905
Reputation: 27584
You need to declare $myusername
as global when you are trying to access it from within function, you also need to print is somehow (e.g. echo
) ;)
File1.php
<?php
$myusername=$_POST['myusername'];
function getusername()
{
global $myusername; // declare as global
return $myusername;
}
?>
File2.php
<?php
require_once('File1.php');
echo getusername(); // echo value
?>
Read more: PHP Variable scope. You could also pass it via $_SESSION.
Upvotes: 3
Reputation: 8767
I would advocate utilizing $_SESSION
.
Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site.
A visitor accessing your web site is assigned a unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL.
The session support allows you to store data between requests in the $_SESSION superglobal array. When a visitor accesses your site, PHP will check automatically (if session.auto_start is set to 1) or on your request (explicitly through session_start() or implicitly through session_register()) whether a specific session id has been sent with the request. If this is the case, the prior saved environment is recreated.
File1.php
<?php
session_start();
$_SESSION['myusername'] = (isset($_POST['myusername']) ? $_POST['myusername'] : '');
?>
File2.php
<?php
session_start();
echo $_SESSION['myusername'];
?>
You will also notice that in the File1.php
code provided, the $_SESSION['myusername']
declaration is checking if the value was provided first. If it was then set the session variable to that value, otherwise set it to empty.
Upvotes: 4
Reputation: 980
By session.
File1.php
<?php
session_start();
$_SESSION['myusername'] = $_POST['myusername'];
File2.php
<?php
session_start();
echo $_SESSION['myusername'];
Upvotes: 1