如何用PHP发送POST请求?

时间:2022-12-01 16:31:44

Actually I want to read the contents that come after the search query, when it is done. The problem is that the URL only accepts POST methods, and it does not take any action with GET method...

实际上,我想要读取搜索查询之后的内容,当它完成时。问题是URL只接受POST方法,并且它不使用GET方法采取任何操作…

I have to read all contents with the help of domdocument or file_get_contents(). Is there any method that will let me send parameters with POST method and then read the contents via PHP?

我必须在domdocument或file_get_contents()的帮助下读取所有内容。有什么方法可以让我用POST方法发送参数,然后通过PHP读取内容吗?

11 个解决方案

#1


1008  

CURL-less method with PHP5:

PHP5 CURL-less方法:

$url = 'http://server.com/path';
$data = array('key1' => 'value1', 'key2' => 'value2');

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data)
    )
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }

var_dump($result);

See the PHP manual for more information on the method and how to add headers, for example:

有关方法的更多信息,以及如何添加标题,请参阅PHP手册,例如:

#2


62  

I did try this one and it is working fine... as I rquired..

我确实试过了,而且效果很好……当我rquired . .

<?php
$url = $file_name;
$fields = array(
            '__VIEWSTATE'=>urlencode($state),
            '__EVENTVALIDATION'=>urlencode($valid),
            'btnSubmit'=>urlencode('Submit')
        );

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
$fields_string = rtrim($fields_string,'&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);

//execute post
$result = curl_exec($ch);
print $result;
?>

#3


35  

I use the following function to post data using curl. $data is an array of fields to post (will be correctly encoded using http_build_query). The data is encoded using application/x-www-form-urlencoded.

我使用以下函数使用curl来发布数据。$data是一个字段的数组(使用http_build_query正确编码)。数据是使用应用程序/x-www-form-urlencode编码的。

function httpPost($url, $data)
{
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
}

@Edward mentions that http_build_query may be omitted since curl will correctly encode array passed to CURLOPT_POSTFIELDS parameter, but be advised that in this case the data will be encoded using multipart/form-data.

@Edward提到,由于curl将正确编码传递给CURLOPT_POSTFIELDS参数的数组,所以可以省略http_build_query,但是请注意,在这种情况下,数据将使用多部分/表单数据进行编码。

I use this function with APIs that expect data to be encoded using application/x-www-form-urlencoded. That's why I use http_build_query().

我使用这个函数使用应用程序/x-www-form-urlencode对数据进行编码的api。这就是为什么我使用http_build_query()。

#4


31  

I recommend you to use the open-source package guzzle that is fully unit tested and uses the latest coding practices.

我建议您使用完全单元测试的开源软件包guzzle,并使用最新的编码实践。

Installing Guzzle

安装狂饮

Go to the command line in your project folder and type in the following command (assuming you already have the package manager composer installed). If you need help how to install Composer, you should have a look here.

转到项目文件夹中的命令行,并键入下面的命令(假设您已经安装了包管理器composer)。如果您需要帮助如何安装Composer,您应该看一下这里。

php composer.phar require guzzlehttp/guzzle

Using Guzzle to send a POST request

使用Guzzle发送一个POST请求。

The usage of Guzzle is very straight forward as it uses a light-weight object-oriented API:

Guzzle的使用非常直接,因为它使用了轻量级的面向对象API:

// Initialize Guzzle client
$client = new GuzzleHttp\Client();

// Create a POST request
$response = $client->request(
    'POST',
    'http://example.org/',
    [
        'form_params' => [
            'key1' => 'value1',
            'key2' => 'value2'
        ]
    ]
);

// Parse the response object, e.g. read the headers, body, etc.
$headers = $response->getHeaders();
$body = $response->getBody();

// Output headers and body for debugging purposes
var_dump($headers, $body);

#5


18  

There's another CURL method if you are going that way.

如果是这样的话,还有另一个旋度法。

This is pretty straightforward once you get your head around the way the PHP curl extension works, combining various flags with setopt() calls. In this example I've got a variable $xml which holds the XML I have prepared to send - I'm going to post the contents of that to example's test method.

这非常简单,一旦您了解了PHP curl扩展的工作方式,将各种标志与setopt()调用组合在一起。在本例中,我有一个变量$xml,它持有我准备发送的xml——我将把它的内容发布到示例的测试方法中。

$url = 'http://api.example.com/services/xmlrpc/';
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
curl_close($ch);
//process $response

First we initialised the connection, then we set some options using setopt(). These tell PHP that we are making a post request, and that we are sending some data with it, supplying the data. The CURLOPT_RETURNTRANSFER flag tells curl to give us the output as the return value of curl_exec rather than outputting it. Then we make the call and close the connection - the result is in $response.

首先,我们初始化连接,然后使用setopt()设置一些选项。这些告诉PHP我们正在做一个post请求,我们正在发送一些数据,提供数据。CURLOPT_RETURNTRANSFER标志告诉curl将输出作为curl_exec的返回值,而不是输出。然后我们调用并关闭连接——结果是$response。

#6


13  

If you by any chance are using Wordpress to develop your app (it's actually a convenient way to get authorization, info pages etc even for very simple stuff), you can use the following snippet:

如果你有任何机会使用Wordpress开发你的应用程序(这实际上是一种获得授权、信息页面等的便捷方式),你可以使用以下代码片段:

$response = wp_remote_post( $url, array('body' => $parameters));

if ( is_wp_error( $response ) ) {
    // $response->get_error_message()
} else {
    // $response['body']
}

It uses different ways of making the actual HTTP request, depending on what is available on the web server. For more details, see the HTTP API documentation.

它使用不同的方法来生成实际的HTTP请求,这取决于web服务器上可用的内容。有关更多细节,请参见HTTP API文档。

If you don't want to develop a custom theme or plugin to start the Wordpress engine, you can just do the following in an isolated PHP file in the wordpress root:

如果你不想开发一个自定义的主题或插件来启动Wordpress引擎,你可以在Wordpress根的一个单独的PHP文件中做以下操作:

require_once( dirname(__FILE__) . '/wp-load.php' );

// ... your code

It won't show any theme or output any HTML, just hack away with the Wordpress APIs!

它不会显示任何主题,也不会输出任何HTML,只需使用Wordpress api就可以了!

#7


9  

I'd like to add some thoughts about the curl-based answer of Fred Tanrikut. I know most of them are already written in the answers above, but I think it is a good idea to show an answer that includes all of them together.

我想补充一些关于Fred Tanrikut的基于curl的答案的想法。我知道他们中的大多数已经写在上面的答案里了,但是我认为最好能给出一个包含所有答案的答案。

Here is the class I wrote to make HTTP-GET/POST/PUT/DELETE requests based on curl, concerning just about the response body:

这里是我写的类,用来使http get /POST/PUT/DELETE请求基于curl,涉及到响应主体:

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;
    }
}

