'echo variable in window location not working

im trying to redirect a user to a url with a php variable $userdata However the script seems not to work, it does put it in the html (confirmed with inspect element) but it does not redirect. the url needs to bee

$first = $user['first'];;
$second= $user['second'];;
$userdata  = "'.$first.'&hello='.$second.'";
echo "<script> window.location = 'example/login?userid='.$userdata.'' </script>";


Solution 1:[1]

Use json_encode() to convert the PHP string to a properly formatted JavaScript string. Than use JavaScript concatenation to combine it with the string in the <script>.

$first = $user['first'];;
$second= $user['second'];;
$userdata  = "$first&hello=$second";
echo "<script> window.location = 'example/login?userid=' + " . json_encode($userdata) . ";</script>";

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Barmar