Skip to content

Instantly share code, notes, and snippets.

@DragonI
Last active March 30, 2018 04:58
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save DragonI/4450164 to your computer and use it in GitHub Desktop.
Save DragonI/4450164 to your computer and use it in GitHub Desktop.
hack to access / set cookies created in JavaScript from Laravel 3.2

##Objective

Add RESS for conditional content based on screen size. Accomplished by creating a JavaScript cookie

##Problem

When a cookie is set via JavaScript, Laravel's Cookie can't read the cookie. It doesn't work because there is no httpOnly option in Laravel. Symfony cookie does have httpOnly option but it defaults to TRUE. httpOnly has to be set to FALSE in order to access cookies from the browser. See issues:

taskaz's laravel/laravel#460 would have added httpOnly to Lavarel but it was closed - no idea why taskaz's changes would have defaulted to FALSE which matches PHP's implementation. Maybe should have set it to TRUE to match Symfony, therefore a little more XSS safe.

##hack - use PHP's $_COOKIE

###Add this to your layout/view - between HEAD tag

<?php
// used for RESS
// if ( !Cookie::has('resolution') ) // doesn't work
if ( !isset( $_COOKIE['resolution'] ) )
{
?>
  <script>
  expiry = new Date();
  expiry.setTime( expiry.getTime()+(3600*60*1000) );
  document.cookie='resolution='+Math.max(screen.width,screen.height)+'; expires='+ expiry.toGMTString() + ';path=/';
  location.reload(true);
  </script>
<?php
}
?>

###Add the following to Base_Controller - base.php

####1. add var - name it appropriately

  public $resolution = 0;

####2. add this to the constructor

	// only call for non Ajax
	if ( !Request::ajax() )
	{
		// RESS conditional content - cookie for mobile screen resolution
		$this->resolution = $this->saveJavaScriptCookie( 'resolution', 3600 );
	}

####3. add the following function

  /*
   * saves a cookie created by JavaScript and returns the cookie value
   */

  private function saveJavaScriptCookie( $cookieName = NULL, $duration = 60 )
  {
     if ( is_null( $cookieName )) 
     {
        return $cookieName;
     }

     if ( !Cookie::has( $cookieName ) )
     {
        if ( isset( $_COOKIE[$cookieName] ) ) 
        {
           Cookie::put( $cookieName, $_COOKIE[$cookieName], $duration );
        }		
     }
     
     return Cookie::get( $cookieName );
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment