开发者

Post an array using PHP socket

HI,

I want to send post data using PHP Soket.

How can I 开发者_如何转开发Post?

E.g $postData = array('value1', 'value2', 'value3');

I want to send $postData from "index.php" to "myweb.php" page using PHP Socket.

Thanks in advance.


You'll need to serialize the data somehow. You could use serialize() and unserialize() between PHP scripts; however, if you think the data will be used by others, JSON might be preferred: json_encode() and json_decode()


 function http_request($request_url, $type='get', $data=array()) {
    $url   = parse_url($request_url);
    $host  = $url['host'];
    $path  = $url['path'];
    $query = $url['query'];
    $path .= $query ? '?'. $query : '';

    $parameter = $sep = '';
    if (!empty($data)) {
        foreach ($data as $key => $value){
            $parameter .= $sep . urlencode($key) .'='. urlencode($value);
            $sep = '&';
        }
    }
    if (strtolower($type) == 'get') {
        $path .= $parameter;
        $out  = "GET {$path} HTTP/1.1\r\n";
        $out .= "Accept: */*\r\n";
        $out .= "Accept-Language: zh-cn\r\n";
        $out .= "User-Agent: {$_SERVER['HTTP_USER_AGENT']}\r\n";
        $out .= "Host: {$host}\r\n";
        $out .= "Connection: Close\r\n\r\n";
    } else {
        $out  = "POST {$path} HTTP/1.1\r\n";
        $out .= "Accept: */*\r\n";
        $out .= "Accept-Language: zh-cn\r\n";
        $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $out .= "User-Agent: {$_SERVER['HTTP_USER_AGENT']}\r\n";
        $out .= "Host: {$host}\r\n";
        $out .= 'Content-Length: '.strlen($parameter)."\r\n";
        $out .= "Connection: Close\r\n\r\n";
        $out .= $parameter;
    }
    $fp = fsockopen($host, 80, $errno, $errstr, 30);
    if ($fp) {
        fwrite($fp, $out);
        fclose($fp);
    }
 }


Are you sure you're not trying to just create an AJAX request? Sockets are created on the server side so while it's not so very unusual to create a socket on a web page it is strange to have it turn around and establish an HTTP connection to a local resource.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