Safe way to work with cookies

1

Colleagues

I'm developing a system that I want to store in a cookie the product that it selected, in case it closes the browser and comes back, the product remains active like this:

setcookie('compras',$_SESSION['produto'],time()+3600); 

But I'm concerned that the cookie is disabled on his browser. Is there any way to solve this? That is, he selects a product and does not finalize the purchase, close the browser and when he returns, the product is still in his cart.

    
asked by anonymous 14.03.2017 / 20:01

1 answer

1

Verify that cookies are enabled for the client. If they are not, let them know about loss of functionality and ask them to enable cookies in the browser.

You can test with PHP:

<?php
session_start();

setcookie('compras', $_SESSION['produto'],time()+3600);

header('Location: VerificaCookies.php');

Then, on the VerifyCookies.php page:

if(isset($_COOKIE['compras'])){
    echo 'Cookies habilitados';
} else {
    // Melhore as mensagens. Estas são só de exemplo
    echo 'Cookies desabilitados';
}

EDIT 1: AGREEMENT (ALMOST) WITH ANDERSON'S COMMENT

You can also use the W3C JavaScript (I could not check with Modernizr, because there are sites blocked for me):

if(navigator.cookieEnabled) {
    cookies = true;
} else {
    cookies = false
}

There's another website, JavaScript Kit with more complete example too: / p>

<script type="text/javascript">
var cookieEnabled=(navigator.cookieEnabled)? true : false

//if not IE4+ nor NS6+
if (typeof navigator.cookieEnabled=="undefined" && !cookieEnabled){ 
    document.cookie="testcookie"
    cookieEnabled=(document.cookie.indexOf("testcookie")!=-1)? true : false
}

//if (cookieEnabled) //if cookies are enabled on client's browser
//do whatever

</script>
    
14.03.2017 / 20:17