Hướng dẫn php send post request with headers - php gửi yêu cầu bài đăng với tiêu đề

Tôi muốn thêm một số suy nghĩ về câu trả lời dựa trên Curl của Fred Tanrikut. Tôi biết hầu hết trong số họ đã được viết trong các câu trả lời ở trên, nhưng tôi nghĩ rằng đó là một ý tưởng tốt để hiển thị một câu trả lời bao gồm tất cả chúng cùng nhau.

Dưới đây là lớp tôi đã viết để thực hiện các yêu cầu http-get/post/put/xóa dựa trên curl, liên quan đến cơ thể phản hồi:

class HTTPRequester {
    /**
     * @description Make HTTP-GET call
     * @param       $url
     * @param       array $params
     * @return      HTTP-Response body or an empty string if the request fails or is empty
     */
    public static function HTTPGet($url, array $params) {
        $query = http_build_query($params); 
        $ch    = curl_init($url.'?'.$query);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }
    /**
     * @description Make HTTP-POST call
     * @param       $url
     * @param       array $params
     * @return      HTTP-Response body or an empty string if the request fails or is empty
     */
    public static function HTTPPost($url, array $params) {
        $query = http_build_query($params);
        $ch    = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }
    /**
     * @description Make HTTP-PUT call
     * @param       $url
     * @param       array $params
     * @return      HTTP-Response body or an empty string if the request fails or is empty
     */
    public static function HTTPPut($url, array $params) {
        $query = \http_build_query($params);
        $ch    = \curl_init();
        \curl_setopt($ch, \CURLOPT_RETURNTRANSFER, true);
        \curl_setopt($ch, \CURLOPT_HEADER, false);
        \curl_setopt($ch, \CURLOPT_URL, $url);
        \curl_setopt($ch, \CURLOPT_CUSTOMREQUEST, 'PUT');
        \curl_setopt($ch, \CURLOPT_POSTFIELDS, $query);
        $response = \curl_exec($ch);
        \curl_close($ch);
        return $response;
    }
    /**
     * @category Make HTTP-DELETE call
     * @param    $url
     * @param    array $params
     * @return   HTTP-Response body or an empty string if the request fails or is empty
     */
    public static function HTTPDelete($url, array $params) {
        $query = \http_build_query($params);
        $ch    = \curl_init();
        \curl_setopt($ch, \CURLOPT_RETURNTRANSFER, true);
        \curl_setopt($ch, \CURLOPT_HEADER, false);
        \curl_setopt($ch, \CURLOPT_URL, $url);
        \curl_setopt($ch, \CURLOPT_CUSTOMREQUEST, 'DELETE');
        \curl_setopt($ch, \CURLOPT_POSTFIELDS, $query);
        $response = \curl_exec($ch);
        \curl_close($ch);
        return $response;
    }
}

