PHP利用fsockopen函数GET、POST提交表单

1、GET

发送端:

<?php
$host = 'ken.01h.net';
$port = 80;
$errno = '';
$errstr = '';
$timeout = 30;
$url = '/receive.php';
 
$param = array(
    'name' => 'ken',
    'gender' => 'man'
);
 
$url = $url.'?'.http_build_query($param);
 
// create connect
$fp = fsockopen($host, $port, $errno, $errstr, $timeout);
 
if(!$fp){
    return false;
}
 
// send request
$out = "GET ${url} HTTP/1.1\r\n";
$out .= "Host: ${host}\r\n";
$out .= "Connection:close\r\n\r\n";
 
fputs($fp, $out);
 
// get response
$response = '';
while($row=fread($fp, 4096)){
    $response .= $row;
}
 
fclose($fp);
 
$pos = strpos($response, "\r\n\r\n");
$response = substr($response, $pos+4);
 
echo $response;
?>

接收端:

<?php
$name = $_GET['name'];
$gender = $_GET['gender'];
 
echo 'name='.$name.'<br>';
echo 'gender='.$gender;
?>

2、POST

发送端:

<?php
$host = 'ken.01h.net';
$port = 80;
$errno = '';
$errstr = '';
$timeout = 30;
$url = '/receive.php';
 
$param = array(
    'name' => 'ken',
    'gender' => 'man',
    'photo' => file_get_contents('./photo.jpg')
);
 
$data = http_build_query($param);
 
// create connect
$fp = fsockopen($host, $port, $errno, $errstr, $timeout);
 
if(!$fp){
    return false;
}
 
// send request
$out = "POST ${url} HTTP/1.1\r\n";
$out .= "Host:${host}\r\n";
$out .= "Content-type:application/x-www-form-urlencoded\r\n";
$out .= "Content-length:".strlen($data)."\r\n";
$out .= "Connection:close\r\n\r\n";
$out .= "${data}";
 
fputs($fp, $out);
 
// get response
$response = '';
while($row=fread($fp, 4096)){
    $response .= $row;
}
 
fclose($fp);
 
$pos = strpos($response, "\r\n\r\n");
$response = substr($response, $pos+4);
 
echo $response;
?>

接收端:

<?php
define('UPLOAD_PATH', dirname(__FILE__).'/upload');
 
$name = $_POST['name'];
$gender = $_POST['gender'];
$photo = $_POST['photo'];
 
$filename = time().'.jpg';
file_put_contents(UPLOAD_PATH.'/'.$filename, $photo, true);
 
echo 'name='.$name.'<br>';
echo 'gender='.$gender.'<br>';
echo '<img src="upload/'.$filename.'">';
?>

发表评论

邮箱地址不会被公开。 必填项已用*标注