關於 PHP, Linux, Open Source 及個人生活記載的網誌。
RSS icon
  • 不使用 form 之下傳送 POST 變數

    Posted on December 11th, 2007 Sam Tang No comments

    可以打開 HTTP socket 連線及傳送 HTTP POST 指令,以下是範例:

    PHP:
    1. <?php
    2. // Generate the request header
    3. $ReqHeader =
    4. "POST $URI HTTP/1.1n".
    5. "Host: $Hostn".
    6. "Content-Type: application/x-www-form-urlencodedn".
    7. "Content-Length: $ContentLengthnn".
    8. "$ReqBodyn";
    9.  
    10. // Open the connection to the host
    11. $socket = fsockopen($Host, 80, &$errno, &$errstr);
    12. if (!$socket){
    13.  
    14.    $Result["errno"] = $errno;
    15.    $Result["errstr"] = $errstr;
    16.    return $Result;
    17. }
    18. $idx = 0;
    19. fputs($socket, $ReqHeader);
    20. while (!feof($socket)){
    21.    $Result[$idx++] = fgets($socket, 128);
    22. }
    23. //-------------------------------------------
    24. ?>

    或者可以使用 PHP 的 cURL extension。當你安裝了 cURL 及重新編譯 PHP 支援 cURL後,便可以用以下這個較簡單的方法:

    PHP:
    1. <?php
    2. $URL="www.mysite.com/test.php";
    3. $ch = curl_init();
    4. curl_setopt($ch, CURLOPT_URL,"https://$URL");
    5. curl_setopt($ch, CURLOPT_POST, 1);
    6. curl_setopt($ch, CURLOPT_POSTFIELDS, "Data1=blah&Data2=blah");curl_exec ($ch);
    7. curl_close ($ch);
    8. ?>


    Leave a reply

    *
    To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
    Click to hear an audio file of the anti-spam word