bleah1
bleah1

Reputation: 481

Why does PHP deletes the content of the file on input?

I have one file: configuration.txt.

This file gets read by PHP, then wrote by the same PHP, while a C++ program reads the content of the same file at a regular interval.

PHP:

$closeFlag = false;
$arrayInputs = new SplFixedArray(3);
$arrayInputs[0] = "URL not entered";
$arrayInputs[1] = "3";
$arrayInputs[2] = "50";
$configFilePath = "/var/www/html/configuration.txt";
$currentSettingsFile = fopen($configFilePath, "r");

if(flock($currentSettingsFile, LOCK_SH)) {
    $arrayInputs = explode(PHP_EOL, fread($currentSettingsFile, filesize($configFilePath)));
    flock($currentSettingsFile, LOCK_UN);
    $closeFlag = fclose($currentSettingsFile);
}

if(isset( $_POST['save_values'])) {
    if(!empty($_POST['getURL'])) {
        $arrayInputs[0] = $_POST['getURL'];
    }
    if(!empty($_POST['getURR'])) {
        $arrayInputs[1] = $_POST['getURR'];
    }
    if(!empty($_POST['getBrightness'])) {
        $arrayInputs[2] = $_POST['getBrightness'];
    }
}

if(!$closeFlag) fclose($currentSettingsFile);
$currentSettingsFile = fopen($configFilePath, "w");

if(flock($currentSettingsFile, LOCK_SH)) {
    foreach ($arrayInputs as $key => $value) {
        if($value != '')
            fwrite($currentSettingsFile,$value.PHP_EOL);
    }
    flock($currentSettingsFile, LOCK_UN);
    fclose($currentSettingsFile);
}
?>

C++

char configFilePath[]="/var/www/html/configuration.txt";
std::fstream configFile;

configFile.open(configFilePath, std::fstream::in);
if(configFile.is_open()){
// do stuff
} else {
      std::cout<<"Error ! Could not open Configuration file to read"<<std::endl;
    }

The c++ returned no error so far. It can open the file. And php will return Warning: fread(): Length parameter must be greater than 0 because the file is empty.

I believe that PHP is deleting the file's content.

Upvotes: 0

Views: 48

Answers (1)

kainaw
kainaw

Reputation: 4334

When locking a file in PHP, you lock a LOCK file, not the main file. Example:

$myfile = 'myfile.txt';
$lockfile = 'myfile.lock';
$lock = fopen($lockfile,'a');
if(flock($lock, LOCK_EX)) // The lock file is locked in exclusive mode - so I can write to it.
{
  $fp = fopen($myfile,'w');
  fputs($fp, "I am writing safely!");
  fclose($fp);
  flock($lock, LOCK_UN); // Always unlock it!
}
fclose($lock);

You work similarly in C++ because PHP is not locking the actual file. It is locking a lock file. The exact syntax depends heavily on your version of C/C++ and the operating system. So, I will use minimal syntax.

int lock=fopen(lockfile, "r+");
if(flock(fileno(lock), LOCK_EX))
{
  //Locked. You can open a stream to ANOTHER file and play with it.
  flock(fileno(lock), LOCK_UN));
}
fclose(lock);

Upvotes: 2

Related Questions