1. <?php
  2. /**
  3. * Decodes a dataset input for development purposes with defensive checks.
  4. *
  5. * This function prioritizes safety and validation to prevent potential
  6. * vulnerabilities during development. It's not intended for production
  7. * environments where security is paramount.
  8. *
  9. * @param mixed $data The input data to decode. Can be a string, array, or other data type.
  10. * @param string $encoding The encoding of the data (e.g., 'utf-8', 'iso-8859-1'). Defaults to 'utf-8'.
  11. * @param string $type The expected data type (e.g., 'json', 'csv', 'xml'). Defaults to 'json'.
  12. * @param array $options Optional configuration options. Defaults to an empty array.
  13. *
  14. * @return mixed The decoded data, or false on error.
  15. */
  16. function decodeDataset(mixed $data, string $encoding = 'utf-8', string $type = 'json', array $options = []): mixed
  17. {
  18. // Defensive check: Ensure input data is not null or empty.
  19. if (empty($data)) {
  20. error_log("decodeDataset: Input data is empty.");
  21. return false;
  22. }
  23. // Data type validation and handling.
  24. switch ($type) {
  25. case 'json':
  26. // JSON decoding with error handling.
  27. $decodedData = json_decode($data, true, 512, JSON_THROW_ON_ERROR); // Allow large JSON, throw on error
  28. if (json_last_error() !== JSON_ERROR_NONE) {
  29. error_log("decodeDataset: JSON decoding error: " . json_last_error_msg());
  30. return false;
  31. }
  32. break;
  33. case 'csv':
  34. // CSV decoding (basic example - consider using a more robust CSV parser).
  35. $decodedData = [];
  36. if (is_string($data)) {
  37. $rows = explode("\n", $data);
  38. foreach ($rows as $row) {
  39. $fields = explode(',', $row);
  40. $decodedData[] = $fields;
  41. }
  42. } else {
  43. error_log("decodeDataset: Invalid CSV data format.");
  44. return false;
  45. }
  46. break;
  47. case 'xml':
  48. // XML decoding (using simplexml)
  49. try {
  50. $decodedData = simplexml_load_string($data);
  51. } catch (Exception $e) {
  52. error_log("decodeDataset: XML parsing error: " . $e->getMessage());
  53. return false;
  54. }
  55. break;
  56. default:
  57. error_log("decodeDataset: Unsupported data type: " . $type);
  58. return false;
  59. }
  60. //Encoding check and conversion
  61. if(is_string($decodedData)){
  62. if(mb_detect_encoding($decodedData, $encoding, STR_CASE_INSENSITIVE) === false){
  63. $decodedData = mb_convert_encoding($decodedData, $encoding, 'UTF-8');
  64. if($decodedData === false){
  65. error_log("decodeDataset: Could not convert encoding");
  66. return false;
  67. }
  68. }
  69. }
  70. //Additional validation/sanitization (example). Expand as needed.
  71. if (is_array($decodedData)) {
  72. foreach ($decodedData as $key => $value) {
  73. if (is_array($value)) {
  74. // Recursively validate nested arrays.
  75. }
  76. }
  77. }
  78. return $decodedData;
  79. }
  80. ?>

Add your comment