Ubuntu : Web Server Cheatsheet


Server First Set Up

Installation of Apache, PHP and MySQL

sudo apt-get update
sudo apt-get upgrade
sudo apt-get install apache2 libapache2-mod-php5 mysql-server libapache2-mod-auth-mysql php5-mysql

Set up Apache virtuals hosts

sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/example.com.conf
sudo vim /etc/apache2/sites-available/example.com.conf

Example :

<VirtualHost *:80>
    ServerAdmin [email protected]
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

And :

sudo a2dissite 000-default
sudo a2ensite example.com
sudo service apache2 reload

Set up domain DNS records

@ 10800 IN A

Ubuntu common operations

Extract a .tar.gz

tar -zxvf file.tar.gz

MySQL common operations

List MySQL users

SELECT User, Host, Password FROM mysql.user;

Create new MySQL user

CREATE USER 'jeffrey'@'localhost' IDENTIFIED BY 'mypass';

Change MySQL user password

SET PASSWORD FOR 'bob'@'%.example.org' = PASSWORD('cleartext password');

Delete MySQL user

DROP USER 'jeffrey'@'localhost';

Create MySQL database

CREATE DATABASE dbname CHARACTER SET utf8 COLLATE utf8_general_ci;

Grant MySQL privileges

GRANT ALL ON db1.* TO 'jeffrey'@'localhost';

Symfony2 : how to fix the “Warning: SessionHandler::read()” Exception


If you too you got an error like this one :

Warning: SessionHandler::read(): open(\xampp\tmp\sess_hagg7jkmp7l7fmh5ec4k6jmgu0, O_RDWR) failed: No such file or directory (2) in [...]\app\cache\dev\classes.php line 423

I let you know that you just have to add/change these 2 lines in app/config/config.yml to fix it :

        handler_id: session.handler.native_file
        save_path: "%kernel.root_dir%/sessions"

PHP : short syntax (cheat sheet)


Whether you need them to shorten your code, to understand code from someone else, or to use them to write your templates, here is a list of short syntax you can use in PHP :

Output : echo

For templates :

<?= $myVar ?>

which is similar to :

<?php echo $myVar; ?>

Ternary operator (conditional operator)

The combination of question mark and colon represent a specific syntax reserved to ternary operators.

$myVar = (CONDITION) ? VALUE_1 : VALUE_2;

function $myFunction()
  return (CONDITION) ? VALUE_1 : VALUE_2;

which are respectively similar to :

if (CONDITION) $myVar = VALUE_1;
else $myVar = VALUE_2;

function $myFunction()
  if (CONDITION) return VALUE_1;
  else return VALUE_2;

Single conditional structures : with an output

This only works with print statement (because it actually always returns 1, thus == true).


which is similar to :


Conditional structures : if … elseif … else

For pure PHP code :

elseif (CONDITION 2):

For templates :

<?php if (CONDITION 1): ?>
<?php elseif (CONDITION 2): ?>
<?php else: ?>
<?php endif ?>

Conditional structures : switch … case

For templates :

Also, becareful with any space between the switch and the first case : this is really not a good idea to close PHP tag et reopen it between them. FYI: I really don’t like switches within templates.

<?php switch($myVar):
case 1: ?>
<?php break;?>
<?php case 2: ?>
<?php break;?>
<?php endswitch;?>

Loop structures : for / foreach / while

For templates :

<?php for($i=0; $i<$i_max; $i++): ?>
<?php endfor ?>

<?php while (CONDITION): ?>
<?php endwhile ?>

<?php foreach($myArray as $value): ?>
<?php endforeach ?>

PHP : How to install PHP Accelerator in Xampp ?


To install PHP Accelerator in Xampp, you need first to go to your php.ini file (i.e. within C:xamppphp directory) and add this line inside Dynamic Extensions part :

