I was creating a login system but I ran into an issue. I have to use PHP COOKIES. A cookie is created when a user enters the correct username and password. "user=22" or "user=23" etc. But a user can go to the console panel and create this cookie themselves with document.cookie.
isset($_COOKIE["user"]) returns true even if the cookie is created by user in console panel. So, I have to check the cookies created by the server. Is there a way to do it? Let me know if there is a better way to fix this problem :)
My Answer:
To check if a cookie was created by the server and not by the user, you can set a specific value in the cookie that only the server knows. Here's an example of how you can do this:
1. When the user logs in and the server creates the cookie, set a unique value in the cookie that only the server knows. For example:
php
$secretKey = 'mySecretKey';
$cookieValue = md5($username . $password . $secretKey);
setcookie('auth_cookie', $cookieValue, time() + 3600, '/');
2. When checking if the cookie is valid, compare the value in the cookie with the expected value based on the username, password, and secret key. If they match, then the cookie was created by the server.
php
$secretKey = 'mySecretKey';
$expectedCookieValue = md5($username . $password . $secretKey);
if(isset($_COOKIE['auth_cookie']) && $_COOKIE['auth_cookie'] === $expectedCookieValue) {
// Cookie was created by the server
// Proceed with authentication
} else {
// Cookie was not created by the server
// Handle unauthorized access
}
By using a secret key that only the server knows, you can ensure that the cookie was created by the server and not tampered with by the user.
Rate this post
3 of 5 based on 2965 votesComments