Skip to content
PHP Logo

How can PHP be used to read and write data to external files for game logic?

To read and write data to external files for game logic in PHP, you can use file handling functions like `fopen`, `fwrite`, `fread`, and `fclose`. These functions allow you to open a file, write data to it, read data from it, and close the file after you're done. By using these functions, you can store game data in external files, such as player scores, game settings, or level information.

php
// Open a file for writing
$file = fopen("game_data.txt", "w");

// Write data to the file
fwrite($file, "Player: John\nScore: 100\nLevel: 5");

// Close the file
fclose($file);

// Open the file for reading
$file = fopen("game_data.txt", "r");

// Read data from the file
$data = fread($file, filesize("game_data.txt"));

// Close the file
fclose($file);

// Display the data
echo $data;