-1

I was trying to get variable value from a page and echo it out in another page for example I have 2 pages pg1.php and pg2.php:

On pg2.php I have:

<?php
$vr = "Hello";
?>

Now I want to echo this out on pg1.php, I have tried this:

<?php
require "pg2.php";
echo $vr;
?>

It works, but the problem is whatever else I have on pg2.php will be displayed on pg1.php.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • That's what a `require` does - it `include`s and evaluates that file. Not sure why you would think any differently considering the [documentation](https://www.php.net/manual/en/function.require.php) states exactly this - "***`require` is identical to `include`** except upon failure it will also produce a fatal E_COMPILE_ERROR level error.*") – esqew Jul 07 '20 at 20:53
  • [this](https://stackoverflow.com/questions/871858/php-pass-variable-to-next-page) might help. – jibsteroos Jul 07 '20 at 20:54
  • @esqew yes sir i know. i am just trying to get help here. – student98735 Jul 07 '20 at 20:56
  • @jibsteroos sorry sir but i don't want to use $_POST or $_GET or seassons or cookies. i am sure it can be done some how. – student98735 Jul 07 '20 at 20:57

1 Answers1

0

It would be best to restructure your code so that variables are defined in one file that then includes another file with output etc.

<?php
// vars.php
$vr = "Hello";
?>

<?php
// pg1.php
require "vars.php";
echo $vr;
?>

<?php
// pg2.php
require "vars.php";
// other stuff
// ...
// ...
?>

But for this issue in general, buffer output and then delete the buffer:

<?php
// pg1.php
ob_start();
require "pg2.php";
ob_end_clean();
echo $vr;
?>
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87