Then you need :

  1. to show you PHP configuration via the PHP function phpinfo()
  2. to get 2 precious informations :
    PHPInfo 2
    PHPInfo 1
    x86 or x64, and TS (Thread Safe) or NTS (Non Thread Safe)
  3. to download the corresponding DLL (including your PHP version):
    (PHP 7: http://pecl.php.net/package/APCu/5.1.3/windows)
  4. to copy/paste the DLL file within your extensions directory
  5. to edit your php.ini file (i.e. within C:xamppphp directory)
  6. and add this line inside Dynamic Extensions part :
; Dynamic Extensions ;



Eventually don’t forget to restart Apache !

PHP : How to install Intl extension in Xampp ?


The PHP Internationalization extension is used, amongst others, by Symfony (for validators). This extension allows you to write codes like this one :

$formatter = new NumberFormatter('en_US', NumberFormatter::DECIMAL);
echo $formatter->format(1234567.89); // 1,234,567.89

$formatter = new NumberFormatter('fr_FR', NumberFormatter::DECIMAL);
echo $formatter->format(1234567.89); // 1 234 567,89

$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
echo $formatter->getTextAttribute(NumberFormatter::CURRENCY_CODE); // USD

$formatter = new NumberFormatter('pt_BR', NumberFormatter::CURRENCY);
echo $formatter->getTextAttribute(NumberFormatter::CURRENCY_CODE); // BRL

and so much more, including formatting of currency, number and date/time as well as UCA-conformant collations (customizable method to compare two strings).

To activate this extension in Xampp, just edit your php.ini (i.e. in C:\xampp\php directory) and remove the semicolon to uncomment this line :


Eventually don’t forget to restart Apache !

Cordova : detecting shaking


For I Met, I needed to detect shaking to allow users adding each other to their timeline by simply shaking their phone at the same time. I did a little search and found leecrossley’s shake.js script but it didn’t really work. Thus I slightly improved it to write this one.

Here is a small sample on how to use it :

// Let's wait for the user to shake it !

function onShake()
  alert('Oh yeah, you shook it !');

// Stop watching for shaking event

Here is the script :

var shake = (
  function ()
  	var shake = {},
  		watchId = null,
  		options = { frequency: 300 },
  		previousAcceleration = { x: null, y: null, z: null },
  		shakeCallBack = null;
  	// Start watching the accelerometer for a shake gesture
  	shake.startWatch = function (onShake)
  		if (onShake) {
  			shakeCallBack = onShake;
  		watchId = navigator.accelerometer.watchAcceleration(getAccelerationSnapshot, handleError, options);
  	// Stop watching the accelerometer for a shake gesture
  	shake.stopWatch = function ()
  		if (watchId !== null) {
  			watchId = null;
  	// Gets the current acceleration snapshot from the last accelerometer watch
  	function getAccelerationSnapshot()
  		navigator.accelerometer.getCurrentAcceleration(assessCurrentAcceleration, handleError);
  	// Assess the current acceleration parameters to determine a shake
  	function assessCurrentAcceleration (acceleration)
      var accelerationChange;
  		if (previousAcceleration !== null)
  			accelerationChange = Math.abs(Math.round(Math.abs(previousAcceleration.x) - Math.abs(acceleration.x))) + Math.abs(Math.round(Math.abs(previousAcceleration.y) - Math.abs(acceleration.y))) + Math.abs(Math.round(Math.abs(previousAcceleration.z) - Math.abs(acceleration.z)));
      // Shake detected :
      if (accelerationChange > 10)
  			if (typeof (shakeCallBack) === "function")


  			setTimeout(shake.startWatch, 1000);

  			previousAcceleration = { 
  				x: null, 
  				y: null, 
  				z: null
  			previousAcceleration = {
  				x: acceleration.x,
  				y: acceleration.y,
  				z: acceleration.z

  	// Handle errors here
  	function handleError()

  	return shake;


And here is the minified version :

var shake=function(){function s(){navigator.accelerometer.getCurrentAcceleration(o,u)}function o(t){var n;if(r!==null){n=Math.abs(Math.round(Math.abs(r.x)-Math.abs(t.x)))+Math.abs(Math.round(Math.abs(r.y)-Math.abs(t.y)))+Math.abs(Math.round(Math.abs(r.z)-Math.abs(t.z)))}if(n&gt;10){if(typeof i==="function"){i()}e.stopWatch();setTimeout(e.startWatch,1e3);r={x:null,y:null,z:null}}else{r={x:t.x,y:t.y,z:t.z}}}function u(){}var e={},t=null,n={frequency:300},r={x:null,y:null,z:null},i=null;e.startWatch=function(e){if(e){i=e}t=navigator.accelerometer.watchAcceleration(s,u,n)};e.stopWatch=function(){if(t!==null){navigator.accelerometer.clearWatch(t);t=null}};return e}()

PHP : How to use 4 methods (DELETE, GET, POST, PUT) in a RESTful API client using Curl ?


Finishing my first release of PhpRestDoc I had to develop a cross-method solution to allow users to test REST API requesting directly from the documentation and get 3 parts of the API response :

  • HTTP Status Code,
  • Header,
  • Body,

through 4 different methods :

  • GET,
  • POST,
  • PUT.

Also I wanted to be able to set what content type I wanted to get (JSON, XML, etc).

I then fully commented to share you the source code I wrote to achieve that :

  Set the Request Url (without Parameters) here
$api_request_url = 'https://api.example.com/user/info/';

  Which Request Method do I want to use ?
$method_name = 'GET';

  Let's set all Request Parameters (api_key, token, user_id, etc)
$api_request_parameters = array(
  'api_key' => 'gF7mc05157W726sL',
  'token' => 'hnFGJSpNzMzft8GE8AVTdvyZaydNYorgthkO46Rt',
  'user_id' => 5428

$ch = curl_init();

if ($method_name == 'DELETE')
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($api_request_parameters));

if ($method_name == 'GET')
  $api_request_url .= '?' . http_build_query($api_request_parameters);

if ($method_name == 'POST')
  curl_setopt($ch, CURLOPT_POST, TRUE);
  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($api_request_parameters));

if ($method_name == 'PUT')
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($api_request_parameters));

  Here you can set the Response Content Type you prefer to get :
  application/json, application/xml, text/html, text/plain, etc
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));

  Let's give the Request Url to Curl
curl_setopt($ch, CURLOPT_URL, $api_request_url);

  Yes we want to get the Response Header
  (it will be mixed with the response body but we'll separate that after)
curl_setopt($ch, CURLOPT_HEADER, TRUE);

  Allows Curl to connect to an API server through HTTPS
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

  Let's get the Response !
$api_response = curl_exec($ch);

  We need to get Curl infos for the header_size and the http_code
$api_response_info = curl_getinfo($ch);

  Don't forget to close Curl

  Here we separate the Response Header from the Response Body
$api_response_header = trim(substr($api_response, 0, $api_response_info['header_size']));
$api_response_body = substr($api_response, $api_response_info['header_size']);

// Response HTTP Status Code
echo $api_response_info['http_code'];

// Response Header
echo $api_response_header;

// Response Body
echo $api_response_body;