CakePHP: Flash uploader and session lost

I recently implemented a YUI uploader for an application developed with CakePHP 1,3. I based me on the solution proposed in the Bakery: Ability to select and upload multiple files at once – under 5 mins..

As explained in the article SWFUpload and cakePHP, a trick is required to avoid losing the current session when you add a Flash uploader to your application.

The solution proposed in the Bakery comes with a component to solve this problem but it is useless. Below comes the rewritten component keeping correctly the current session:

<?php
class YuiUploaderComponent extends Object {

	/**
	 * Restore session from POST fields if possible.
	 * 
	 * This is required because flash plugin uses a different
         * session (id and user agent) from the application one.
	 * 
	 * @param Object &$controller pointer to calling controller
	 */
	public function initialize(&$controller) {
		if (!empty($_POST[Configure::read('Session.cookie')])) {
			//Restore session for our application and not session used by Flash plugin.
			$controller->Session->id($_POST[Configure::read('Session.cookie')]);
			//Required if application is configured to check session user agent.
			if (Configure::read('Session.checkAgent')) {
				$controller->Session->write('Config.userAgent', $_POST['userAgent']);
			}
		}
	}

}
?>

Changes made:

  • The session should be restored before any call to a method of the CakeSession class. It means the trick has to be executed in the “initialize” method of the component and not in the “startup” method.
  • If the variable Session.checkAgent in core.php is set to true (to check the user agent), the user agent should also be restored.