通过PHP发出HTTPS请求并获得响应

时间:2010-10-06 13:54:04

标签: php https request

我想通过PHP向服务器发出HTTPS请求并获得响应。

类似于这个红宝石代码的东西

  http = Net::HTTP.new("www.example.com", 443)

  http.use_ssl = true

  path = "uri"

  resp, data = http.get(path, nil)

由于

4 个答案:

答案 0 :(得分:15)

这可能有用,请试一试。

 $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Get the response and close the channel.
$response = curl_exec($ch);
curl_close($ch);

了解更多信息,请检查 http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/

答案 1 :(得分:2)

Zend Framework有一个名为Zend_Http_Client的好组件,非常适合这种交易。

它使用curl来发出请求,但是你会发现Zend_Http_Client有一个更好的界面可供使用,并且当你想要添加自定义标题或使用响应时更容易配置。

如果您只想以最少的工作量检索页面内容,则可以执行以下操作,具体取决于服务器的配置:

$data = file_get_contents('https://www.example.com/');

答案 2 :(得分:0)

示例如何使用HttpRequest发布数据并接收响应:

<?php
//set up variables
$theData = '<?xml version="1.0"?>
<note>
    <to>my brother</to>
    <from>me</from>
    <heading>hello</heading>
    <body>this is my body</body>
</note>';
$url = 'http://www.example.com';
$credentials = 'user@example.com:password';
$header_array = array('Expect' => '',
                'From' => 'User A');
$ssl_array = array('version' => SSL_VERSION_SSLv3);
$options = array(headers => $header_array,
                httpauth => $credentials,
                httpauthtype => HTTP_AUTH_BASIC,
            protocol => HTTP_VERSION_1_1,
            ssl => $ssl_array);

//create the httprequest object               
$httpRequest_OBJ = new httpRequest($url, HTTP_METH_POST, $options);
//add the content type
$httpRequest_OBJ->setContentType = 'Content-Type: text/xml';
//add the raw post data
$httpRequest_OBJ->setRawPostData ($theData);
//send the http request
$result = $httpRequest_OBJ->send();
//print out the result
echo "<pre>"; print_r($result); echo "</pre>";
?>

答案 3 :(得分:0)

有2个示例GET方法和POST方法

GET示例:

<?php
$r = new HttpRequest('http://example.com/feed.rss', HttpRequest::METH_GET);
$r->setOptions(array('lastmodified' => filemtime('local.rss')));
$r->addQueryData(array('category' => 3));
try {
    $r->send();
    if ($r->getResponseCode() == 200) {
        file_put_contents('local.rss', $r->getResponseBody());
    }
} catch (HttpException $ex) {
    echo $ex;
}
?>

发布示例

<?php
$r = new HttpRequest('http://example.com/form.php', HttpRequest::METH_POST);
$r->setOptions(array('cookies' => array('lang' => 'de')));
$r->addPostFields(array('user' => 'mike', 'pass' => 's3c|r3t'));
$r->addPostFile('image', 'profile.jpg', 'image/jpeg');
try {
    echo $r->send()->getBody();
} catch (HttpException $ex) {
    echo $ex;
}
?>