HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

PHP+JS Code Combining

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
codephpcombining

Problem

Just wondering if this is okay to do? I have to store some PHP variable values into LocalStorage.

if($res->status == "success"){

            echo 'alert("alrighty sparky! lets get you in...");';
            echo 'localStorage.setItem("token", JSON.stringify({"token": "'.$res->token.'" }))';
            echo 'localStorage.setItem("username", JSON.stringify({"username": "'.$data->username.'" }))';
            echo 'localStorage.setItem("id", JSON.stringify({"id": "'.$data->id.'" }))';

            $boarding_url =  base_url() . 'index.php/boarding/teddies';
            redirect($boarding_url);
        }

Solution

No, it doesn't work like that because you're not escaping your PHP strings to be a safe JavaScript string. What you're doing is encoding them as JSON but if - for example - $res->token contains \ then it will produce a broken JavaScript string and JSON.stringify() won't fix it.

Correct code must use json_encode() for this purpose.

echo 'localStorage.setItem("id", "'.json_encode($data->id).'")';


Also note that you don't need to repeat `` tag each time:

echo '';
// Write all lines here, don't forget semicolon at the end of each one
echo 'localStorage.setItem("id", "'.json_encode($data->id).'");';
echo '';

Code Snippets

echo '<script>localStorage.setItem("id", "'.json_encode($data->id).'")</script>';
echo '<script type="text/javascript">';
// Write all lines here, don't forget semicolon at the end of each one
echo 'localStorage.setItem("id", "'.json_encode($data->id).'");';
echo '</script>';

Context

StackExchange Code Review Q#117342, answer score: 3

Revisions (0)

No revisions yet.