I am currently working on a little website on which I have to make an account creation system. In order to know whether the user is already connected or not I would like use cookies cuz this was looking like the easiest way. However, after checking the official documentation on php.net, and some other forums, I'm still not able to create my cookie. Here is my code :
function connexionOK() {
$cookieName = "CookieCo";
$cookieValue = "true";
$isSent = setcookie($cookieName, $cookieValue, time() + 3600, "/");
if($isSent) {
echo '<script type="text/javascript">';
echo "alert('Cookie envoyé');";
echo "</script>";
}
else {
echo '<script type="text/javascript">';
echo "alert('Cookie failed');";
echo "</script>";
}}
So the page is indeed alerting me 'Cookie failed'.
Thanks for everyone who've been trying to help me ! :)
You may be calling this function after headers were already sent:
try this and see if you get an exception:
function connexionOK() {
$cookieName = "CookieCo";
$cookieValue = "true";
if(headers_sent()){
throw new Exception('Cannot set cookie, headers already sent');
}else{
$isSent = setcookie($cookieName, $cookieValue, time() + 3600, "/");
if($isSent){
echo '<script type="text/javascript">';
echo "alert('Cookie set');";
echo "</script>";
}else{
echo '<script type="text/javascript">';
echo "alert('Cookie not set');";
echo "</script>";
}
}
}
connexionOK();
If so, you will need to refactor and make sure you setcookie before headers are sent.
EDIT: The above code was included to more clearly illustrate the problem - it is poorly written and includes a lot of redundancy as calling set setCookie while headers are sent will already throw an exception and probably terminate execution. If this is NOT the case, you will need to add checks and handle them accordingly.