Create and Get Cookie in Javascript/PHP

Creating Cookie in Javascript

<script type="text/javascript">
    //create cookie function
    function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires + "; path=/";
    }
</script>

Function for checking if cookie exist in javascript

    function getCookie(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for(var i=0; i<ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1);
            if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
        }
        return "";
    }

Here is an example of how you to create cookie if it is not exist

 <script type="text/javascript">
    function checkCookie() {
        var expirydays=1;
        var user = getCookie("testcookie");
        if (user != "") {
           // alert("Welcome again " + user);
        } else {
                document.getElementById("popupmaintenance").style.visibility = "hidden";
                setCookie("testcookie", 'testcookievalue', expirydays);

        }
    }
    </script>

An sample of code in PHP for creating cookie if it doesn’t exist (for 2 days expiry time)

 <script type="text/javascript">
    function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires + "; path=/";
    }
</script>

<?php

if(!isset($_COOKIE['testcookie']) || ($_COOKIE['testcookie']=='')) {

echo ' <div class="continue">
                    <a href="javascript:setCookie("test", "testvalue", 2);">Create test cookie</a>
                </div>';
}
?>