Как пользоваться curl php
Once you’ve compiled PHP with cURL support, you can begin using the cURL functions. The basic idea behind the cURL functions is that you initialize a cURL session using the curl_init() , then you can set all your options for the transfer via the curl_setopt() , then you can execute the session with the curl_exec() and then you finish off your session using the curl_close() . Here is an example that uses the cURL functions to fetch the example.com homepage into a file:
Example #1 Using PHP’s cURL module to fetch the example.com homepage
$ch = curl_init ( «http://www.example.com/» );
$fp = fopen ( «example_homepage.txt» , «w» );
curl_setopt ( $ch , CURLOPT_FILE , $fp );
curl_setopt ( $ch , CURLOPT_HEADER , 0 );
curl_exec ( $ch );
if( curl_error ( $ch )) fwrite ( $fp , curl_error ( $ch ));
>
curl_close ( $ch );
fclose ( $fp );
?>
User Contributed Notes 1 note
8 years ago
It is important to notice that when using curl to post form data and you use an array for CURLOPT_POSTFIELDS option, the post will be in multipart format
$params =[ ‘name’ => ‘John’ , ‘surname’ => ‘Doe’ , ‘age’ => 36 ];
$defaults = array(
CURLOPT_URL => ‘http://myremoteservice/’ ,
CURLOPT_POST => true ,
CURLOPT_POSTFIELDS => $params ,
);
$ch = curl_init ();
curl_setopt_array ( $ch , ( $options + $defaults ));
?>
This produce the following post header:
—————————fd1c4191862e3566
Content-Disposition: form-data; name=»name»
Jhon
—————————fd1c4191862e3566
Content-Disposition: form-data; name=»surnname»
Doe
—————————fd1c4191862e3566
Content-Disposition: form-data; name=»age»
Setting CURLOPT_POSTFIELDS as follow produce a standard post header
Which is:
name=John&surname=Doe&age=36
This caused me 2 days of debug while interacting with a java service which was sensible to this difference, while the equivalent one in php got both format without problem.
- Copyright © 2001-2023 The PHP Group
- My PHP.net
- Contact
- Other PHP.net sites
- Privacy policy
Using cURL in PHP to access HTTPS (SSL/TLS) protected sites
From PHP , you can access the useful cURL Library (libcurl) to make requests to URLs using a variety of protocols such as HTTP , FTP, LDAP and even Gopher. (If you’ve spent time on the *nix command line, most environments also have the curl command available that uses the libcurl library)
In practice, however, the most commonly-used protocol tends to be HTTP , especially when using PHP for server-to-server communication. Typically this involves accessing another web server as part of a web service call, using some method such as XML -RPC or REST to query a resource. For example, Delicious offers a HTTP -based API to manipulate and read a user’s posts. However, when trying to access a HTTPS resource (such as the delicious API), there’s a little more configuration you have to do before you can get cURL working right in PHP .
The problem
If you simply try to access a HTTPS (SSL or TLS-protected resource) in PHP using cURL, you’re likely to run into some difficulty. Say you have the following code: (Error handling omitted for brevity)
// Initialize session and set URL. $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);
If $url points toward an HTTPS resource, you’re likely to encounter an error like the one below:
Failed: Error Number: 60. Reason: SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
The problem is that cURL has not been configured to trust the server’s HTTPS certificate. The concepts of certificates and PKI revolves around the trust of Certificate Authorities (CAs), and by default, cURL is setup to not trust any CAs, thus it won’t trust any web server’s certificate. So why don’t you have problems visiting HTTPs sites through your web browser? As it happens, the browser developers were nice enough to include a list of default CAs to trust, covering most situations, so as long as the website operator purchased a certificate from one of these CAs.
The quick fix
There are two ways to solve this problem. Firstly, we can simply configure cURL to accept any server(peer) certificate. This isn’t optimal from a security point of view, but if you’re not passing sensitive information back and forth, this is probably alright. Simply add the following line before calling curl_exec() :
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
This basically causes cURL to blindly accept any server certificate, without doing any verification as to which CA signed it, and whether or not that CA is trusted. If you’re at all concerned about the data you’re passing to or receiving from the server, you’ll want to enable this peer verification properly. Doing so is a bit more complicated.
The proper fix
The proper fix involves setting the CURLOPT_CAINFO parameter. This is used to point towards a CA certificate that cURL should trust. Thus, any server/peer certificates issued by this CA will also be trusted. In order to do this, we first need to get the CA certificate. In this example, I’ll be using the https://api.del.icio.us/ server as a reference.
First, you’ll need to visit the URL with your web browser in order to grab the CA certificate. Then, (in Firefox) open up the security details for the site by double-clicking on the padlock icon in the lower right corner:
Then click on “View Certificate”:
Bring up the “Details” tab of the cerficates page, and select the certificate at the top of the hierarchy. This is the CA certificate.
Then click “Export”, and save the CA certificate to your selected location, making sure to select the X.509 Certificate (PEM) as the save type/format.
Now we need to modify the cURL setup to use this CA certificate, with CURLOPT_CAINFO set to point to where we saved the CA certificate file to.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_CAINFO, getcwd() . "/CAcerts/BuiltinObjectToken-EquifaxSecureCA.crt");
The other option I’ve included, CURLOPT_SSL_VERIFYHOST can be set to the following integer values:
- 0: Don’t check the common name (CN) attribute
- 1: Check that the common name attribute at least exists
- 2: Check that the common name exists and that it matches the host name of the server
If you have CURLOPT_SSL_VERIFYPEER set to false, then from a security perspective, it doesn’t really matter what you’ve set CURLOPT_SSL_VERIFYHOST to, since without peer certificate verification, the server could use any certificate, including a self-signed one that was guaranteed to have a CN that matched the server’s host name. So this setting is really only relevant if you’ve enabled certificate verification.
This ensures that not just any server certificate will be trusted by your cURL session. For example, if an attacker were to somehow redirect traffic from api.delicious.com to their own server, the cURL session here would not properly initialize, since the attacker would not have access to a server certificate (i.e. would not have the private key) trusted by the CA we added. These steps effectively export the trusted CA from the web browser to the cURL configuration.
More information
If you have the CA certificate, but it is not in the PEM format (i.e. it is in a binary or DER format that isn’t Base64-encoded), you’ll need to use something like OpenSSL to convert it to the PEM format. The exact command differs depending on whether you’re converting from PKCS12 or DER format.
There is a CURLOPT_CAPATH option that allows you to specify a directory that holds multiple CA certificates to trust. But it’s not as simple as dumping every single CA certificate in this directory. Instead, they CA certificates must be named properly, and the OpenSSL c_rehash utility can be used to properly setup this directory for use by cURL.
Related Posts
- Decoding Google Maps Encoded Polylines using PHP
- Evaluation of boolean values in JavaScript
- Google App Engine for Java: First thoughts
- Aspect-Oriented Programming
- Using the Basic Constraints extension in X.509 v3 certificates for intermediate CAs
- JavaScript Event Delegation
- Posted at 8:22 pm
- Posted in curl, development, http, PHP, pki, programming, security
- Previous entry: Google App Engine for Java: First thoughts
- Next entry: Open Cygwin Bash Shell Here
200 Comments »
1. Rob said on April 2nd, 2014 at 6:26 am #
I’ve been struggling to use CURL to retrieve data from a particular site. Following the instructions in this article has resolved my issue. Many Thanks for taking the time to right this very clear guide.
2. Felipe Marques said on April 30th, 2014 at 2:44 pm #
Thanks! work for me
3. karthikeyan said on May 30th, 2014 at 4:50 am #
hi,
i did upload videos from viemo. I did set privacy to all videos. i want to get direct link with token from all vimeo videos in particular users. i have tried php language, with out privacy videos get direct link from all, but i have set privacy link can’t get direct link.
4. Hillel said on July 21st, 2014 at 10:10 am #
Thank you very much, this is the best explanation about it. I was looking for this answer over 10 hours.
5. karl said on October 7th, 2014 at 3:49 am #
I fix this problem by update php from 5.3.3-22 to 5.3.3-27.
6. Https access with cURL from localserver | CleanScript said on October 24th, 2014 at 6:21 pm #
[…] Similar Article […]
7. Ms. C said on November 3rd, 2014 at 9:18 pm #
I’m having a problem on connecting to a https site, I followed your post but nothing happens still can’t retrieve response from an API. It says “Failed to connect to **************** port 443: Connection timed “
8. Alberto said on November 11th, 2014 at 3:51 am #
Hi, the step involving setting CURLOPT_CAINFO does not work (at least on PHP 5.4.4, Debian 7): cURL is unable to validate the chain with the ca-certificates.crt (or ca.pem) file. It requires instead setting CURLOPT_CAPATH to /etc/ssl/certs/ and letting it picking the right certificate by itself.
This solves the problem.
9. pborough said on December 18th, 2014 at 11:32 am #
We have a client that has an app pointing to an old 2003 web cluster where https is not forced and their PHP cUrl app is working fine. We point them to the new 2012 web cluster where all calls a forced to https and the call fails with the following:
Notice: SSL certificate problem: unable to get the local issuer certificate in …….
We implemented the quick fix performed an IIS reset and still see the same issue. Any ideas? I do not have any PHP resources to help me at this time.
10. Cristian Caballero said on January 10th, 2015 at 10:21 am #
Thanks , was the solution to my problem.
11. lingtalfi said on March 11th, 2015 at 12:40 am #
12. Borislav said on March 18th, 2015 at 2:16 pm #
Listen to this guy. THANK YOU “I think, the really really nessecary thing is the Post in comment number 4. You have to choose export option: X.509 Certificate with chain (PEM)”
cURL PHP: что это такое и как им пользоваться?

