Write PHP class to work with Cookies. Code example open

Write PHP class to work with Cookies. Code example

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators
Tested: PHP 7
class Cookie{
		public static int $baseTime = 86400 * 7;//86400 = 24hr, 7 = days in week
		public static string $basePath = '/';//set the range of cookies, / - the whole site

		//method in which we can get our cookies
		public static function get(string $name) : ?string{
			return $_COOKIE[$name] ?? null;
		}

		//method to create a new cookie
		public static function add(string $name, string $value, int $time = null, string $path = null){
			//if we do not set the cookie time then set the cookie time
			if($time === null){
				$time = time() + self::$baseTime;
			}

			//if we do not set cookie path, set default
			if($path === null){
				$path = self::$basePath;
			}

			//set cookies using the standard php function
			setcookie($name, $value, $time, $path);
			$_COOKIE[$name] = $value;
		}

		//Writing a method that will delete our cookies
		public static function remove(string $name, string $path = null){
			if($path === null){
				$path = self::$basePath;
			}

			setcookie($name, '', 1, $path);
			unset($_COOKIE[$name]);
		}
	}
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation