<?php
/**
* Extends existing text file logic with debugging and input validation.
*
* @param string $filename The name of the text file.
* @param array $data The data to write to the file.
* @param string $mode The file opening mode (e.g., 'w', 'a').
* @return bool True on success, false on failure.
*/
function writeDataToFileWithDebug(string $filename, array $data, string $mode = 'w'): bool
{
// Input validation: Check if filename is provided and is a string.
if (empty($filename) || !is_string($filename)) {
error_log("Invalid filename provided: " . var_export($filename, true));
return false;
}
//Input validation: Check if data is provided and is an array
if(empty($data) || !is_array($data)){
error_log("Invalid data provided: " . var_export($data, true));
return false;
}
// Debugging: Log the filename and data being written.
error_log("Writing to file: " . $filename);
error_log("Data to write: " . json_encode($data));
try {
$result = file_put_contents($filename, json_encode($data)); //Use json_encode to handle arrays properly
if ($result === false) {
error_log("Error writing to file: " . $filename);
return false;
}
return true;
} catch (Exception $e) {
error_log("Exception writing to file: " . $e->getMessage());
return false;
}
}
/**
* Reads data from a text file with basic validation.
*
* @param string $filename The name of the text file.
* @return array|false The data read from the file as an array, or false on failure.
*/
function readDataFromFileWithDebug(string $filename): array|false
{
// Input validation: Check if filename is provided and is a string
if (empty($filename) || !is_string($filename)) {
error_log("Invalid filename provided: " . var_export($filename, true));
return false;
}
// Debugging: Log the filename being read.
error_log("Reading from file: " . $filename);
try {
$file_contents = file_get_contents($filename);
if ($file_contents === false) {
error_log("Error reading file: " . $filename);
return false;
}
$data = json_decode($file_contents, true); // Decode JSON to array
if (json_last_error() !== JSON_ERROR_NONE) {
error_log("Error decoding JSON from file: " . $filename . ". Error: " . json_last_error_msg());
return false;
}
return $data;
} catch (Exception $e) {
error_log("Exception reading from file: " . $e->getMessage());
return false;
}
}
?>
Add your comment