Cải tiến

  • Sử dụng http_build_query để lấy chuỗi truy vấn ra khỏi mảng yêu cầu.
  • Trả lời phản hồi thay vì lặp lại nó. BTW Bạn có thể tránh trả lại bằng cách loại bỏ dòng curl_setopt ($ CH, curlopt_returntransfer, true) ;. Sau đó, giá trị trả về là boolean (true = yêu cầu đã thành công nếu không có lỗi xảy ra) và phản hồi được lặp lại. Xem: http://php.net/en/manual/function.curl-exec.phpcurl_setopt($ch, CURLOPT_RETURNTRANSFER, true);. After that the return value is a boolean(true = request was successful otherwise an error occured) and the response is echoed. See: http://php.net/en/manual/function.curl-exec.php
  • Làm sạch phiên đóng và xóa tay cầm curl bằng cách sử dụng curl_close. Xem: http://php.net/manual/en/function.curl-close.phpcurl_close. See: http://php.net/manual/en/function.curl-close.php
  • Sử dụng các giá trị boolean cho hàm Curl_setopt thay vì sử dụng bất kỳ số nào. (Tôi biết rằng bất kỳ số nào không bằng 0 cũng được coi là đúng, nhưng việc sử dụng True tạo ra một mã dễ đọc hơn, nhưng đó chỉ là ý kiến ​​của tôi)curl_setopt function instead of using any number.(I know that any number not equal zero is also considered as true, but the usage of true generates a more readable code, but that's just my opinion)
  • Khả năng thực hiện các cuộc gọi HTTP-PUT/Xóa (hữu ích cho kiểm tra dịch vụ RESTful)

Ví dụ về việc sử dụng

LẤY

$response = HTTPRequester::HTTPGet("http://localhost/service/foobar.php", array("getParam" => "foobar"));

BƯU KIỆN

$response = HTTPRequester::HTTPPost("http://localhost/service/foobar.php", array("postParam" => "foobar"));

ĐẶT

$response = HTTPRequester::HTTPPut("http://localhost/service/foobar.php", array("putParam" => "foobar"));

XÓA BỎ

$response = HTTPRequester::HTTPDelete("http://localhost/service/foobar.php", array("deleteParam" => "foobar"));

Kiểm tra

Bạn cũng có thể thực hiện một số bài kiểm tra dịch vụ thú vị bằng cách sử dụng lớp đơn giản này.

class HTTPRequesterCase extends TestCase {
    /**
     * @description test static method HTTPGet
     */
    public function testHTTPGet() {
        $requestArr = array("getLicenses" => 1);
        $url        = "http://localhost/project/req/licenseService.php";
        $this->assertEquals(HTTPRequester::HTTPGet($url, $requestArr), '[{"error":false,"val":["NONE","AGPL","GPLv3"]}]');
    }
    /**
     * @description test static method HTTPPost
     */
    public function testHTTPPost() {
        $requestArr = array("addPerson" => array("foo", "bar"));
        $url        = "http://localhost/project/req/personService.php";
        $this->assertEquals(HTTPRequester::HTTPPost($url, $requestArr), '[{"error":false}]');
    }
    /**
     * @description test static method HTTPPut
     */
    public function testHTTPPut() {
        $requestArr = array("updatePerson" => array("foo", "bar"));
        $url        = "http://localhost/project/req/personService.php";
        $this->assertEquals(HTTPRequester::HTTPPut($url, $requestArr), '[{"error":false}]');
    }
    /**
     * @description test static method HTTPDelete
     */
    public function testHTTPDelete() {
        $requestArr = array("deletePerson" => array("foo", "bar"));
        $url        = "http://localhost/project/req/personService.php";
        $this->assertEquals(HTTPRequester::HTTPDelete($url, $requestArr), '[{"error":false}]');
    }
}

Làm cách nào để gửi một yêu cầu bài viết bằng PHP?

Có hai tùy chọn để gửi các yêu cầu POST từ PHP: Sử dụng thư viện Curl tích hợp và phương thức không có Curl sử dụng các chức năng phát trực tuyến gốc của PHP. Trong ví dụ yêu cầu bài PHP này, chúng tôi đang gửi một yêu cầu bài đăng bằng thư viện Curl.using the built-in Curl library and the CURL-less method that uses PHP's native streaming functions. In this PHP POST request example, we are sending a POST request using the Curl library.

Làm thế nào để gửi yêu cầu POST đến API REST trong PHP?

Để gửi dữ liệu đến máy chủ API REST bằng PHP, bạn phải thực hiện yêu cầu POST HTTP và bao gồm dữ liệu bài đăng trong thân của yêu cầu. Bạn cũng cần cung cấp các tiêu đề yêu cầu loại nội dung: Ứng dụng/JSON và độ dài nội dung. Dưới đây là một ví dụ về yêu cầu POST API REST cho điểm cuối API REQBIN REST.make an HTTP POST request and include the POST data in the request's body. You also need to provide the Content-Type: application/json and Content-Length request headers. Below is an example of a REST API POST request to a ReqBin REST API endpoint.

Làm thế nào để gửi dữ liệu JSON bằng cách sử dụng yêu cầu bài đăng HTTP trong PHP?

Gửi dữ liệu JSON qua POST với PHP Curl Chỉ định URL ($ url) nơi dữ liệu JSON được gửi.Bắt đầu tài nguyên Curl mới bằng Curl_init ().Thiết lập dữ liệu trong mảng PHP và mã hóa thành chuỗi JSON bằng json_encode ().Gắn dữ liệu JSON vào các trường bài bằng cách sử dụng tùy chọn Curlopt_PostFields.Specify the URL ( $url ) where the JSON data to be sent. Initiate new cURL resource using curl_init(). Setup data in PHP array and encode into a JSON string using json_encode(). Attach JSON data to the POST fields using the CURLOPT_POSTFIELDS option.

Làm thế nào đăng URL trong PHP?

Nếu bạn đang tìm cách đăng dữ liệu lên URL từ chính mã PHP (mà không sử dụng biểu mẫu HTML), nó có thể được thực hiện với Curl.Nó sẽ trông như thế này: $ url = 'http://www.someurl.com';$ myvars = 'myvar1 ='.$ myvar1.with curl. It will look like this: $url = 'http://www.someurl.com'; $myvars = 'myvar1=' . $myvar1 .