-1

I want to save a cookie for a visitor. I use the code below but it seems it won't work for me. Please guide me where I am wrong

<script type="text/javascript">
    if(!isset($_COOKIE['visited_alreadyxxx']))
    {
        setcookie('visited_alreadyxxx' , 'true' , time()+60*60*24*7*365);  
        alert("hi");
    }
</script>

demo

Edit : sorry for above code , does below code work correctly ?

<?php 
    if(!isset($_COOKIE['visited_alreadyxxx']))
        {
            setcookie('visited_alreadyxxx' , 'true' , time()+60*60*24*7*365);  
          ?>

<script>alert("hi");</script>
<?
        }

?>
luiges90
  • 4,493
  • 2
  • 28
  • 43
Vishnu Simbu
  • 175
  • 1
  • 3
  • 13
  • 2
    You seem to be mixing PHP and JavaScript. You just cannot do that. The JavaScript engine will try to call `isset` and create a runtime error because, I assume, `isset` is not defined. – Felix Kling Feb 09 '13 at 03:50
  • I was just about to say the same thing as Felix King. `isset` and `$_COOKIE` are PHP things. – Piccolo Feb 09 '13 at 03:51
  • oh sorry about that i am new to coding stuffs .Cant we set cookie without php ? – Vishnu Simbu Feb 09 '13 at 03:53
  • http://stackoverflow.com/questions/4825683/how-do-i-create-and-read-a-value-from-cookie – Kijewski Feb 09 '13 at 03:55
  • Of course you can: http://www.quirksmode.org/js/cookies.html. – Felix Kling Feb 09 '13 at 03:56
  • hey my php code is working fine. how to change this time time()+60*60*24*7*365 to 1 hour ? – Vishnu Simbu Feb 09 '13 at 04:01
  • @Vishnu: `time()` returns the current time in seconds. If you want the cookie to expire in one our, you have to add one hour to the current tim. One hour are 3600 seconds. – Felix Kling Feb 09 '13 at 12:20

1 Answers1

0

I don't think you can access cookies like that. It appears to be PHP, mixed with Javascript.

  1. isset() is a PHP function
  2. $_COOKIE is how you access cookies in PHP
  3. setcookie is also PHP
  4. alert is Javascript.

The Javascript interpreter doesn't know how to parse PHP, and will fail to execute.

Julio
  • 2,261
  • 4
  • 30
  • 56