request.class.php 2.04 KB
<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Class support for requesting to a server
 * CreateDate: 22 February 2011
 * Author: Khanh Huy
 * Email :khanhhuyna@gmail.com
 */
class FgcRequest {

    var $url;

    function __construct($url = null) {
        $this->url = $url;
    }

    function __destruct() {

    }

    /**
     *
     * @param string $url
     * @param boolean $synchronize .Define whether the script return immediately without waiting for a output from server
     * or require to get output from server.
     * @param string $requestType
     * @return mixed
     */
    function request($url = null, $synchronize = false, $requestType = 'POST') {
        if ($url === null)
            $url = $this->url;

        if (empty($url))
            return;

        if ($synchronize) {
            $fp = fopen($url, 'r');
            if (!$fp) {
                return false;
            } else {
                $return = '';
                while (!feof($fp)) {
                    $return .= fgets($fp, 1024);
                }
            }
            fclose($fp);
            return $return;
        } else {
            $parts = parse_url($url);
            $fp = fsockopen($parts['host'], isset($parts['port']) ? $parts['port'] : 80, $errno, $errstr, 600);
            if (!$fp) {
                return false;
            } else {

                $out = "POST " . $parts['path'] . " HTTP/1.1\r\n";
                $out .= "Host: " . $parts['host'] . "\r\n";
                $out .= "Connection: Close\r\n";
                if (isset($parts['query'])) {
                    $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
                    $out .= "Content-Length: " . strlen($parts['query']) . "\r\n";
                }
                $out .= "\r\n";
                if (isset($parts['query']))
                    $out .= $parts['query'];

                fwrite($fp, $out);
                fclose($fp);

                return true;
            }
        }
    }

}

?>