0

I have this command inside my javascript to create a cookie with a specific value.

...
    document.cookie="superpage=John Doe;secure=true";
...

My goal: I want the content of this cookie inserted via PHP.

So I tried this: In a separate PHP file i declared

$myvalue = "superpage=John Doe;secure=true";

Then I changed the javascript cookie creation to this:

    ...
document.cookie= '<?php echo $myvalue; ?>';
...

Cookie is then created but with the value <?php echo $myvalue and not the string I defined via PHP. Any help is highly appreciated.

2
  • 3
    In which file is located your javascript? It seems it is not processed by php Commented Apr 19, 2015 at 16:12
  • can you alert or console.log that $myvalue? alert(<?php echo $myvalue; ?>); or console.log(<?php echo $myvalue; ?>); if cannot it means your php file is not included to javascript Commented Apr 19, 2015 at 16:14

2 Answers 2

1

Put your JavaScript on a page with .php extension and your code will work, .i.e:

file.php

<?php
$myvalue = "superpage=John Doe;secure=true";
?>

then, on the same page, outside the php block:

<script>
document.cookie= '<?php echo $myvalue; ?>';
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

Good to ear that! If my answer solved your problem, please consider accepting it as the correct answer. Tks.
@user3909280 to accept the answer you'll need to click on the check mark in the middle of the arrows ;)
0

There seems to be confusion on how to mix php with javascript. The only way to do so would be with javascript inside a php file:

<?php

php code.....

$myvalue = "superpage=John Doe;secure=true";

echo '
<script>
javascript code....
document.cookie= '.$myvalue.'
</script>';

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.