Improvements

  • Using http_build_query to get the query-string out of an request-array.(you could also use the array itself, therefore see: http://php.net/manual/en/function.curl-setopt.php)
  • 使用http_build_query从请求数组中获取查询字符串。(您也可以使用数组本身,因此参见:http://php.net/manual/en/function.curl-setopt.php)
  • Returning the response instead of echoing it. Btw you can avoid the returning by removing the line curl_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
  • 返回响应,而不是响应它。您可以通过删除行curl_setopt($ch, CURLOPT_RETURNTRANSFER, true)来避免返回。在此之后,返回值是一个布尔值(true = request是成功的,否则会出现错误),响应也会得到响应。参见:http://php.net/en/manual/function.curl-exec.php
  • Clean session closing and deletion of the curl-handler by using curl_close. See: http://php.net/manual/en/function.curl-close.php
  • 使用curl_close来关闭和删除curl处理程序。参见:http://php.net/manual/en/function.curl-close.php
  • Using boolean values for the 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)
  • 使用布尔值的curl_setopt函数而不是使用任何数字。(我知道任何不等于零的数字也被认为是正确的,但是使用true会生成更可读的代码,但这只是我的观点)
  • Ability to make HTTP-PUT/DELETE calls(useful for RESTful service testing)
  • 能够进行HTTP-PUT/DELETE调用(用于RESTful服务测试)

Example of usage

GET

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

POST

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

PUT

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

DELETE

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

Testing

You can also make some cool service tests by using this simple class.

您还可以使用这个简单的类来做一些很酷的服务测试。

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}]');
    }
}

#8


5  

I was looking for a similar problem and found a better approach of doing this. So here it goes.

我正在寻找一个类似的问题,并找到了一个更好的方法。这里。

You can simply put the following line on the redirection page (say page1.php).

您可以简单地在重定向页面(比如page1.php)中添加以下行。

header("Location: URL", TRUE, 307); // Replace URL with to be redirected URL, e.g. final.php

