08 Mar 2012

Sending compressed data over http with PHP curl

There are times applications need to sync across multiple servers by data transfer via http. This data could at times be bulky, taking up to tenths of megs. Instead of sending that large volume, a better way would be to compress first, send, and decompress at the other end. This will not only reduce the consumption of bandwidth but as well make the transfer faster.

Here is a the way to do it in PHP using the CURL library:

  1. Compress the data

    1
    2
    
    <?php
    $compressed_data = gzdeflate($raw_data, 9);
    

  2. Send

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    
    <?php
    $url = "http://some_site_or_ip.com/reciever.php";
    //open connection
    $ch = curl_init();
    //set the url and POST data
    curl_setopt($ch,CURLOPT_URL, $url);
    curl_setopt($ch,CURLOPT_POST, true);
    curl_setopt($ch,CURLOPT_POSTFIELDS, $compressed_data);
    //execute post
    $result = curl_exec($ch);
    //echo curl_error($ch);
    //close connection
    curl_close($ch);
    

  3. Decompress (at the other end i.e reciever.php)

    1
    2
    3
    4
    
    <?php
    $input = file_get_contents('php://input');
    $output = gzinflate($input);
    // You have ur data back as $output
    

 

Looking for a simple marketing automation tool to automate your customer onboarding, retention and lifecycle emails? Check out Engage and signup for free.

 

My name is Opeyemi Obembe. I build things for web and mobile and write about my experiments. Follow me on Twitter—@kehers.

 

Next post: Freemium - when the number doesn't matter