1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| function http_post($host, $path, $data_hash, $file = '', $file_param_name = '') { $boundary = md5(uniqid()); if ($file && $file_param_name) { $binary = file_get_contents($file['tmp_name']);
$content_type = "multipart/form-data; boundary=$boundary";
$items = array(); foreach (array_keys($data_hash) as $key) { array_push($items, "--$boundary\r\nContent-Disposition: form-data; name=\"$key\"\r\n\r\n{$data_hash[$key]}\r\n"); } array_push($items, "--$boundary\r\nContent-Disposition: form-data; name=\"$file_param_name\"; filename=\"{$file['name']}\"\r\n"); array_push($items, "Content-Type: {$file['type']}\r\nContent-Transfer-Encoding: binary\r\n\r\n$binary\r\n--$boundary--\r\n"); $data = implode('', $items); } else { $content_type = 'application/x-www-form-urlencoded; charset=UTF-8';
$items = array(); foreach (array_keys($data_hash) as $key) { array_push($items, urlencode($key) . '=' . urlencode($data_hash[$key])); } $data = implode('&', $items); }
$content_length = strlen($data); $fp = fsockopen($host, 80); fputs($fp, "POST $path HTTP/1.1\r\n"); fputs($fp, "Host: $host\r\n"); fputs($fp, "Content-Type: $content_type\r\n"); fputs($fp, "Content-Length: $content_length\r\n"); fputs($fp, "Connection: close\r\n\r\n"); fputs($fp, $data, $content_length);
$http_response = stream_get_contents($fp); fclose($fp);
list($headers, $body) = explode("\r\n\r\n", $http_response, 2); return $body; }
|