1

There is a PHP file called test2.php,the code is in follow:

<?php
$data=array(
    'name' => 'jack',
    'age' => 8,
);
?>

I want to modify the $data in anoher php file called test1.php, but i find that if only use:

require_once "./test2.php";
$data['age']=10;
echo $data['age'];

Although the output is 10,but $data in test2.php dosen't change.

I want to know how to edit a PHP file in anoher PHP file.

5
  • 1
    "but $data in test1.php dosen't change" You mean test2.php? Why would that change, you'd need to edit/save/write new contents to the file. Commented Jan 2, 2023 at 10:56
  • 1
    I think you need to use SESSION php.net/manual/en/reserved.variables.session.php Commented Jan 2, 2023 at 10:56
  • You seem to be confused with the basics. Commented Jan 2, 2023 at 11:20
  • Using a SESSION won't alter/change the file Commented Jan 2, 2023 at 11:23
  • This looks more like you need to store the values in a database or in some form of .env file. Commented Jan 2, 2023 at 11:47

1 Answer 1

0

To change the contents of test2.php, you need to use a code editor (or... thru file_put_contents (make sure your file is writable), or use a database approach to store the data values, etc.)

However, if you just want to change the value of the age element of the $data array thru programming, then you can use session variables to do what you want

So change test2.php to

<?php
session_start();

if (!isset($_SESSION["data"])) {
   $_SESSION["data"]=array(
            'name' => 'jack',
            'age' => 8,
   );
}

echo $_SESSION["data"]["age"];


?>

and use the following as test1.php

<?php
session_start();

//require_once "./test2.php";
//$data['age']=10;
//echo $data['age'];

$_SESSION["data"]["age"]=10;

echo "Data changed, please visit test2.php to see the effect";

?>

Please try these steps:

  1. visit the test2.php and see the value of $_SESSION["data"]["age"] echoed
  2. visit the test1.php (to change the data)
  3. visit test2.php and see what happens
Sign up to request clarification or add additional context in comments.

2 Comments

"To change the contents of test2.php, you need to use a code editor." So file_put_contents wouldn't work?
Oh of course file_put_contents will also work, let me slightly change my answer :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.