<?php
/**
* Truncates file contents for validation checks with graceful failure.
*
* @param string $filePath Path to the file.
* @param int $maxLength Maximum length of the data to extract.
* @param string $errorTitle Title for the error message.
* @param string $errorDescription Description of the error.
* @return string|false Truncated data or false on failure.
*/
function truncateFileContent(string $filePath, int $maxLength, string $errorTitle, string $errorDescription): string|false
{
if (!file_exists($filePath)) {
error_log("File not found: " . $filePath); // Log the error
return false;
}
$fileContent = file_get_contents($filePath);
if ($fileContent === false) {
error_log("Failed to read file: " . $filePath); // Log the error
return false;
}
if (strlen($fileContent) <= $maxLength) {
return $fileContent; // Return the original content if already within limit
}
$truncatedContent = substr($fileContent, 0, $maxLength); // Truncate the data
return $truncatedContent;
}
// Example Usage (for testing):
// $filePath = 'data.txt'; // Replace with your file path
// $maxLength = 100;
// $truncatedData = truncateFileContent($filePath, $maxLength, 'Truncation Error', 'File is larger than the maximum allowed length.');
// if ($truncatedData === false) {
// echo "Error: " . $errorTitle . " - " . $errorDescription . "\n";
// } else {
// echo "Truncated data:\n" . $truncatedData . "\n";
// }
?>
Add your comment