简体   繁体   中英

how to access the variable to the page without using GET and POST methods and without using header function?

Below are two files first.php and second.php I want to access the $name variable in the second file. I used global but it just access values inside the file. I do not want to use POST and GET method because I used POST already for redirecting to home.php

first.php
 <?php
 $name = 'New York';
 ?>

  second.php
 <?php
  // Access variable here from the above first.php file 
 ?>

INCLUDE

first.php

$name = "New York";

second.php

include "path/to/first.php";
echo $name; //echo "New York"

Here is the manual for PHP: Include


SESSIONS

If you don't want everything from first.php on second.php, you should use sessions.

first.php

session_start(); //start sessions, so you can use session variables
$_SESSION['name'] = "New York"; //set session variable called "name" to "New York"

second.php

session_start(); //start session so you can use session variables
echo $_SESSION['name']; //echo "New York"

Session variables work basically the same as regular variables, but you access them like an array. You have to start the session on every page to access them. I usually just start sessions in my header file so it's always included.

More info about PHP sessions


COOKIES

You could also use cookies, though I recommend using SESSIONS instead in most cases. Cookies are good for when that variable needs to last through multiple log in sessions or for a really long time, I usually use these for users settings themes in my application and such things that don't change often.

first.php

$name = "New York"; //set variable
setcookie("name", $name, time() + (86400 * 30), '/'); //set cookie that expires in 1 day

seconds.php

echo $_COOKIE['name']; //echo New York

More information on cookies

Try to use $_SESSION variable.

<?php //first.php
session_start();
$_SESSION['name'] = 'New York';
?>
<?php //second.php
session_start();
echo $_SESSION['name'];
?>

The best and safe way so far is using include_once() . If you want to include many files then you may use __autoload() (if it is object orient approach) .

Check the documentation

$_REQUEST['var'];

This adapt with both post and get. Doesn't Metter what you are using. Or with include 'file.php' Or with setcookie('name', 'value'); $_COOKIE['name']; setcookie('name', 'value'); $_COOKIE['name']; Or with session storage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM