Search code examples
phpvariablesecho

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

  • 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>";