Simple PHP read and write to a text file

This code snippet reads a text file that if it is not existed it will create one with some text in it.

Next time this code is executed, if the file existed, PHP echoes the content of the file.

<?php
$settingfile = "settings.txt";
$filelink = fopen($settingfile, "r");
$filecontent = fread($filelink, filesize($settingfile));
echo $filecontent;
fclose($filelink);
$newContents = "Hello world!";
if($filecontent != $newContents){
    $settingfile = "settings.txt";
    $filelink = fopen($settingfile, "w");
    fwrite($filelink, $newContents);
    fclose($filelink);
}
?>

Or this one, the better one:

<?php
$settingfile = "settings.txt";
if(file_exists($settingfile)){
    $filelink = fopen($settingfile, "r");
    $filecontent = fread($filelink, filesize($settingfile));
    echo $filecontent;
    fclose($filelink);
}else{
    $astring = "Hello world!";
    $settingfile = "settings.txt";
    $filelink = fopen($settingfile, "w");
    fwrite($filelink, $astring);
    fclose($filelink);
}
?>

 

Leave a Reply

Your email address will not be published. Required fields are marked *