client snippets

How to upload a file with PHP and lib_curl

Tagged php, file, upload, client, pear  Languages php

This is an example of how to upload a file from PHP to another server that may or may not be running PHP.

Note that using Pear's HTTP_Request package is probably easier.

<?php
  require_once('Var_Dump.php');
  Var_Dump::displayInit(array('display_mode' => 'HTML4_Text'), array('mode' => 'normal','offset' => 4));

  $url = 'www.aktagon.com/upload';
  $file = '/tmp/file_to_upload';
  $post_data = array();

  $post_data['username'] = '';
  $post_data['password'] = '';
  $post_data['file'] = "@$file";

  $ch = curl_init();

  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
#    'Cookie: xxxx',
#    'Content-Type: xxxx'
  ));
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  curl_setopt($ch, CURLOPT_POST, true);
  #curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:8888');

  curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

  $response  = curl_exec($ch);
  $info      = curl_getinfo($ch); 
  $http_code = $info['http_code'];
  $speed     = round($info['speed_upload'] / 1024);
  $size      = round($info['size_upload'] / 1024);

  if($http_code != 200)
  {
    echo "Upload failed with HTTP code $http_code. Uploaded $size kilobytes with $speed kilobytes/s.<br/>";
    echo "<h1>Response</h1><pre>$response</pre><h1>Debug information</h1>";

    Var_Dump::display($info);
  }
  else
  {
    echo "Uploaded successful. Uploaded $size kilobytes with $speed kilobytes / s.<br/>";
    echo "<h1>Response</h1><pre>$response</pre>";
  }
  curl_close($ch);
?>

You can remove the Var_Dump code (Pear module), if you haven't installed it, or don't need it.

A simple HTTP client for PHP

Tagged http, client, php  Languages php

A simple HTTP client for PHP that uses curl:

class HTTP {
    static function get($url, $headers=null) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_HEADER, true);

        if($headers) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }

        // Execute request
        $response = curl_exec($ch);

        // Split headers and body
        list($header_text, $body) = explode("\r\n\r\n", $response, 2);
        $header_lines = explode("\r\n", $header_text);

        // Extract HTTP status
        $header_line = array_shift($header_lines);
        if (preg_match('@^HTTP/[0-9]\.[0-9] ([0-9]{3})@', $header_line, $matches)) {
            $status = $matches[1];
        }

        // Extract HTTP headers
        $headers = array();
        foreach ($header_lines as $header_line) {
            list($header, $value) = explode(': ', $header_line, 2);
            $headers[$header] = $value;
        }

        $info = curl_getinfo($ch); 

        curl_close($ch);    

        $status = $info['http_code'];

        return new Response($status, $body, $headers, $info);
    }
}

Even supports reading response headers.

class Response  {
    public function Response($code, $body, $headers, $info=null) {
        $this->code = $code;
        $this->body = $body;
        $this->headers = $headers;
        $this->info = $info;
    }
}

A simple Python HTTP client

Tagged client, python, http  Languages python

A simple HTTP client I had laying around that I wrote a long time ago. It supports cookies, redirects and stuff:

#!/usr/bin/env python
#
#     Http
#
#     A simple HTTP client that supports persistent cookies
#

import cookielib
import httplib
#httplib.HTTPConnection.debuglevel = 1
import urllib2

class Http:
  def __init__(self, redirect_callback = None):
    self.redirect_callback = redirect_callback
    self.cookie_jar = cookielib.CookieJar()
    self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor (self.cookie_jar))

    urllib2.install_opener(self.opener)

  def get(self, url, headers = None):
    request = urllib2.Request(url, headers = headers)
    return self.execute_request(request)

  def post(self, url, headers = None, parameters = None):
    data = None
    if parameters != None:
      data = urllib.urlencode(parameters)

    request = urllib2.Request(url, data, headers)
    return self.execute_request(request)

  def execute_request(self, request):
    response = self.opener.open(request)
    # Check for redirect, maybe better way to do this
    if response.geturl() != request.get_full_url():
      if self.redirect_callback == None:
        raise "Redirected to '" + response.geturl() + "' but no redirect callback defined"
      else:
        self.redirect_callback(response)

    return response