В этой записи, я покажу на примерах как пользоваться cURL, где его применяют и почему вам стоит в нём разобраться, если вы еще этого не сделали.
Где используют cURL PHP? Его можно применять для работы с API других сайтов, выполнять простые HTTP запросы и более сложные, например загрузок файлов с FTP.
Мы в этой записи, посмотрим на простые GET / POST запросы и как их делать с помощь.
Важно знать
Настройка запроса
- CURLOPT_RETURNTRANSFER — вернуть ответ в виде строки, вместо того, чтобы показывать его сразу
- CURLOPT_CONNECTTIMEOUT — сколько по времени ждать ответа
- CURLOPT_TIMEOUT — сколько секунд будет выполняться cURL запрос
- CURLOPT_USERAGENT — headers (заголовки) для запроса
- CURLOPT_URL — URL куда будет отправлен запрос
- CURLOPT_POST — отправить POST запрос
- CURLOPT_POSTFIELDS — массив POST полей к запросу
Настройки выше используются для изменения параметров отправки запроса. Когда вы не задали никаких параметров для cURL, то у него «появляется куча вопросов». Например: какой запрос вы хотите выполнить ( GET / POST )? Сколько времени выделить на запрос? Куда он должен выполнять и другие подобные.
Другие используемые функции
- curl_init() — открывает сеанс cURL
- curl_close() — закрывает сеанс cURL
- curl_exec() — выполняет запрос
Функции выше используются для создания запроса, его запуска и закрытия.
PHP cURL GET
Для начала сделаем GET запрос.
// Для начала скажем, что мы хотим использовать cURL $curl = curl_init(); // Определение параметров. Ссылку (куда будет делаться запрос) и headers (заголовки) curl_setopt_array($curl, [ CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => 'http://domain.ru/?param=one¶m2=two', CURLOPT_USERAGENT => 'Sample of cURL' ]); // Отправляем запрос и сохраняем ответ в $res $res = curl_exec($curl); // Закрываем запрос и удаляем инициализацию $curl curl_close($curl);
В этом запросе мы создаем cURL, и указываем, что нужно вернут ответ со страницы в виде строки CURLOPT_RETURNTRANSFER (не выводя его на экран), указываем ссылку запроса CURLOPT_URL (куда он будет выполнен) и указываем USERAGENT заголовки (не обязательный параметр и его можно удалить). Далее отправляем запрос и получаем ответ. Закрываем cURL и вуаля — у вас теперь есть ответ в $res , который вы теперь можете вывести на экран с помощью echo $var или var_dump($res) .
PHP cURL POST
Разница между GET и POST запросами — это синтаксиc для отправки. Для POST можно указать больше параметров, например, поля, которые будут отправляться. Допустим, вы хотите отправить форму на сайте куда делаете запрос, тогда в данном случае вам точно понадобиться POST .
// Для начала скажем, что мы хотим использовать cURL $curl = curl_init(); // Определение прааметров. Ссылку (куда будет делаться запрос), какие заголовки будут у этого запроса, задаем, что запрос должен быть в формате POST и передаем параметры этого запроса в виде массива 'ключ' => 'значение'. curl_setopt_array($curl, [ CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => 'http://testcURL.com', CURLOPT_USERAGENT => 'Codular Sample cURL Request', CURLOPT_POST => 1, CURLOPT_POSTFIELDS => [ 'param1' => 'значение1', 'param2' => 'значение2' ] ]); // Отправляем запроса и сохраняем его в $res $res = curl_exec($curl); // Закрываем запрос и удаляем инициализацию $curl curl_close($curl);
Процедура отправки этого запроса почти идентична тому, что было в GET за исключением двух дополнительных строчек. С помощью CURLOPT_POST мы говорим cURL о том, что хотим отправить POST запрос и затем прописываем параметры для отправки с CURLOPT_POSTFIELDS в виде массива (сначала имя параметра и затем его значение).
В случае, если вы хотите зарегистрироваться на сайте куда вы отправляете запрос и на нем из полей только три, допустим: first_name (имя), last_name (фамилия), email (почта), тогда поля у вас будут выглядеть следующим образом:
CURLOPT_POSTFIELDS => [ 'first_name' => 'Bologer', 'last_name' => 'Test', 'email' => 'admin@bologer.ru' ]
Обратите внимание на то, что если на форме будет стоять капча (проверка на ботов), тогда зарегистрироваться автоматически не получится.
Похожие функции
Для отправки GET запросов так же подойдет file_get_contents() который делает запрос и возвращает то, что удалось получить.
Чем он плох?
- На некоторых сайтах он заблокирован
- Некоторые хостинги по умолчанию блокируют эту функцию, поэтому вам придется просить у них включить ее в общий список модулей
- Мало настроек для отправки запросов
Чем он хорош?
- Проще чем cURL. Удобно пользоваться, например: file_get_contents(‘http://google.com’)
Альтернативно вы можете воспользоваться функцией copy() , но опять же она не везде доступна.
copy('http://example.com/archive.tar.gz', '/tmp/arhive.tar.gz');
Библиотеки

Чтобы не создавать новый велосипед, лучше всего воспользоваться готовым решением в виде Guzzle.
Я вкратце опишу что это и с чем его едят:
Guzzle был создан для того, чтобы упростить процесс отправки HTTP запросов. Зачастую используется для отправки запросов к API и чему угодно в целом.
У вас есть API, которое вы недавно разработали и пришло время начать с ним работать. Вы могли бы написать свою библиотеку или даже мини класс для работы с ним, но (1) у вас ушло бы не мало времени, а если бы и мало, то вероятнее всего решение получилось бы не самое лучшее, (2) его нужно постоянно поддерживать и улучшать. В таком случае, лучше использовать готовое решение, которое поддерживается большим сообществом и Guzzle репозитория уже насчитывает 12 тыс. звезд, что очень похвально.
Вы можете спросить: Зачем это нужно, если уже существует куча библиотек?
Guzzle собрал все самое лучшее в себе, сделать это еще лучше и теперь это самая популярная PHP библиотека для работы с HTTP запросами. Она и вправду крутая, посмотрите только на простоту запроса:
// Создается клиент с базовой URI $client = new GuzzleHttp\Client(['base_uri' => 'http://bologer.ru/']); // Теперь вы можете отправить запрос на http://bologe.ru/about-blog, информацю о моем блоге :) $response = $client->request('GET', 'about-blog'); // Также можно отправить на http://bologer.ru/about, чтобы прочитать обо мне. Guzzle запоминает базовую ссылку и теперь вы можете указывать лишь последующие страницы для удобства $response = $client->request('GET', 'about');
Круто? Мне очень нравится.
Документация у Guzzle достаточно обширная, каждый вариант не распишешь, да и нужно для этого целый пост, который я в скором времени обязательно напишу 🙂
Послесловие
Если у вас остались какие-либо вопросы пишите их ниже к этому посту и я буду рад вам помочь. Так же, если у вас есть какие-то поправки по статье и вы увидели где-то ошибку или хотите добавить что-то буду рад вас выслушать.
Client URL Library
I wrote the following to see if a submitted URL has a valid http response code and also if it responds quickly.
Use the code like this:
$is_ok = http_response ( $url ); // returns true only if http response code < 400
?>
The second argument is optional, and it allows you to check for a specific response code
http_response ( $url , ‘400’ ); // returns true if http status is 400
?>
The third allows you to specify how long you are willing to wait for a response.
http_response ( $url , ‘200’ , 3 ); // returns true if the response takes less than 3 seconds and the response code is 200
?>
function http_response ( $url , $status = null , $wait = 3 )
<
$time = microtime ( true );
$expire = $time + $wait ;
// we fork the process so we don’t have to wait for a timeout
$pid = pcntl_fork ();
if ( $pid == — 1 ) <
die( ‘could not fork’ );
> else if ( $pid ) <
// we are the parent
$ch = curl_init ();
curl_setopt ( $ch , CURLOPT_URL , $url );
curl_setopt ( $ch , CURLOPT_HEADER , TRUE );
curl_setopt ( $ch , CURLOPT_NOBODY , TRUE ); // remove body
curl_setopt ( $ch , CURLOPT_RETURNTRANSFER , TRUE );
$head = curl_exec ( $ch );
$httpCode = curl_getinfo ( $ch , CURLINFO_HTTP_CODE );
curl_close ( $ch );
if( $status === null )
<
if( $httpCode < 400 )
<
return TRUE ;
>
else
<
return FALSE ;
>
>
elseif( $status == $httpCode )
<
return TRUE ;
>
return FALSE ;
pcntl_wait ( $status ); //Protect against Zombie children
> else <
// we are the child
while( microtime ( true ) < $expire )
<
sleep ( 0.5 );
>
return FALSE ;
>
>
?>
Hope this example helps. It is not 100% tested, so any feedback [sent directly to me by email] is appreciated.
13 years ago
I needed to use cURL in a php script to download data using not only SSL for the server authentication but also for client authentication.
On a default install of Fedora, setting up the proper cURL parameters, I would get an error:
$ php curl.php
Peer certificate cannot be authenticated with known CA certificates
The data on http://curl.haxx.se/docs/sslcerts.html was most useful. Indeed, toward to bottom it tells you to add a missing link inside /etc/pki/nssdb to use the ca-bundle.crt file. You do it so:
# cd /etc/pki/nssdb
# ln -s /usr/lib64/libnssckbi.so libnssckbi.so
Now you can do client authentication, provided you have your certificate handy with:
$data = «
$tuCurl = curl_init ();
curl_setopt ( $tuCurl , CURLOPT_URL , «https://example.com/path/for/soap/url/» );
curl_setopt ( $tuCurl , CURLOPT_PORT , 443 );
curl_setopt ( $tuCurl , CURLOPT_VERBOSE , 0 );
curl_setopt ( $tuCurl , CURLOPT_HEADER , 0 );
curl_setopt ( $tuCurl , CURLOPT_SSLVERSION , 3 );
curl_setopt ( $tuCurl , CURLOPT_SSLCERT , getcwd () . «/client.pem» );
curl_setopt ( $tuCurl , CURLOPT_SSLKEY , getcwd () . «/keyout.pem» );
curl_setopt ( $tuCurl , CURLOPT_CAINFO , getcwd () . «/ca.pem» );
curl_setopt ( $tuCurl , CURLOPT_POST , 1 );
curl_setopt ( $tuCurl , CURLOPT_SSL_VERIFYPEER , 1 );
curl_setopt ( $tuCurl , CURLOPT_RETURNTRANSFER , 1 );
curl_setopt ( $tuCurl , CURLOPT_POSTFIELDS , $data );
curl_setopt ( $tuCurl , CURLOPT_HTTPHEADER , array( «Content-Type: text/xml» , «SOAPAction: \»/soap/action/query\»» , «Content-length: » . strlen ( $data )));
$tuData = curl_exec ( $tuCurl );
if(! curl_errno ( $tuCurl )) <
$info = curl_getinfo ( $tuCurl );
echo ‘Took ‘ . $info [ ‘total_time’ ] . ‘ seconds to send a request to ‘ . $info [ ‘url’ ];
> else <
echo ‘Curl error: ‘ . curl_error ( $tuCurl );
>
curl_close ( $tuCurl );
echo $tuData ;
?>
7 years ago
In this example: http://php.net/manual/en/book.curl.php#102885 by «frank at interactinet dot com»
There’s a small bug in
elseif( $status == $httpCode )
<
return TRUE ;
>
return FALSE ;
pcntl_wait ( $status ); //Protect against Zombie children
> else <
// we are the child
while( microtime ( true ) < $expire )
?>
The code will immediately leave the function at the `return`, and pcntl_wait() will NEVER be executed, under any circumstances.
I can’t see any other issues with this function however.
14 years ago
Hey I modified script for php 5. Also I add support server auth. and fixed some little bugs on the script.
[EDIT BY danbrown AT php DOT net: Original was written by (unlcuky13 AT gmail DOT com) on 19-APR-09. The following note was included:
Below is the my way of using through PHP 5 objecte oriented encapsulation to make thing easier.]
class mycurl <
protected $_useragent = ‘Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1’ ;
protected $_url ;
protected $_followlocation ;
protected $_timeout ;
protected $_maxRedirects ;
protected $_cookieFileLocation = ‘./cookie.txt’ ;
protected $_post ;
protected $_postFields ;
protected $_referer = «http://www.google.com» ;
protected $_session ;
protected $_webpage ;
protected $_includeHeader ;
protected $_noBody ;
protected $_status ;
protected $_binaryTransfer ;
public $authentication = 0 ;
public $auth_name = » ;
public $auth_pass = » ;
public function useAuth ( $use ) <
$this -> authentication = 0 ;
if( $use == true ) $this -> authentication = 1 ;
>
public function setName ( $name ) <
$this -> auth_name = $name ;
>
public function setPass ( $pass ) <
$this -> auth_pass = $pass ;
>
public function __construct ( $url , $followlocation = true , $timeOut = 30 , $maxRedirecs = 4 , $binaryTransfer = false , $includeHeader = false , $noBody = false )
<
$this -> _url = $url ;
$this -> _followlocation = $followlocation ;
$this -> _timeout = $timeOut ;
$this -> _maxRedirects = $maxRedirecs ;
$this -> _noBody = $noBody ;
$this -> _includeHeader = $includeHeader ;
$this -> _binaryTransfer = $binaryTransfer ;
$this -> _cookieFileLocation = dirname ( __FILE__ ). ‘/cookie.txt’ ;
public function setReferer ( $referer ) <
$this -> _referer = $referer ;
>
public function setCookiFileLocation ( $path )
<
$this -> _cookieFileLocation = $path ;
>
public function setPost ( $postFields )
<
$this -> _post = true ;
$this -> _postFields = $postFields ;
>
public function setUserAgent ( $userAgent )
<
$this -> _useragent = $userAgent ;
>
public function createCurl ( $url = ‘nul’ )
<
if( $url != ‘nul’ ) <
$this -> _url = $url ;
>
curl_setopt ( $s , CURLOPT_URL , $this -> _url );
curl_setopt ( $s , CURLOPT_HTTPHEADER ,array( ‘Expect:’ ));
curl_setopt ( $s , CURLOPT_TIMEOUT , $this -> _timeout );
curl_setopt ( $s , CURLOPT_MAXREDIRS , $this -> _maxRedirects );
curl_setopt ( $s , CURLOPT_RETURNTRANSFER , true );
curl_setopt ( $s , CURLOPT_FOLLOWLOCATION , $this -> _followlocation );
curl_setopt ( $s , CURLOPT_COOKIEJAR , $this -> _cookieFileLocation );
curl_setopt ( $s , CURLOPT_COOKIEFILE , $this -> _cookieFileLocation );
if( $this -> authentication == 1 ) <
curl_setopt ( $s , CURLOPT_USERPWD , $this -> auth_name . ‘:’ . $this -> auth_pass );
>
if( $this -> _post )
<
curl_setopt ( $s , CURLOPT_POST , true );
curl_setopt ( $s , CURLOPT_POSTFIELDS , $this -> _postFields );
if( $this -> _includeHeader )
<
curl_setopt ( $s , CURLOPT_HEADER , true );
>
if( $this -> _noBody )
<
curl_setopt ( $s , CURLOPT_NOBODY , true );
>
/*
if($this->_binary)
<
curl_setopt($s,CURLOPT_BINARYTRANSFER,true);
>
*/
curl_setopt ( $s , CURLOPT_USERAGENT , $this -> _useragent );
curl_setopt ( $s , CURLOPT_REFERER , $this -> _referer );
$this -> _webpage = curl_exec ( $s );
$this -> _status = curl_getinfo ( $s , CURLINFO_HTTP_CODE );
curl_close ( $s );
public function getHttpStatus ()
<
return $this -> _status ;
>
public function __tostring () <
return $this -> _webpage ;
>
>
?>
[EDIT BY danbrown AT php DOT net: Contains a bugfix supplied by «roetsch.beni at googlemail (dot) com» on 02-AUG-09, with the following note: «Fixes the bugfix: 417 bug at lighthttp server.»]
13 years ago
CURL failed with PHP5.3 and Apache2.2.X on my Windows 7 machine.
It turns out that it’s not enough to copy the two dll’s mentioned (libeay32 and sslea32) from the php folder into your system32 folder. You HAVE TO UNBLOCK THESE TWO FILES.
Right click the file, select unblock, for each one. Then restart Apache.
Another very handy security feature added into Windows.
2 years ago
Sharing is caring, handles included.
$url_one = «php.net» ;
$url_two = «» ;
$user_agent = ‘Mozilla HotFox 1.0’ ;
$ch = curl_init ();
curl_setopt ( $ch , CURLOPT_URL , $url_one . $url_two );
curl_setopt ( $ch , CURLOPT_USERAGENT , $user_agent );
curl_setopt ( $ch , CURLOPT_RETURNTRANSFER , true );
curl_setopt ( $ch , CURLOPT_FOLLOWLOCATION , 1 );
curl_setopt ( $ch , CURLOPT_HEADER , 0 );
curl_setopt ( $ch , CURLOPT_NOBODY , 0 );
curl_setopt ( $ch , CURLOPT_TIMEOUT , 30 );
$res = curl_exec ( $ch );
curl_close ( $ch );
$url_two = «lazyphp.net» ;
$url_one = «» ;
$res_two = curl_exec ( $ch );
curl_close ( $ch );
3 months ago
мега тор — mega зеркало рабочее, mega gl
9 years ago
Here you have a function that I use to get the content of a URL using cURL:
function getUrlContent($url) $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, ‘Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)’);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
$data = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return ($httpcode>=200 && $httpcode<300) ? $data : false;
>
The source comes from this website:
4 years ago
Please note that new versions of curl is using http2 as default, so if you are having some strange errors, 0 http status codes, etc, please explicitly specify the http version in your code.
5 years ago
FYI cURL support (default enabled, ok) is prerequisite for Installation and Configuration of the Collection Extension of wiki portal. https://pickbestscope.com/
15 years ago
You can use this class for fast entry
class cURL <
var $headers ;
var $user_agent ;
var $compression ;
var $cookie_file ;
var $proxy ;
function cURL ( $cookies = TRUE , $cookie = ‘cookies.txt’ , $compression = ‘gzip’ , $proxy = » ) <
$this -> headers [] = ‘Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg’ ;
$this -> headers [] = ‘Connection: Keep-Alive’ ;
$this -> headers [] = ‘Content-type: application/x-www-form-urlencoded;charset=UTF-8’ ;
$this -> user_agent = ‘Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0)’ ;
$this -> compression = $compression ;
$this -> proxy = $proxy ;
$this -> cookies = $cookies ;
if ( $this -> cookies == TRUE ) $this -> cookie ( $cookie );
>
function cookie ( $cookie_file ) <
if ( file_exists ( $cookie_file )) <
$this -> cookie_file = $cookie_file ;
> else <
fopen ( $cookie_file , ‘w’ ) or $this -> error ( ‘The cookie file could not be opened. Make sure this directory has the correct permissions’ );
$this -> cookie_file = $cookie_file ;
fclose ( $this -> cookie_file );
>
>
function get ( $url ) <
$process = curl_init ( $url );
curl_setopt ( $process , CURLOPT_HTTPHEADER , $this -> headers );
curl_setopt ( $process , CURLOPT_HEADER , 0 );
curl_setopt ( $process , CURLOPT_USERAGENT , $this -> user_agent );
if ( $this -> cookies == TRUE ) curl_setopt ( $process , CURLOPT_COOKIEFILE , $this -> cookie_file );
if ( $this -> cookies == TRUE ) curl_setopt ( $process , CURLOPT_COOKIEJAR , $this -> cookie_file );
curl_setopt ( $process , CURLOPT_ENCODING , $this -> compression );
curl_setopt ( $process , CURLOPT_TIMEOUT , 30 );
if ( $this -> proxy ) curl_setopt ( $process , CURLOPT_PROXY , $this -> proxy );
curl_setopt ( $process , CURLOPT_RETURNTRANSFER , 1 );
curl_setopt ( $process , CURLOPT_FOLLOWLOCATION , 1 );
$return = curl_exec ( $process );
curl_close ( $process );
return $return ;
>
function post ( $url , $data ) <
$process = curl_init ( $url );
curl_setopt ( $process , CURLOPT_HTTPHEADER , $this -> headers );
curl_setopt ( $process , CURLOPT_HEADER , 1 );
curl_setopt ( $process , CURLOPT_USERAGENT , $this -> user_agent );
if ( $this -> cookies == TRUE ) curl_setopt ( $process , CURLOPT_COOKIEFILE , $this -> cookie_file );
if ( $this -> cookies == TRUE ) curl_setopt ( $process , CURLOPT_COOKIEJAR , $this -> cookie_file );
curl_setopt ( $process , CURLOPT_ENCODING , $this -> compression );
curl_setopt ( $process , CURLOPT_TIMEOUT , 30 );
if ( $this -> proxy ) curl_setopt ( $process , CURLOPT_PROXY , $this -> proxy );
curl_setopt ( $process , CURLOPT_POSTFIELDS , $data );
curl_setopt ( $process , CURLOPT_RETURNTRANSFER , 1 );
curl_setopt ( $process , CURLOPT_FOLLOWLOCATION , 1 );
curl_setopt ( $process , CURLOPT_POST , 1 );
$return = curl_exec ( $process );
curl_close ( $process );
return $return ;
>
function error ( $error ) <
echo «
$error
die;
>
>
$cc = new cURL ();
$cc -> get ( ‘http://www.example.com’ );
$cc -> post ( ‘http://www.example.com’ , ‘foo=bar’ );
?>
[EDIT BY danbrown AT php DOT net: Includes a bugfix provided by «Anonymous» on 01-Dec-2008 @ 06:52. Also replaced real URL with example.com as per RFC 2606.]
[EDIT BY danbrown AT php DOT net: Includes a bugfix provided by (manuel AT rankone DOT ch) on 24-NOV-09 to properly reference cURL initialization.]
9 years ago
After a lot of frustration with the fact that nobody has documented which curl commandline options go with which library functions, I discovered that the curl commandline will tell you (in the form of a C program) if you add `—libcurl foo.c`
If you’ve been struggling with trying to figure out how to get your fancy curl commandline to work in PHP, this makes it a breeze!
15 years ago
In order to use curl with secure sites you will need a ca-bundle.crt file; here’s a PHP script I’ve written which creates a fresh ca-bundle:
http://www.gknw.net/php/phpscripts/mk-ca-bundle.php
I’ve also written scripts in other languages, f.e. the Perl one which ships now with curl distributions:
http://curl.haxx.se/lxr/source/lib/mk-ca-bundle.pl
and also a Win32 WSH script if you prefer that:
http://www.gknw.net/vb/scripts/mk-ca-bundle.vbs
12 years ago
This anomali only happen on windows.
Server indicates that some variables built by http_build_query() is missing.
//.
//.
//.
$ping_url = $this -> sx_url . ‘ping.php?’ . http_build_query ( $options );
$message = $this -> _post_curl ( $ping_url );
?>
After debugging i found that $ping_url contain url like :
But myserver give «No ttd GET variable» response
This problem fixed by adding optional parameter to make sure that http_build_query() use only ‘&’ as arg separator rather than ‘&’
//.
//.
//.
$ping_url = $this -> sx_url . ‘ping.php?’ . http_build_query ( $options , » , ‘&’ );
$message = $this -> _post_curl ( $ping_url );
?>
13 years ago
A solution that addresses repeat calls to the same set of urls using the same connection simulating frequent ajax calls in separate browser tabs.
In a unique situation you may need to set a cookie then use that cookie for multiple separate persistent connections using the same session cookie. The problem is the session cookie may change while your doing your persistent calls. If you set every curl handle to update a shared cookiejar on close you may overwrite the new found session value with the old session value depending on the closing order of your handles. Also, because the cookiejar is only written to on a curl_close, you may be using dissimilar or old session info in some of your ‘faked browser tabs’.
To solve this problem I created a unique handle that opens and closes specifically to set a cookie file using CURLOPT_COOKIEJAR. Then I just use the read-only CURLOPT_COOKIEFILE on the multiple separate persistent handles.
This solves the problem of shared cookies fighting to write their values and keep persistent calls using the most up to date cookie information.
Note: In my case the multiple calls were in a while loop and I was using php in shell. The session cookie value plus browser type limited the number of connections available and i wanted to use the max connections per session.
6 years ago
/**
* Curl send get request, support HTTPS protocol
* @param string $url The request url
* @param string $refer The request refer
* @param int $timeout The timeout seconds
* @return mixed
*/
function getRequest ( $url , $refer = «» , $timeout = 10 )
$ssl = stripos ( $url , ‘https://’ ) === 0 ? true : false ;
$curlObj = curl_init ();
$options = [
CURLOPT_URL => $url ,
CURLOPT_RETURNTRANSFER => 1 ,
CURLOPT_FOLLOWLOCATION => 1 ,
CURLOPT_AUTOREFERER => 1 ,
CURLOPT_USERAGENT => ‘Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)’ ,
CURLOPT_TIMEOUT => $timeout ,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_0 ,
CURLOPT_HTTPHEADER => [ ‘Expect:’ ],
CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4 ,
];
if ( $refer ) $options [ CURLOPT_REFERER ] = $refer ;
>
if ( $ssl ) //support https
$options [ CURLOPT_SSL_VERIFYHOST ] = false ;
$options [ CURLOPT_SSL_VERIFYPEER ] = false ;
>
curl_setopt_array ( $curlObj , $options );
$returnData = curl_exec ( $curlObj );
if ( curl_errno ( $curlObj )) //error message
$returnData = curl_error ( $curlObj );
>
curl_close ( $curlObj );
return $returnData ;
>
?php
/**
* Curl send post request, support HTTPS protocol
* @param string $url The request url
* @param array $data The post data
* @param string $refer The request refer
* @param int $timeout The timeout seconds
* @param array $header The other request header
* @return mixed
*/
function postRequest ( $url , $data , $refer = «» , $timeout = 10 , $header = [])
$curlObj = curl_init ();
$ssl = stripos ( $url , ‘https://’ ) === 0 ? true : false ;
$options = [
CURLOPT_URL => $url ,
CURLOPT_RETURNTRANSFER => 1 ,
CURLOPT_POST => 1 ,
CURLOPT_POSTFIELDS => $data ,
CURLOPT_FOLLOWLOCATION => 1 ,
CURLOPT_AUTOREFERER => 1 ,
CURLOPT_USERAGENT => ‘Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)’ ,
CURLOPT_TIMEOUT => $timeout ,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_0 ,
CURLOPT_HTTPHEADER => [ ‘Expect:’ ],
CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4 ,
CURLOPT_REFERER => $refer
];
if (!empty( $header )) $options [ CURLOPT_HTTPHEADER ] = $header ;
>
if ( $refer ) $options [ CURLOPT_REFERER ] = $refer ;
>
if ( $ssl ) //support https
$options [ CURLOPT_SSL_VERIFYHOST ] = false ;
$options [ CURLOPT_SSL_VERIFYPEER ] = false ;
>
curl_setopt_array ( $curlObj , $options );
$returnData = curl_exec ( $curlObj );
if ( curl_errno ( $curlObj )) //error message
$returnData = curl_error ( $curlObj );
>
curl_close ( $curlObj );
return $returnData ;
>
$getRes = getRequest ( «https://secure.php.net/» );
echo $getRes ; //Get index page html of php.net
8 years ago
/*
Example values
url — ‘http://example.com’
fields — array(‘var’ => ‘value’), or can be empty
auth — ‘user:password’, or can be empty
by romet, 4.20.2015
*/
function curl($url, $fields = array(), $auth = false)
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_USERAGENT, «Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1»);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_HEADER, 1);
if($auth) curl_setopt($curl, CURLOPT_USERPWD, «$auth»);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
>
if($fields) <
$fields_string = http_build_query($fields);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $fields_string);
>
$response = curl_exec($curl);
$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$header_string = substr($response, 0, $header_size);
$body = substr($response, $header_size);
$header_rows = explode(PHP_EOL, $header_string);
$header_rows = array_filter($header_rows, trim);
foreach((array)$header_rows as $hr) $colonpos = strpos($hr, ‘:’);
$key = $colonpos !== false ? substr($hr, 0, $colonpos) : (int)$i++;
$headers[$key] = $colonpos !== false ? trim(substr($hr, $colonpos+1)) : $hr;
>
foreach((array)$headers as $key => $val) $vals = explode(‘;’, $val);
if(count($vals) >= 2) unset($headers[$key]);
foreach($vals as $vk => $vv) $equalpos = strpos($vv, ‘=’);
$vkey = $equalpos !== false ? trim(substr($vv, 0, $equalpos)) : (int)$j++;
$headers[$key][$vkey] = $equalpos !== false ? trim(substr($vv, $equalpos+1)) : $vv;
>
>
>
//print_rr($headers);
curl_close($curl);
return array($body, $headers);
>
list($d[‘body’], $d[‘headers’]) = curl2(‘http://google.com’, array(q => ‘123’));
//POST to google.com with POST var «q» as «123»
echo »;
print_r($d);
Array
(
[headers] => Array
(
[0] => HTTP/1.1 405 Method Not Allowed
[Allow] => GET, HEAD
[Date] => Mon, 20 Apr 2015 22:20:10 GMT
[Server] => gws
[Content-Length] => 1453
[X-Frame-Options] => SAMEORIGIN
[Alternate-Protocol] => 80:quic,p=1
[Content-Type] => Array
(
[0] => text/html
[charset] => UTF-8
)
[X-XSS-Protection] => Array
(
[1] => 1
[mode] => block
)
