IT TIP

cURL을 사용하여 HTTPS 사이트에 연결할 수 없습니다.

itqueen 2020. 11. 22. 21:00
반응형

cURL을 사용하여 HTTPS 사이트에 연결할 수 없습니다. 대신 길이가 0 인 콘텐츠를 반환합니다. 어떡해?


결제를 위해 cURL (최신 버전)을 사용하여 보안 게이트웨이에 연결하는 사이트가 있습니다.

문제는 cURL이 항상 길이가 0 인 콘텐츠를 반환한다는 것입니다. 헤더 만 가져옵니다. 그리고 헤더를 반환하도록 cURL을 설정할 때만. 다음 플래그가 있습니다.

curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_URL, $gatewayURI);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_POST, 1);

반환 된 헤더는

HTTP/1.1 100 Continue

HTTP/1.1 200 OK
Date: Tue, 25 Nov 2008 01:08:34 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
Content-Length: 0
Content-Type: text/html
Set-Cookie: ASPSESSIONIDxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx; path=/
Cache-control: private

나는 또한 다른 사이트를 컬링하려고 시도했으며 콘텐츠를 정상적으로 반환합니다. 문제가 https 연결과 관련이 있다고 생각합니다.

회사와 이야기를했는데 도움이되지 않습니다.

다른 사람이이 오류를 경험하고 해결 방법을 알고 있습니까? cURL을 버리고 사용해 볼까요 fsockopen()?

감사합니다. :)


curl_error ()에서 오류 메시지도 확인해야합니다. curl_ * 함수마다 한 번씩이 작업을 수행해야 할 수 있습니다.

http://www.php.net/curl_error


나는 오늘도 같은 문제가 있었다. Curl은 HTTPS 인증서를 인증하기위한 오래된 파일과 함께 제공됩니다.

새로운 것을 얻으십시오 :

http://curl.haxx.se/ca/cacert.pem

사이트의 일부 디렉토리에 저장

그리고 추가

curl_setopt ($curl_ch, CURLOPT_CAINFO, dirname(__FILE__)."/cacert.pem"); 

모든 요청에 ​​:-)

CURLOPT_VERIFYPEER 및 CURLOPT_VERIFYHOST 비활성화에 대한 멍청한 의견은 무시하십시오 !! 그러면 코드가 중간자 공격에 취약 해집니다!

2016 년 12 월 편집 :

아래에 언급 된 Jasen의 방법을 사용하여 올바르게 해결하십시오.

curl.cainfo=/etc/ssl/certs/ca-certificates.crt당신에게 php.ini 추가

2017 년 10 월 편집 :

이제 CA 인증서를 관리하는 데 도움이되는 작성기 패키지가 있으므로 인증서 취소로 인해 cacert.pem이 오래 되어도 취약하지 않습니다.

https://github.com/paragonie/certainty- >composer require paragonie/certainty:dev-master


참고 : 이것은 엄격하게 프로덕션 용도가 아닙니다. 빠르게 디버그하려면이 방법이 유용 할 수 있습니다. 그렇지 않으면 위의 @SchizoDuckie의 답변을 사용하십시오.

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);     
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); 

추가하기 만하면됩니다. 효과가있다.


매우 유사한 문제가 발생하여 다음을 추가하여 해결했습니다.

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

분명히 내가 가져 오는 사이트는 다른 위치로 리디렉션되고 php-curl은 기본적으로 리디렉션을 따르지 않습니다.


이것이 도움이 된 상황이있었습니다. (Windows의 PHP 5.4.16)

curl_setopt($ch, CURLOPT_SSLVERSION, 3);

PHP / Curl로 무언가를 테스트 할 때마다 먼저 명령 줄에서 시도하고 작동하는 것을 파악한 다음 내 옵션을 PHP로 이식합니다.


https에 오류가 발생하지 않도록 Curl 인증서를 최신 버전으로 업그레이드해야하는 경우가 있습니다.


나는 사용 file_get_contents하여 stream_create_context잘 작동합니다.

$postdataStr = http_build_query($postdataArr);

$context_options = array (
        'http' => array (    <blink> // this will allways be http!!!</blink>
            'method' => 'POST',
            'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
                . "Content-Length: " . strlen($postdataArr) . "\r\n"
                . "Cookie: " . $cookies."\r\n"
            'content' => $postdataStr
            )
        );

$context = stream_context_create($context_options);
$HTTPSReq = file_get_contents('https://www.example.com/', false, $context);

there might be a problem at your web hosting company from where you are testing the secure communication for gateway, that they might not allow you to do that.

also there might be a username, password that must be provided before connecting to remote host.

or your IP might need to be in the list of approved IP for the remote server for communication to initiate.


I discovered this error on a recent application project. I was writing to run from the command line or the browser window, so I was using server detection to get the relative URL of the document I was asking for. The trouble was, the site is https, and each time I attempted to access http://(same server), cURL helpfully changed it to https.

This works fine from the browser, but from the command-line, I'd then get an SSL error even with both verify's set to false. What I had to do was,

1) Check $_SERVER['HTTP_HOST']. If present, use ($_SERVER['HTTPS'] ? "https://" : "http://").$_SERVER['HTTP_HOST']

2) Check $_SERVER['COMPUTERNAME'], and if it matched the production server, provide the https URL. ("https://(servername)")

3) If neither condition passed, it means I'm running command-line on a different server, and use "http://localhost".

Now, this worked, but it's a hack. Also, I never did figure out why on one server (https) cURL changed my URL, while on the other (also https) it left my URL alone.

Weird.


The best way to use https and avoid security issues is to use Firefox (or another tool) and download the certificate to your server. This webpage helped me a lot, and these were the steps that worked for me:

1) Open in Firefox the URL you're gonna use with CURL

2) On the address bar click on the padlock > more information (FF versions can have different menus, just find it). Click the View certificate button > Details tab.

3) Highlight the "right" certificate in Certificate hierarchy. In my case it was the second of three, called "cPanel, Inc. Certification Authority". I just discovered the right one by "trial and error" method.

4) Click the Export button. In my case the one who worked was the file type "PEM with chains" (again by trial and error method).

5) Then in your PHP script add:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);    
curl_setopt($ch, CURLOPT_CAINFO, [PATH_TO_CRT_FILE]);

In addition I'd say that we must pay attention on the fact that these steps will probably need to be redone once a year or whenever the URL certificate is replaced or renewed.


You are using POST method, but are you providing an array of data? E.g.

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

참고URL : https://stackoverflow.com/questions/316099/cant-connect-to-https-site-using-curl-returns-0-length-content-instead-what-c

반응형