1. <?php
  2. /**
  3. * Truncates file contents for validation checks with graceful failure.
  4. *
  5. * @param string $filePath Path to the file.
  6. * @param int $maxLength Maximum length of the data to extract.
  7. * @param string $errorTitle Title for the error message.
  8. * @param string $errorDescription Description of the error.
  9. * @return string|false Truncated data or false on failure.
  10. */
  11. function truncateFileContent(string $filePath, int $maxLength, string $errorTitle, string $errorDescription): string|false
  12. {
  13. if (!file_exists($filePath)) {
  14. error_log("File not found: " . $filePath); // Log the error
  15. return false;
  16. }
  17. $fileContent = file_get_contents($filePath);
  18. if ($fileContent === false) {
  19. error_log("Failed to read file: " . $filePath); // Log the error
  20. return false;
  21. }
  22. if (strlen($fileContent) <= $maxLength) {
  23. return $fileContent; // Return the original content if already within limit
  24. }
  25. $truncatedContent = substr($fileContent, 0, $maxLength); // Truncate the data
  26. return $truncatedContent;
  27. }
  28. // Example Usage (for testing):
  29. // $filePath = 'data.txt'; // Replace with your file path
  30. // $maxLength = 100;
  31. // $truncatedData = truncateFileContent($filePath, $maxLength, 'Truncation Error', 'File is larger than the maximum allowed length.');
  32. // if ($truncatedData === false) {
  33. // echo "Error: " . $errorTitle . " - " . $errorDescription . "\n";
  34. // } else {
  35. // echo "Truncated data:\n" . $truncatedData . "\n";
  36. // }
  37. ?>

Add your comment