I wrote the following class, Cookie.php
class Cookie extends Config{
//Variables declaration
private $cookieName;
private $cookieValue;
private $cookieExpireTime;
private $cookiePath;
private $cookieDomain;
private $cookieSecureThroughSSL;
private $cookieOnlyThroughHTTP;
//Constructor method, creates a new cookie with the assigned values
function __construct($presetCookieName,
$presetCookieValue,
$presetCookieExpireTime,
$presetCookiePath='/',
$presetCookieDomain = NULL,
$presetCookieSecureThroughSSL = false,
$presetCookieOnlyThroughHTTP = true){
$this->cookieName = $presetCookieName;
$this->cookieValue = $presetCookieValue;
$this->cookieExpireTime = $presetCookieExpireTime;
$this->cookiePath = $presetCookiePath;
$this->cookieDomain = $presetCookieDomain;
$this->cookieSecureThroughSSL = $presetCookieSecureThroughSSL;
$this->cookieOnlyThroughHTTP = $presetCookieOnlyThroughHTTP;
return $this->createCookie();
}
//Clean cookie from possible malicious HTML code, or mistakenly typed spaces
private function cleanCookieValue($value){
return htmlspecialchars(str_replace(' ', '', $value));
}
//Create a new cookie function
public function createCookie(){
return setcookie($this->cleanCookieValue($this->cookieName),
$this->cleanCookieValue($this->cookieValue),
$this->cleanCookieValue($this->cookieExpireTime),
$this->cleanCookieValue($this->cookiePath),
$this->cleanCookieValue($this->cookieDomain),
$this->cleanCookieValue($this->cookieSecureThroughSSL),
$this->cleanCookieValue($this->cookieOnlyThroughHTTP));
}
And the following test file:
$cookie = new Cookie("testCookie", "Value", 3600, "/");
if(isset($_COOKIE['testCookie'])){
echo 'Success';
}
else{
echo 'Failed!';
}
And I keep getting 'Failed' error (After two or more refreshes as well).
Do you guys see the problem here?
By the way, the following simple example works perfectly:
setcookie("token", "value", time()+60*60*24*100, "/");
if(isset($_COOKIE['token'])){
echo 'Token succeeded';
}
else{
echo 'Token failed!';
}
In the class, you had posted 3rd parameter is $presetCookieExpireTime, not "seconds of life". To make it work - do the
$cookie = new Cookie("testCookie", "Value", time() + 3600, "/");
Related
I'm currently building a social network. I got to the point where I need cookies and tokens (in the database) to make people logout and login in.
The problem is that for some reason one of my variables is not getting any data from the query I wrote...
Here's the code of the page:
Cookie_login.php
<?php declare(strict_types=1);
class Login
{
public static function isloggedIn(): ?int
{
if (isset($_COOKIE['SNID'])) {
$user = DB::query(
'SELECT user_id FROM tokens WHERE token=:token',
[':token' => sha1($_COOKIE['SNID'])]
);
if (empty($user) && isset($user[0]['user_id'])) {
$userid = $user[0]['user_id'];
}
if (isset($_COOKIE['SNID_'])) {
return $userid;
}
$cstrong = true;
$token = bin2hex(openssl_random_pseudo_bytes(64, $cstrong));
DB_update::query_update(
'INSERT INTO tokens VALUES (\'\',:token,:user_id)',
[':token' => sha1($token), ':user_id' => $userid]
);
DB_update::query_update('DELETE FROM tokens WHERE token=:token', [':token' => sha1($_COOKIE['SNID'])]);
setcookie('SNID', $token, time() + 60 * 60 * 24 * 7, '/', null, true, true);
return $userid;
}
return null;
}
}
and the DB.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
class DB
{
private static function connect(): PDO
{
$pdo = new PDO('mysql:host=127.0.0.1;dbname=pap;charset=utf8', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
public static function query($query, $params = [])
{
$statement = self::connect()->prepare($query);
$statement->execute($params);
return $statement->fetchALL();
}
}
class DB_update
{
private static function connect(): PDO
{
$pdo = new PDO('mysql:host=127.0.0.1;dbname=pap;charset=utf8', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
public static function query_update($query_update, $paramss = [])
{
$statement = self::connect()->prepare($query_update);
$statement->execute($paramss);
return $statement->RowCount();
}
}
I used the fopen() and fwrite() to see what $userid is returning and it was returning 1... Already check the queries in SQL and they work just fine... So I don't know why the $userid variable is not saving the user_id from the table. I hope you guys can help me...
PS:DB_update is just a name to be different from DB_query
First, of all:
fwrite($fp, print_r($userid));
Function print_r has a second parameter, default sets to false but in your case, you have to explicity set to true:
fwrite($fp, print_r($userid, true));
Otherwise, you will always write to file 1 value.
And the second. It's good idea to use function fclose to close opened file pointer if it's no longer required.
This line generates your "undefined index off 0" error:
$userid = DB::query('SELECT user_id FROM tokens WHERE token=:token',
array(':token' =>sha1($_COOKIE['SNID'])))[0]['user_id'];
Specifically, the [0]['user_id'] bit that you've patched to the end of the query. You should only ever do that if you're sure the function called will always return an array with the necessary fields (not the case with DB queries!). When there is no match, your DB::query method probably returns NULL or false (and you can't have NULL[0] etc. much less NULL[0]['user_id'], thus the error).
You'll want to postpone the offset assignment, and first of all have a logic for situations where no match happens. First put the DB query result into a variable that you can evaluate as being the expected type of resource or not -- only then assign array offsets.
$user = DB::query('SELECT user_id FROM tokens WHERE token=:token',
array(':token' =>sha1($_COOKIE['SNID'])));
if (!empty($user) && isset($user[0]['user_id'])) {
$userid = $user[0]['user_id'];
}
else {
// whatever that you need to do here.
}
On your debugging trouble; your print_r logger is only logging 1 because:
print_r ( mixed $expression [, bool $return = FALSE ] ) : mixed
... "When the $return parameter is TRUE, this function will return a string.
Otherwise, the return value is TRUE."
If you want to both print and log into a file, then use an intermediate variable, along the lines of $pr = print_r($foo, true); echo $pr; fwrite($fp, $pr);. Hope that helps you get it sorted.
Ok, that's whole code with comments:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
class DB
{
private static function connect()
{
$pdo = new PDO('mysql:host=127.0.0.1;dbname=pap;charset=utf8','root','');
$pdo -> setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
return $pdo;
}
public static function query($query,$params=array())
{
$statement = self::connect() ->prepare($query);
$statement ->execute($params);
$data = $statement -> fetchALL();
return $data;
}
}
class DB_update
{
private static function connect()
{
$pdo = new PDO('mysql:host=127.0.0.1;dbname=pap;charset=utf8','root','');
$pdo -> setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
return $pdo;
}
public static function query_update($query_update,$paramss=array())
{
$statement = self::connect() ->prepare($query_update);
$statement ->execute($paramss);
$datas = $statement -> RowCount();
return $datas;
}
}
/**
* Table `tokens` schema:
* CREATE TABLE `tokens` (
* `token` varchar(255) NOT NULL,
* `user_id` int(11) NOT NULL,
* PRIMARY KEY (`token`)
* ) ENGINE=InnoDB DEFAULT CHARSET=utf8
*/
class Login
{
public static function isloggedIn()
{
if (isset($_COOKIE['SNID'])) {
$userid = DB::query('SELECT user_id FROM tokens WHERE token=:token',array(':token' =>sha1($_COOKIE['SNID'])))[0]['user_id'];
$fp = fopen('problem.txt', 'w');
fwrite($fp, print_r($userid, true));
fclose($fp);
// I don't understand, what is this ? There is no place in your code, to set that cookie in that named key
// It always be false
if (isset($_COOKIE['SNID_']))
{
return $userid;
}
else {
$cstrong = TRUE;
$token = bin2hex(openssl_random_pseudo_bytes(64, $cstrong));
DB_update::query_update('INSERT INTO tokens VALUES (:token,:user_id)',array(':token'=>sha1($token),':user_id'=>$userid));
DB_update::query_update('DELETE FROM tokens WHERE token=:token',array(':token'=>sha1($_COOKIE['SNID'])));
setcookie("SNID", $token, time() + 60 * 60 * 24 * 7, '/', NULL, TRUE, TRUE);
// I don't understand what is this below
setcookie("SNID:", '1', time() + 60 * 60 * 24 * 3, '/', NULL, TRUE, TRUE);
return $userid;
}
}
return false;
}
}
// Uncomment code below to log in
// $userIdToLogIn = 19; // You can change it to any other value
// $cstrong = true;
// $token = bin2hex(openssl_random_pseudo_bytes(64, $cstrong));
// DB_update::query_update('INSERT INTO tokens VALUES (:token, :user_id)', array(':token' => sha1($token), ':user_id' => $userIdToLogIn));
// setcookie("SNID", $token, time() + 60 * 60 * 24 * 7, '/', NULL, TRUE, TRUE);
// ------------------------------
// Uncomment code below to log out
// setcookie("SNID", time() - 3600);
// -------------------------------
// And check
$userId = Login::isloggedIn();
if($userId) {
printf(
"User with id: %s is logger in with token: %s",
$userId,
DB::query('SELECT token FROM tokens WHERE user_id = :user_id', array(':user_id' => $userId))[0]['token']
);
} else {
echo "User is not logger in!";
}
And now:
Uncomment lines for comment: Uncomment code below to log in for first request. Script log in you.
Comment it back for second and nexts requests to check how it works.
I've created a class which has multiple private an public functions and an construct function. It's an client to connect to the vCloud API. I want two objects loaded with different initiations of this class. They have to exist in parallel.
$vcloud1 = new vCloud(0, 'system');
$vcloud2 = new vCloud(211, 'org');
When I check the output of $vcloud1 it's loaded with info of $vcloud2. Is this correct, should this happen? Any idea how I can load a class multiple times and isolate both class loads?
This is part of my class, it holds the most important functions. Construct with user and org to login to. If info in the DB exists, then we authenticate with DB info, else we authenticate with system level credentials. So I would like to have two class loads, one with the user level login and one with system level login.
class vCloud {
private $client;
private $session_id;
private $sdk_ver = '7.0';
private $system_user = 'xxxxxxxxxxx';
private $system_password = 'xxxxxxxxxxxxxxxxx';
private $system_host = 'xxxxxxxxxxxxx';
private $org_user;
private $org_password;
private $org_host;
private $base_url;
public function __construct($customerId, $orgName) {
if ($this->vcloud_get_db_info($customerId)) {
$this->base_url = 'https://' . $this->org_host . '/api/';
$this->base_user = $this->org_user . "#" . $orgName;
$this->base_password = $this->org_password;
} else {
$this->base_url = 'https://' . $this->system_host . '/api/';
$this->base_user = $this->system_user;
$this->base_password = $this->system_password;
}
$response = \Httpful\Request::post($this->base_url . 'sessions')
->addHeaders([
'Accept' => 'application/*+xml;version=' . $this->sdk_ver
])
->authenticateWith($this->base_user, $this->base_password)
->send();
$this->client = Httpful\Request::init()
->addHeaders([
'Accept' => 'application/*+xml;version=' . $this->sdk_ver,
'x-vcloud-authorization' => $response->headers['x-vcloud-authorization']
]);
Httpful\Request::ini($this->client);
}
public function __destruct() {
$deleted = $this->vcloud_delete_session();
if (!$deleted) {
echo "vCloud API session could not be deleted. Contact administrator if you see this message.";
}
}
private function vcloud_delete_session() {
if (isset($this->client)) {
$response = $this->client::delete($this->base_url . 'session')->send();
return $response->code == 204;
} else {
return FALSE;
}
}
public function vcloud_get_db_info($customerId) {
global $db_handle;
$result = $db_handle->runQuery("SELECT * from vdc WHERE customer=" . $customerId);
if ($result) {
foreach ($result as $row) {
if ($row['org_host'] != "") {
$this->org_user = $row['org_user'];
$this->org_password = $row['org_password'];
$this->org_host = $row['org_host'];
return true;
} else {
return false;
}
}
} else {
return false;
}
}
public function vcloud_get_admin_orgs() {
$response = $this->client::get($this->base_url . 'query?type=organization&sortAsc=name&pageSize=100')->send();
return $response->body;
}
}
$vcloud1 = new vCloud('user1', 'system');
$vcloud2 = new vCloud('user2', 'org');
This is enough to make two instances which are not related.
I suppose your database is returning the same results.
How about providing a custom equals method to each object that retreives an instance of vCloud?
class vCloud {
//Other definitions
public function equals(vCloud $other){
//Return true if $other is same as this class (has same client_id etc etc)
}
}
So you just need to do as the code says:
$vcloud1 = new vCloud('user1', 'system');
$vcloud2 = new vCloud('user2', 'org');
if($vcloud1.equals($vclous2)){
echo "Entries are the same";
} else {
echo "Entries are NOT the same";
}
Also you may need to have various getter and setter methods into your class definitions. What is needed for you to do is to fill the equals method.
I am developing an e-commerce website on which i need to store sessions inside database.I did that by implementing SessionHandlerInterface Class that is provided by the php itself.However it works totally fine and did store sessions inside the database , as well as read them properly.
However I am facing problem when I am using unset to unset a session variable.Sometimes it does work.Sometimes it doesn't.
For example:If i have a session variable by the name ABC unset might delete it from the database or it doesn't deletes the variable.
<?php
//inc.session.php
require_once 'RemoteAddress.php';
class SysSession implements SessionHandlerInterface
{
private $remote_write;
private $remote_read;
private $link;
private $ip_address_write;
private $ip_address_read;
public function open($savePath, $sessionName)
{
$link = new mysqli("localhost","root","","cakenbake");
if($link){
$this->link = $link;
return true;
}else{
return false;
}
}
public function close()
{
mysqli_close($this->link);
return true;
}
public function read($id)
{
$this->remote_read=new RemoteAddress();
$this->ip_address_read=$this->remote_read->getIpAddress();
$stmt=$this->link->prepare("SELECT `Session_Data`,`ip_address` FROM Session WHERE `Session_Id` = ? AND `Session_Expires` > '".date('Y-m-d H:i:s')."'");
$stmt->bind_param("s",$id);
$stmt->execute();
//$result = mysqli_query($this->link,"SELECT Session_Data FROM Session WHERE Session_Id = '".$id."' AND Session_Expires > '".date('Y-m-d H:i:s')."'");
/*$result=$this->link->prepare("Some query inside")
* This shows up an error stating prepare method not found
*
*/
$res=$stmt->get_result();
if($row=$res->fetch_assoc()){
if($this->ip_address_read==$row['ip_address'])
return $row['Session_Data'];
else return "";
}else{
return "";
}
}
public function write($id, $data)
{
$this->remote_write=new RemoteAddress();
$this->ip_address_write=$this->remote_write->getIpAddress();
if(!empty($data))
{
$DateTime = date('Y-m-d H:i:s');
$NewDateTime = date('Y-m-d H:i:s',strtotime($DateTime.' + 1 hour'));
$stmt=$this->link->prepare("REPLACE INTO Session SET Session_Id = ?, Session_Expires = '".$NewDateTime."', Session_Data = '".$data."', ip_address = '".$this->ip_address_write."'");
$stmt->bind_param("s",$id);
// $result = mysqli_query($this->link,"REPLACE INTO Session SET Session_Id = '".$id."', Session_Expires = '".$NewDateTime."', Session_Data = '".$data."'");
if($stmt->execute()){
return true;
}else{
return false;
}
}
}
public function destroy($id)
{
$stmt = $this->link->prepare("DELETE FROM Session WHERE Session_Id =?");
$stmt->bind_param("s",$id);
if($stmt->execute()){
return true;
}else{
return false;
}
}
public function gc($maxlifetime)
{
$result = $this->link->query("DELETE FROM Session WHERE ((UNIX_TIMESTAMP(Session_Expires) + ".$maxlifetime.") < UNIX_TIMESTAMP(NOW()))");
if($result){
return true;
}else{
return false;
}
}
}
$handler = new SysSession();
session_set_save_handler($handler, true);
?>
The above code stores and read sessions from the database.
Structure of the session table.
What could be the possible reason for this weird behaviour. Do i have to implement unset function as well?.
How should i resolve this problem?
If you could suggest me someother already written code for storing in database.That would work as well but i dont need any frameworks such as codeigniter and Yii2.
If you need more information regarding this problem.I will update my question.
Thanks in advance!
The problem is not with the unset function but with your write function.The write function is responsible for any updates that are made to the specific session id.
The wierd behiviour is not with the unset but it is with the write funciton you have implemented.
See ,the !empty constraint checks if your data is empty or not.What i can guess is that your database for that specific id must be empty after the removal of the specific variable .So the write tries to update your row with an empty value but with that constraint it isn't able to do so.
Just remove the !empty tag and it will work like a charm.
I'm creating my own custom SessionHandler to store my session information in a postgresql 9.3 database and I'm having a problem where the session data passed to the write() method isn't being written to the database, but the session name is??
Things that I know for a fact
My custom class is handling the sessions when session_start() is called - as tested with echoing output from the various methods and no session files are being created in /tmp
The $session_data arg in write() contains the proper serialized string as shown by echoing the contents in the write() method.
$session_name is being written to the database just fine and so is a BLANK serialized string a:0:{}.
Things I'm confused about:
Echoing the contents of $_SESSION['test_var1'] shows the correct value stored, even if read() is empty or returning no value??
If the session name is saved in the DB just fine, why isn't the session data?
Server Configuration
OS: Gentoo
Database: Postgresql 9.3
Web Server: NGINX 1.7.6
PHP 5.5.18 connected to NGINX via FPM
PHP ini session settings
session.save_handler = user
session.use_strict_mode = 1
session.use_cookies = 1
session.cookie_secure = 1
session.use_only_cookies = 1
session.name = _g
session.auto_start = 0
session.serialize_handler = php_serialize
class SessionManagement implements SessionHandlerInterface {
private $_id = '';
private $_link = null;
public function __construct() {
session_set_save_handler(
[$this, 'open'],
[$this, 'close'],
[$this, 'read'],
[$this, 'write'],
[$this, 'destroy'],
[$this, 'gc']
);
}
public function open($save_path, $session_id) {
echo 'open called<br/>';
$this->_id = $session_id;
$this->_link = new PDO('pgsql:host=' . $_SERVER['DB_HOST'] . ';dbname=' . $_SERVER['DB_DB'],
$_SERVER['DB_USER'],
$_SERVER['DB_PASS']);
}
public function close() {
echo 'close called<br/>';
}
public function destroy($session_id) {
echo 'destroying '.$session_id, '<br/>';
}
public function gc($maxlifetime) {
echo 'GC called<br/>';
}
public function read($session_name) {
$name = $this->_id.'_'.$session_name;
$sql = 'SELECT session_data FROM sessions WHERE session_name = :name';
if ($rel = $this->_link->prepare($sql)) {
if ($rel->execute([':name' => $name])) {
return $rel->fetch(PDO::FETCH_ASSOC)['session_data'];
} else {
return false;
}
} else {
return false;
}
return '';
}
public function write($session_name, $session_data) {
echo 'Session data: '.$session_data.'<br/>';
$name = $this->_id . '_' . $session_name;
$data = $session_data;
$sql = "SELECT 1 FROM sessions WHERE session_name = :name";
if ($rel = $this->_link->prepare($sql)) {
if ($rel->execute([':name' => $name])) {
if ($rel->rowCount()) {
echo 'Updating...<br/>';
$sql = 'UPDATE sessions SET session_data = :data WHERE session_name = :name';
if ($rel = $this->_link->prepare($sql)) {
if ($rel->execute([':name' => $name, ':data' => $data])) {
echo 'Update success...<br/>';
} else {
echo 'Update failed...<br/>';
var_dump($rel->errorInfo());
}
}
} else {
echo 'Inserting...<br/>';
$sql = 'INSERT INTO sessions (session_name, session_data) ';
$sql .= 'VALUES(:name, :data)';
if ($rel = $this->_link->prepare($sql)) {
if ($rel->execute([':name' => $name, ':data' => $data])) {
echo 'Insert success...<br/>';
} else {
echo 'Insert failed...<br/>';
var_dump($rel->errorInfo());
}
}
}
}
}
}
}
Test code:
new SessionManagement();
session_start();
$_SESSION['test_var1'] = 'some test data';
session_write_close(); // Making sure writing is finished
echo $_SESSION['test_var1'];
Output via test page
open called
Session data: a:1:{s:9:"test_var1";s:14:"some test data";}
Inserting...
Insert success...
close called
some test data
Relevant database fields
session_name: _g_h8m64bsb7a72dpj56vgojn6f4k3ncdf97leihcqfupg2qtvpbo20
session_data: a:0:{}
I'm not sure if this is a database issue or a PHP issue. I've been messing with this for a few days now and decided it was time to ask the community. Hopefully someone has some insight as to what the problem is.
I think you must initialize PDO object outside of the Open function handler and the class itself
try to access to your PDO Object with a Global value or through a static variable.
This is my implementation with MYSQL for my project :
class Core_DB_SessionHandler implements SessionHandlerInterface
{
protected $options = array(); // Options de la session
protected static $db = NULL; // Acceder a la BDD
public function __construct($options, $pdo) {
$this->options = $options;
self::$db = $pdo;
}
public function open($savePath, $sessionName) {
$now = time();
$req = self::$db->prepare("DELETE FROM tbl_sessions WHERE expire < '{1}' ");
$req->execute(array($now));
return TRUE;
}
public function close() {
$this->gc(ini_get('session.gc_maxlifetime'));
}
public function read($id) {
$now = time();
$stmt = self::$db->query("SELECT data FROM tbl_sessions WHERE sid = '$id AND expire < '$now'");
$result = $stmt->fetchColumn();
return $result;
}
public function write($id, $data) {
if (array_key_exists('TIMEOUT', $_SESSION)) {
$newExp = $_SESSION['TIMEOUT'];
}
else {
$newExp = time() + $this->options['time_limiter'];
}
try {
$req = self::$db->prepare('INSERT INTO tbl_sessions (sid, data, expire) VALUES (:sid, :data, :expire)
ON DUPLICATE KEY UPDATE data = :data, expire = :expire');
$vals = array('sid' => $id, 'data' => $data, 'expire' => $newExp);
$req->execute($vals);
return TRUE;
}
catch (PDOException $e) {
throw new Core_Exception(sprintf('PDOException was thrown when trying to write the session data: %s', $e->getMessage()), 0, $e);
}
}
public function destroy($id) {
$stmt = self::$db->prepare("DELETE FROM tbl_sessions WHERE sid = '{1}'");
$stmt->execute(array($id));
//return ($stmt->rowCount() === 1) ? true : false;
return TRUE;
}
public function gc($maxlifetime) {
$now = time();
$req = self::$db->prepare("DELETE FROM tbl_sessions WHERE expire < '{1}' ");
$req->execute(array($now));
return TRUE;
}
}
and i initialize handler like this :
$handler = new Core_DB_SessionHandler($MyOptions, $MyPDO);
if (PHP5) {
if (!session_set_save_handler($handler, TRUE)) {
throw new Core_Exception('Erreur lors de l\'init des sessions !');
}
}
nb : In your Table structure don't use autoincrement for ID
Well, I've solved my problem, but it's hard to say if this fix was actually the problem in the first place.
In the read method, I changed the follow:
return $rel->fetch(PDO::FETCH_ASSOC)['session_data'];
to
$data $rel->fetch(PDO::FETCH_ASSOC)['session_data'];
return $data;
After this the session was writing $session_data to the database without any problem. That's all well and dandy, but it doesn't explain why it didn't work in the first place. I mainly say this because upon switching the statement back everything continued to work. As in, I can't reproduce the issue now. So it's hard for me to even say that this was the problem in the first place.
Hopefully this helps someone. I've been unable to find more information about it, but it something does show up I'll be sure to add it here.
Can anyone tell me what is wrong with my code?
<?php
class MyCookie
{
private $expiration = 0;
private $path = "";
private $domain = "";
private $secure = false;
private $httponly = false;
private $names = array();
public function __construct($e, $p = "/temp/", $s = false, $h = false) {
$this->expiration = $e;
$this->path = $p;
$this->domain = '.' . $_SERVER["SERVER_NAME"];
$this->secure = $s;
$this->httponly = $h;
}
public function getDomain() {
return $this->domain;
}
public function write($name, $value) {
return setcookie($name, $value, time() + $this->expiration, $this->path, $this->domain, $this->secure, $this->httponly);
}
public function delete($name) {
return setcookie($name, $value, time() - $this->expiration, $this->path, $this->domain, $this->secure, $this->httponly);
}
public function read($name) {
return $_COOKIE[$name];
}
}
session_start();
$cookie = new MyCookie(3600 * 24 * 30);
$cookie->write('name', 'jun');
echo $cookie->read('name');
?>
Somehow the cookie is not registering or showing up.
Cookie won't show up in $_COOKIE array until you reload the page (cookies are sent with HTTP response)
Two suggestions...
a) Try making the cookie visible to your whole domain, rather than a specified path
b) Get the Web Developer Toolbar for Firefox so you can easily view the current list of Cookies while you browse, which is really useful for de-bugging.
In PHP, the cookie is not actually set until the page reloads. You're creating the cookie then immediately trying to get a value from $_COOKIE, but that value doesn't exist yet in $_COOKIE.
Although it's generally not a good idea to alter values of any of the superglobal arrays, you can do this:
replace:
public function write($name, $value) {
return setcookie($name, $value, time() + $this->expiration, $this->path, $this->domain, $this->secure, $this->httponly);
}
with:
public function write($name, $value) {
$_COOKIE[$name] = $value;
return setcookie($name, $value, time() + $this->expiration, $this->path, $this->domain, $this->secure, $this->httponly);
}
setcookie will not moify the $_COOKIE superglobal.
Is your directory currently '/temp/'? If not, the cookie won't be passed along. Try not giving the new cookie a directory while you're at it, it will auto set to the correct one anyway.
Yup it isn't registering because it needs to reload the page.
It works like this:
_>Http Request
_>Php SetCookie
_>Http Response with cookie header
->New Http Request with cookie
->Php can read cookie now.