̃Gg[͂ĂȃubN}[Nɒlj

PHP :: POSTリクエストを送信する for PHP4



class HTTP
{
    /**
     * POSTリクエストを送信する (プロトコルは http のみに対応)
     * 
     * for PHP 4
     * 
     * @param string $uri 送信先URI (http://~)
     * @param array $data 送信するデータ array('name'=>'value', ...)
     * @param float $timeout タイムアウト秒
     * @return boolean
     * @access public
     * @static
     */
    function postRequest($uri, $data, $timeout = 60)
    {
        $elem = parse_url($uri);
        $host = $elem['host'];
        $path = $elem['path'];
        $scheme = $elem['scheme'];
 
        if (strtolower($scheme) !== 'http') {
            return false;
        }
 
        $sock = fsockopen($host, 80, $errno, $errstr, $timeout);
        if ( ! $sock) {
            //return "$errstr ($errno)\n";
            return false;
        }
 
        $params = array();
        foreach ($data as $k => $v) {
            $params[] = $k . '=' . urlencode($v);
        }
        $param = implode('&', $params);
 
                  $ret = fwrite($sock, "POST $path HTTP/1.0\r\n");
        if ($ret) $ret = fwrite($sock, "Host: $host\r\n");
        if ($ret) $ret = fwrite($sock, "Content-type: application/x-www-form-urlencoded\r\n");
        if ($ret) $ret = fwrite($sock, "Content-length: " . strlen($param) . "\r\n");
        if ($ret) $ret = fwrite($sock, "Accept: */*\r\n");
        if ($ret) $ret = fwrite($sock, "\r\n");
        if ($ret) $ret = fwrite($sock, "$param\r\n");
        if ($ret) $ret = fwrite($sock, "\r\n");
 
        fclose($sock);
 
        if ($ret === false) {
            return false;
        }
 
        return true;
    }
}


■使い方

require_once 'HTTP.php';
$uri = 'http://hoge.fuga/jojo.php';
$data = array('val_1' => '100', 'val_2' => '200');
$res = HTTP::postRequest($uri, $data);


PHP5版




programming/php/etc/http_post_request_php4.txt