Fix script on open page

This commit is contained in:
Bruno Rybársky 2024-02-05 22:56:20 +01:00
parent 36de27df7a
commit 3947bbb52a

@ -1,17 +1,18 @@
<?php <?php
function generateScriptData($phpArray) { function generateScriptData($phpArray):string {
// Check if the array is associative and single-level // Check if the array is associative and single-level
if (is_array($phpArray) && count($phpArray) > 0 && count(array_filter(array_keys($phpArray), 'is_string')) === count($phpArray)) { if (is_array($phpArray) && count($phpArray) > 0 && count(array_filter(array_keys($phpArray), 'is_string')) === count($phpArray)) {
// Generate JavaScript code to save each array element to local storage // Generate JavaScript code to save each array element to local storage
echo "<script>"; $out = "<script>";
foreach ($phpArray as $key => $value) { foreach ($phpArray as $key => $value) {
$escapedKey = addslashes($key); // Escape special characters in the key $escapedKey = addslashes($key); // Escape special characters in the key
$escapedValue = addslashes($value); // Escape special characters in the value $escapedValue = addslashes($value); // Escape special characters in the value
echo "localStorage.setItem('$escapedKey', '$escapedValue');"; $out .= "localStorage.setItem('$escapedKey', '$escapedValue');";
} }
echo "</script>"; $out.= "</script>";
} else { } else {
echo "<script>console.error('Invalid PHP array. Must be single-level and associative.');</script>"; $out = "<script>console.error('Invalid PHP array. Must be single-level and associative.');</script>";
} }
return $out;
} }