Tuesday, February 5, 2013

PHP - cURL - Optimise Speed Reusing SSL Connections

Below is an example of using cURL to fetch multiple URLs that are using SSL and then reuse those connections to retrieve more data. This example fetches 2 URLs simultaneously which both open an SSL connection, then the next lot of 2 URLs reuse those connections to retrieve data thereby bypassing the SSL handshake.

<?php
//Number of SSL connections to use
$connections = 2;

//Array of URLs to retrieve using https
$urls = array();
$urls[] = 'https://www.googleapis.com/plus/v1/people/105381197794279347286?fields=displayName%2Cgender%2CobjectType&key=AIzaSyCFj15TpkchL4OUhLD1Q2zgxQnMb7v3XaM';
$urls[] = 'https://www.googleapis.com/plus/v1/people/105381197794279347286?fields=displayName%2Cgender%2CobjectType&key=AIzaSyCFj15TpkchL4OUhLD1Q2zgxQnMb7v3XaM';
$urls[] = 'https://www.googleapis.com/plus/v1/people/105381197794279347286?fields=displayName%2Cgender%2CobjectType&key=AIzaSyCFj15TpkchL4OUhLD1Q2zgxQnMb7v3XaM';
$urls[] = 'https://www.googleapis.com/plus/v1/people/105381197794279347286?fields=displayName%2Cgender%2CobjectType&key=AIzaSyCFj15TpkchL4OUhLD1Q2zgxQnMb7v3XaM';
$urls[] = 'https://www.googleapis.com/plus/v1/people/105381197794279347286?fields=displayName%2Cgender%2CobjectType&key=AIzaSyCFj15TpkchL4OUhLD1Q2zgxQnMb7v3XaM';
$urls[] = 'https://www.googleapis.com/plus/v1/people/105381197794279347286?fields=displayName%2Cgender%2CobjectType&key=AIzaSyCFj15TpkchL4OUhLD1Q2zgxQnMb7v3XaM';

//Number of times to reuse each SSL connection (6/2 = 3)
$reuse = count($urls) / $connections;

//Array used to store multiple cURL handles for each SSL connection
$handle = array();

//Array used to store all returned page data
$result = array();

//Log file used to see that only 2 SSL conections are being used
//$logfh = fopen("curl.log", 'a+');

//Loop for each SSL connection
for($r=0;$r<$reuse;$r++) {
  //Loop for each reuse of the SSL connection
  for($c=0;$c<$connections;$c++) {
    //Initialise a cURL session using the urls
    $handle[$c] = curl_init($urls[($r*$connections)+$c]);

    //Set any options you want here
    curl_setopt($handle[$c], CURLOPT_HTTPHEADER, array('x-origin: https://developers.google.com'));
    curl_setopt($handle[$c], CURLOPT_RETURNTRANSFER, true);
    //Turns on detailed info for the log
    //curl_setopt($handle[$c], CURLOPT_VERBOSE, true);
    //Send the output to the log file
    //curl_setopt($handle[$c], CURLOPT_STDERR, $logfh);

    static $multi = NULL;
    if (empty($multi)) {
      //Initialise a multi cURL session if one does not already exist
      $multi = curl_multi_init();
    }

    //Add the single cURL handle to the mutli cURL handle
    curl_multi_add_handle($multi, $handle[$c]);
  }

  $running = NULL;
  do {
    //Execute all handles in $multi until all are completed
    curl_multi_exec($multi, $running);
  } while($running > 0);

  for($i=0;$i<$connections;$i++) {
    //Do something with each result
    $result[] = curl_multi_getcontent($handle[$i]);
    //Remove the single cURL handle from the multi cURL handle
    curl_multi_remove_handle($multi, $handle[$i]);
  }
}
//Dump the result which will show my public profile info 6 times
var_dump($result);
?>

Output: This will output 6 arrays, one for each of the pages we retrieved. It will contain some public information from my Google+ profile.

Note: If you use the curl.log you must ensure you have the correct permissions on the file.

Sunday, April 15, 2012

Javascript - Object.keys Browser Compatibility

For Object.keys compatibility in all browsers add this code before using Object.keys.

if (!Object.keys) Object.keys = function(o) {
  if (o !== Object(o))
    throw new TypeError('Object.keys called on a non-object');
  var k=[],p;
  for (p in o) if (Object.prototype.hasOwnProperty.call(o,p)) k.push(p);
  return k;
}

You can now use Object.keys as normal such as Object.keys(myObject).length

Wednesday, May 25, 2011

JavaScript - AJAX / SJAX - Submit Form Data to PHP Script

Below is a function I use to submit form data (POST) to a PHP script using Asynchronous / Synchronous JavaScript And XML.

function runSQL(div, script, data) {
  var
ajax = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest;
  if (div != "") {
    ajax.onreadystatechange = function () {
     if (ajax.readyState == 4) {document.getElementById(div).innerHTML = ajax.responseText}; //AJAX
    };
  }
  ajax.open("POST", script, div != '' ? true : false);
  if (data) {ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")};
  ajax.send(data ? data : null);
  if (div == "") {
    return ajax.responseText; //SJAX
  } else {
    return
;
  }
}

Example of AJAX call:

runSQL('DIV_Content', 'sql.php', 'action=getContents&page=Home&custom=1');

Example of SJAX call:

result = runSQL('', 'sql.php', 'action=getContents&page=Home&custom=1');
//Do something with result

Note: Using AJAX allows the JavaScript to continue executing however using SJAX forces JavaScript to wait for the result before continuing. This is useful if you need to do something with the result such as use it in a calculation elsewhere in JavaScript whereas the AJAX result can just be returned straight to the HTML div element as is, once it is ready.

Thursday, May 19, 2011

jQuery - Tables - Show and Hide Columns

You can hide and show columns in a table by specifying a column index where 1 is the first column in the table.

function toggleColumn(column) {
  $('#iTable tr *:nth-child('+ column +')').toggle();
}

Note: iTable is the name of the HTML table.
Note: The * is used to ensure you show / hide both the TH and TD tags.

Friday, May 6, 2011

jQuery - Datepicker - Disable Specific Dates

You can disable specific dates with the jQuery Datepicker using the beforeShowDay event.

var unavailableDates = ["9-5-2011","14-5-2011","15-5-2011"];

function unavailable(date) {
  dmy = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear();
  if ($.inArray(dmy, unavailableDates) < 0) {
    return [true
,"","Book Now"];
  } else {
    return [false
,"","Booked Out"];
  }
}

$('#iDate').datepicker({ beforeShowDay: unavailable });

Note: iDate in the last line is the name of the HTML form input element.

To see a working example with some more features please see the jsFiddle example: HERE