safefilerewrite (function)

Last updated: Fri, Apr 14, 2023 4:46 pm
Return to Knowledgebase

Purpose

Write data to a file in a safe and secure manner, using file locking to prevent race conditions where multiple processes or threads might attempt to write to the same file at the same time.

Location

users/helpers/helpers.php

Parameters

# Parameter Data Type Required Description
1 $fileName string Yes The filename you wish to use
2 $dataToSave string Yes The data you wish to write

Example

safefilerewrite("myfile.ini.php", "Hello world");

Further Documentation:

Note that this function is primarily used for ini files, but if you need a similar function, you can copy the function itself to usersc/includes/custom_functions.php and change

$security = ';die();?>'; ?>

to

$security = ''; ?>

The function first sets a security string to be written to the beginning of the file to prevent unauthorized access or execution of the file contents. The string is ';die();?>'.

The function then attempts to open the file in write mode ('w') using the fopen function. If successful, it sets a start time using microtime and enters a do-while loop that attempts to obtain a lock on the file using the flock function with the LOCK_EX flag.

If the lock is not obtained, the function sleeps for a random amount of time between 0 and 100 milliseconds to avoid collisions and CPU load. The loop continues until a lock is obtained or 5 seconds have elapsed since the start time.

Once the lock is obtained, the function writes the security string and the data to save to the file using the fwrite function. It then releases the lock using the flock function with the LOCK_UN flag and closes the file using the fclose function.