I need this to redirect POST requests for REST API calls. This solution is able to redirect with post data as well as custom header values.

我需要它将POST请求重定向到REST API调用。这个解决方案可以通过post数据和自定义的标题值重定向。

Here is the reference link.

这是参考链接。

#9


4  

There is one more which you can use

还有一个你可以用的。

<?php
$fields = array(
    'name' => 'mike',
    'pass' => 'se_ret'
);
$files = array(
    array(
        'name' => 'uimg',
        'type' => 'image/jpeg',
        'file' => './profile.jpg',
    )
);

$response = http_post_fields("http://www.example.com/", $fields, $files);
?>

Click here for details

请点击这里查看细节

#10


2  

Try PEAR's HTTP_Request2 package to easily send POST requests. Alternatively, you can use PHP's curl functions or use a PHP stream context.

尝试使用PEAR的HTTP_Request2包来轻松发送POST请求。或者,您可以使用PHP的curl函数或使用PHP流上下文。

HTTP_Request2 also makes it possible to mock out the server, so you can unit-test your code easily

HTTP_Request2还可以模拟服务器,这样就可以轻松地对代码进行单元测试。

#11


0  

Another alternative of the curl-less method above is to use the native stream functions:

上面的另一种不受限制的方法是使用本机流函数:

  • stream_context_create():

    Creates and returns a stream context with any options supplied in options preset.

    创建并返回一个流上下文,其中包含选项预置中提供的任何选项。

  • stream_get_contents():

    Identical to file_get_contents(), except that stream_get_contents() operates on an already open stream resource and returns the remaining contents in a string, up to maxlength bytes and starting at the specified offset.

    与file_get_contents()相同,除了stream_get_contents()操作在已经打开的流资源上,并返回字符串中的其余内容,直到maxlength字节,并从指定的偏移量开始。

A POST function with these can simply be like this:

一个具有这些功能的POST函数可以是这样的:

<?php

function post_request($url, array $params) {
  $query_content = http_build_query($params);
  $fp = fopen($url, 'r', FALSE, // do not use_include_path
    stream_context_create([
    'http' => [
      'header'  => [ // header array does not need '\r\n'
        'Content-type: application/x-www-form-urlencoded',
        'Content-Length: ' . strlen($query_content)
      ],
      'method'  => 'POST',
      'content' => $query_content
    ]
  ]));
  if ($fp === FALSE) {
    fclose($fp);
    return json_encode(['error' => 'Failed to get contents...']);
  }
  $result = stream_get_contents($fp); // no maxlength/offset
  fclose($fp);
  return $result;
}

#1


1008  

CURL-less method with PHP5:

PHP5 CURL-less方法:

$url = 'http://server.com/path';
$data = array('key1' => 'value1', 'key2' => 'value2');

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data)
    )
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }

var_dump($result);

See the PHP manual for more information on the method and how to add headers, for example:

有关方法的更多信息,以及如何添加标题,请参阅PHP手册,例如:

#2


62  

I did try this one and it is working fine... as I rquired..

我确实试过了,而且效果很好……当我rquired . .

