通过HTTPS而不是HTTP连接

时间:2012-11-28 13:44:24

标签: php http post https protocols

我想使用一个简单的API,我想以安全的方式做到这一点。 它目前正在使用套接字和端口80.据我所知,端口80是打开的,它似乎不是一个安全的连接。

由于要发送的数据包含用户和密码,我想使用HTTPS而不是HTTP来使其安全。

我想知道它是否只是改变这一行是如此简单;

$headers = "POST /api/api.php HTTP/1.0\r\n";

对于这一行

$headers = "POST /api/api.php HTTPS/1.0\r\n";

将端口更改为443

这是连接功能:

// api connect function
function api_connect($Username, $Password, $ParameterArray)
{
   // Create the URL to send the message.
   // The variables are set using the input from an HTML form

   $err = array();
   $url = "api.text-connect.co.uk";
   $headers = "POST /api/api.php HTTP/1.0\r\n";
   $headers .= "Host: ".$url."\r\n";

   // Create post string
   // Username and Password
   $poststring = "Username=".$Username."&";
   $poststring .= "Password=".$Password;

   // Turn the parameter array into the variables

   while (list($Key, $Value)=@each($ParameterArray))
   {
      $poststring .= "&".$Key."=".urlencode($Value);
   }

   // Finish off the headers
   $headers .= "Content-Length: ".strlen($poststring)."\r\n";
   $headers .= "Content-Type: application/x-www-form-urlencoded\r\n";


   // Open a socket
   $http = fsockopen ($url, 80, $err[0], $err[1]);
   if (!$http)
   {
      echo "Connection to ".$url.":80 failed: ".$err[0]." (".$err[1].")";
      exit();
   }

   // Socket was open successfully, post the data.
   fwrite ($http, $headers."\r\n".$poststring."\r\n");

   // Read the results from the post
   $result = "";
   while (!feof($http))
   {
      $result .= fread($http, 8192);
   }

   // Close the connection
   fclose ($http);

   // Strip the headers from the result
   list($resultheaders, $resultcode)=split("\r\n\r\n", $result, 2);

   return $resultcode;
}
?>

3 个答案:

答案 0 :(得分:2)

无论是使用HTTP还是HTTPS,您的代码都存在大量问题 - 实现HTTP客户端(或服务器)比简单地在套接字上抛出一些标头然后沉没响应要复杂得多。

这种方法特别糟糕的是它会在某些时候起作用 - 然后它就会失败,你就会明白为什么。

使用curl重新开始

这样做你只需要更改URL(它还实现了一个cookie jar,支持头注入,自动跟踪重定向,通过代理路由,验证或不验证SSL证书等)。 / p>

答案 1 :(得分:1)

  

我想知道它是否如此简单

不,不是。真的,真的不是。

HTTPS通过SSL进行HTTP隧道传输。因此,您根本不会更改HTTP请求的内容。

您需要在执行HTTP操作之前执行所有SSL握手。

SSL是加密的,因此很难。不要尝试重新发明这个轮子。使用cURL等库。

答案 2 :(得分:1)

curl 并设置CURLOPT_SSL_VERIFYPEER = false

相关问题