<?php
$url = $file_name;
$fields = array(
            '__VIEWSTATE'=>urlencode($state),
            '__EVENTVALIDATION'=>urlencode($valid),
            'btnSubmit'=>urlencode('Submit')
        );

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
$fields_string = rtrim($fields_string,'&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);

//execute post
$result = curl_exec($ch);
print $result;
?>

#3


35  

I use the following function to post data using curl. $data is an array of fields to post (will be correctly encoded using http_build_query). The data is encoded using application/x-www-form-urlencoded.

我使用以下函数使用curl来发布数据。$data是一个字段的数组(使用http_build_query正确编码)。数据是使用应用程序/x-www-form-urlencode编码的。

function httpPost($url, $data)
{
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
}

@Edward mentions that http_build_query may be omitted since curl will correctly encode array passed to CURLOPT_POSTFIELDS parameter, but be advised that in this case the data will be encoded using multipart/form-data.

@Edward提到,由于curl将正确编码传递给CURLOPT_POSTFIELDS参数的数组,所以可以省略http_build_query,但是请注意,在这种情况下,数据将使用多部分/表单数据进行编码。

I use this function with APIs that expect data to be encoded using application/x-www-form-urlencoded. That's why I use http_build_query().

我使用这个函数使用应用程序/x-www-form-urlencode对数据进行编码的api。这就是为什么我使用http_build_query()。

#4


31  

I recommend you to use the open-source package guzzle that is fully unit tested and uses the latest coding practices.

我建议您使用完全单元测试的开源软件包guzzle,并使用最新的编码实践。

Installing Guzzle

安装狂饮

Go to the command line in your project folder and type in the following command (assuming you already have the package manager composer installed). If you need help how to install Composer, you should have a look here.

转到项目文件夹中的命令行,并键入下面的命令(假设您已经安装了包管理器composer)。如果您需要帮助如何安装Composer,您应该看一下这里。

php composer.phar require guzzlehttp/guzzle

Using Guzzle to send a POST request

使用Guzzle发送一个POST请求。

The usage of Guzzle is very straight forward as it uses a light-weight object-oriented API:

Guzzle的使用非常直接,因为它使用了轻量级的面向对象API:

// Initialize Guzzle client
$client = new GuzzleHttp\Client();

// Create a POST request
$response = $client->request(
    'POST',
    'http://example.org/',
    [
        'form_params' => [
            'key1' => 'value1',
            'key2' => 'value2'
        ]
    ]
);

// Parse the response object, e.g. read the headers, body, etc.
$headers = $response->getHeaders();
$body = $response->getBody();

// Output headers and body for debugging purposes
var_dump($headers, $body);

#5


18  

There's another CURL method if you are going that way.

如果是这样的话,还有另一个旋度法。

This is pretty straightforward once you get your head around the way the PHP curl extension works, combining various flags with setopt() calls. In this example I've got a variable $xml which holds the XML I have prepared to send - I'm going to post the contents of that to example's test method.

这非常简单,一旦您了解了PHP curl扩展的工作方式,将各种标志与setopt()调用组合在一起。在本例中,我有一个变量$xml,它持有我准备发送的xml——我将把它的内容发布到示例的测试方法中。

$url = 'http://api.example.com/services/xmlrpc/';
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
curl_close($ch);
//process $response

First we initialised the connection, then we set some options using setopt(). These tell PHP that we are making a post request, and that we are sending some data with it, supplying the data. The CURLOPT_RETURNTRANSFER flag tells curl to give us the output as the return value of curl_exec rather than outputting it. Then we make the call and close the connection - the result is in $response.

首先,我们初始化连接,然后使用setopt()设置一些选项。这些告诉PHP我们正在做一个post请求,我们正在发送一些数据,提供数据。CURLOPT_RETURNTRANSFER标志告诉curl将输出作为curl_exec的返回值,而不是输出。然后我们调用并关闭连接——结果是$response。

#6


13  

If you by any chance are using Wordpress to develop your app (it's actually a convenient way to get authorization, info pages etc even for very simple stuff), you can use the following snippet:

如果你有任何机会使用Wordpress开发你的应用程序(这实际上是一种获得授权、信息页面等的便捷方式),你可以使用以下代码片段:

$response = wp_remote_post( $url, array('body' => $parameters));

if ( is_wp_error( $response ) ) {
    // $response->get_error_message()
} else {
    // $response['body']
}

It uses different ways of making the actual HTTP request, depending on what is available on the web server. For more details, see the HTTP API documentation.

它使用不同的方法来生成实际的HTTP请求,这取决于web服务器上可用的内容。有关更多细节,请参见HTTP API文档。

If you don't want to develop a custom theme or plugin to start the Wordpress engine, you can just do the following in an isolated PHP file in the wordpress root:

如果你不想开发一个自定义的主题或插件来启动Wordpress引擎,你可以在Wordpress根的一个单独的PHP文件中做以下操作:

require_once( dirname(__FILE__) . '/wp-load.php' );

// ... your code

It won't show any theme or output any HTML, just hack away with the Wordpress APIs!

它不会显示任何主题,也不会输出任何HTML,只需使用Wordpress api就可以了!

#7


9  

I'd like to add some thoughts about the curl-based answer of Fred Tanrikut. I know most of them are already written in the answers above, but I think it is a good idea to show an answer that includes all of them together.

我想补充一些关于Fred Tanrikut的基于curl的答案的想法。我知道他们中的大多数已经写在上面的答案里了,但是我认为最好能给出一个包含所有答案的答案。

Here is the class I wrote to make HTTP-GET/POST/PUT/DELETE requests based on curl, concerning just about the response body:

这里是我写的类,用来使http get /POST/PUT/DELETE请求基于curl,涉及到响应主体:

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;
    }
}

Improvements

  • Using http_build_query to get the query-string out of an request-array.(you could also use the array itself, therefore see: http://php.net/manual/en/function.curl-setopt.php)
  • 使用http_build_query从请求数组中获取查询字符串。(您也可以使用数组本身,因此参见:http://php.net/manual/en/function.curl-setopt.php)
  • Returning the response instead of echoing it. Btw you can avoid the returning by removing the line curl_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
  • 返回响应,而不是响应它。您可以通过删除行curl_setopt($ch, CURLOPT_RETURNTRANSFER, true)来避免返回。在此之后,返回值是一个布尔值(true = request是成功的,否则会出现错误),响应也会得到响应。参见:http://php.net/en/manual/function.curl-exec.php
  • Clean session closing and deletion of the curl-handler by using curl_close. See: http://php.net/manual/en/function.curl-close.php
  • 使用curl_close来关闭和删除curl处理程序。参见:http://php.net/manual/en/function.curl-close.php
  • Using boolean values for the 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)
  • 使用布尔值的curl_setopt函数而不是使用任何数字。(我知道任何不等于零的数字也被认为是正确的,但是使用true会生成更可读的代码,但这只是我的观点)
  • Ability to make HTTP-PUT/DELETE calls(useful for RESTful service testing)
  • 能够进行HTTP-PUT/DELETE调用(用于RESTful服务测试)

Example of usage

GET

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

POST

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

PUT

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

DELETE

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

Testing

You can also make some cool service tests by using this simple class.

您还可以使用这个简单的类来做一些很酷的服务测试。

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}]');
    }
}

#8


5  

I was looking for a similar problem and found a better approach of doing this. So here it goes.

我正在寻找一个类似的问题,并找到了一个更好的方法。这里。

You can simply put the following line on the redirection page (say page1.php).

您可以简单地在重定向页面(比如page1.php)中添加以下行。

header("Location: URL", TRUE, 307); // Replace URL with to be redirected URL, e.g. final.php

I need this to redirect POST requests for REST API calls. This solution is able to redirect with post data as well as custom header values.

我需要它将POST请求重定向到REST API调用。这个解决方案可以通过post数据和自定义的标题值重定向。

Here is the reference link.

这是参考链接。

#9


4  

There is one more which you can use

还有一个你可以用的。

<?php
$fields = array(
    'name' => 'mike',
    'pass' => 'se_ret'
);
$files = array(
    array(
        'name' => 'uimg',
        'type' => 'image/jpeg',
        'file' => './profile.jpg',
    )
);

$response = http_post_fields("http://www.example.com/", $fields, $files);
?>

Click here for details

请点击这里查看细节

#10


2  

Try PEAR's HTTP_Request2 package to easily send POST requests. Alternatively, you can use PHP's curl functions or use a PHP stream context.

尝试使用PEAR的HTTP_Request2包来轻松发送POST请求。或者,您可以使用PHP的curl函数或使用PHP流上下文。

HTTP_Request2 also makes it possible to mock out the server, so you can unit-test your code easily

HTTP_Request2还可以模拟服务器,这样就可以轻松地对代码进行单元测试。

#11


0  

Another alternative of the curl-less method above is to use the native stream functions:

上面的另一种不受限制的方法是使用本机流函数:

  • stream_context_create():

    Creates and returns a stream context with any options supplied in options preset.

    创建并返回一个流上下文,其中包含选项预置中提供的任何选项。

  • stream_get_contents():

    Identical to file_get_contents(), except that stream_get_contents() operates on an already open stream resource and returns the remaining contents in a string, up to maxlength bytes and starting at the specified offset.

    与file_get_contents()相同,除了stream_get_contents()操作在已经打开的流资源上,并返回字符串中的其余内容,直到maxlength字节,并从指定的偏移量开始。

A POST function with these can simply be like this:

一个具有这些功能的POST函数可以是这样的:

<?php

function post_request($url, array $params) {
  $query_content = http_build_query($params);
  $fp = fopen($url, 'r', FALSE, // do not use_include_path
    stream_context_create([
    'http' => [
      'header'  => [ // header array does not need '\r\n'
        'Content-type: application/x-www-form-urlencoded',
        'Content-Length: ' . strlen($query_content)
      ],
      'method'  => 'POST',
      'content' => $query_content
    ]
  ]));
  if ($fp === FALSE) {
    fclose($fp);
    return json_encode(['error' => 'Failed to get contents...']);
  }
  $result = stream_get_contents($fp); // no maxlength/offset
  fclose($fp);
  return $result;
}