- How to set the authorization header using cURL
- Примеры использования cURL в PHP
- GET запрос
- GET-запрос с параметрами
- POST запрос
- Отправка JSON через POST-запрос
- PUT запрос
- DELETE запрос
- Запрос через proxy
- Отправка файлов на другой сервер
- До PHP 5.5
- Скачивание файлов
- Отправить и получить cookie
- Имитация браузера
- HTTP авторизация
- Basic Authorization
- OAuth авторизация
- Получить HTTP код ответа сервера
- Если CURL возвращает false
- Sending auth in headers php curl
- 4 Answers 4
How to set the authorization header using cURL
HTTP Authentication is the ability to tell the server your username and password so that it can verify that you’re allowed to do the request you’re doing. The Basic authentication used in HTTP (which is the type curl uses by default) is plain text based, which means it sends username and password only slightly obfuscated, but still fully readable by anyone that sniffs on the network between you and the remote server.
To tell curl to use a user and password for authentication:
curl --user name:password http://www.example.com
The site might require a different authentication method (check the headers returned by the server), and then —ntlm, —digest, —negotiate or even —anyauth might be options that suit you.
Sometimes your HTTP access is only available through the use of a HTTP proxy. This seems to be especially common at various companies. A HTTP proxy may require its own user and password to allow the client to get through to the Internet. To specify those with curl, run something like:
curl --proxy-user proxyuser:proxypassword curl.haxx.se
If your proxy requires the authentication to be done using the NTLM method, use —proxy-ntlm, if it requires Digest use —proxy-digest.
If you use any one these user+password options but leave out the password part, curl will prompt for the password interactively.
Do note that when a program is run, its parameters might be possible to see when listing the running processes of the system. Thus, other users may be able to watch your passwords if you pass them as plain command line options. There are ways to circumvent this.
It is worth noting that while this is how HTTP Authentication works, very many web sites will not use this concept when they provide logins etc. See the Web Login chapter further below for more details on that.
Примеры использования cURL в PHP
cURL PHP – это библиотека предназначенная для получения и передачи данных через такие протоколы, как HTTP, FTP, HTTPS. Библиотека используется для получения данных в виде XML, JSON и непосредственно в HTML, парсинга, загрузки и передачи файлов и т.д.
GET запрос
$ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $html = curl_exec($ch); curl_close($ch); echo $html;
GET-запрос с параметрами
$get = array( 'name' => 'Alex', 'email' => 'mail@example.com' ); $ch = curl_init('https://example.com?' . http_build_query($get)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $html = curl_exec($ch); curl_close($ch); echo $html;
POST запрос
$array = array( 'login' => 'admin', 'password' => '1234' ); $ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($array, '', '&')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $html = curl_exec($ch); curl_close($ch); echo $html;
Отправка JSON через POST-запрос
$data = array( 'name' => 'Маффин', 'price' => 100.0 ); $ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $res = curl_exec($ch); curl_close($ch); $res = json_encode($res, JSON_UNESCAPED_UNICODE); print_r($res);
PUT запрос
HTTP-метод PUT используется в REST API для обновления данных.
$data = array( 'name' => 'Маффин', 'price' => 100.0 ); $ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($array, '', '&')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $html = curl_exec($ch); curl_close($ch); echo $html;
DELETE запрос
HTTP-метод DELETE используется в REST API для удаления объектов.
$ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); curl_exec($ch); curl_close($ch);
Запрос через proxy
$proxy = '165.22.115.179:8080'; $ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_TIMEOUT, 400); curl_setopt($ch, CURLOPT_PROXY, $proxy); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $html = curl_exec($ch); curl_close($ch);
Отправка файлов на другой сервер
Отправка файлов осуществляется методом POST :
До PHP 5.5
$ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, array('photo' => '@' . __DIR__ . '/image.png'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $html = curl_exec($ch); curl_close($ch);
С PHP 5.5 следует применять CURLFile.
$curl_file = curl_file_create(__DIR__ . '/image.png', 'image/png' , 'image.png'); $ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, array('photo' => $curl_file)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $res = curl_exec($ch); curl_close($ch);
Также через curl можно отправить сразу несколько файлов:
$curl_files = array( 'photo[0]' => curl_file_create(__DIR__ . '/image.png', 'image/png' , 'image.png'), 'photo[1]' => curl_file_create(__DIR__ . '/image-2.png', 'image/png' , 'image-2.png') ); $ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $curl_files); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $res = curl_exec($ch); curl_close($ch);
Ещё файлы можно отправить методом PUT , например так загружаются файлы в REST API Яндекс Диска.
$file = __DIR__ . '/image.jpg'; $fp = fopen($file, 'r'); $ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_PUT, true); curl_setopt($ch, CURLOPT_UPLOAD, true); curl_setopt($ch, CURLOPT_INFILESIZE, filesize($file)); curl_setopt($ch, CURLOPT_INFILE, $fp); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); curl_exec($ch); curl_close($ch);
Скачивание файлов
Curl позволяет сохранить результат сразу в файл, указав указатель на открытый файл в параметре CURLOPT_FILE .
$file_name = __DIR__ . '/file.html'; $file = @fopen($file_name, 'w'); $ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_FILE, $file); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); curl_exec($ch); curl_close($ch); fclose($file);
$ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $html = curl_exec($ch); curl_close($ch); file_put_contents(__DIR__ . '/file.html', $html);
Отправить и получить cookie
Чтобы CURL сохранял куки в файле достаточно прописать его путь в параметрах CURLOPT_COOKIEFILE и CURLOPT_COOKIEJAR .
$ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_COOKIEFILE, __DIR__ . '/cookie.txt'); curl_setopt($ch, CURLOPT_COOKIEJAR, __DIR__ . '/cookie.txt'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $html = curl_exec($ch); curl_close($ch);
Передать значение кук можно принудительно через параметр CURLOPT_COOKIE .
$ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_COOKIE, 'PHPSESSID=61445603b6a0809b061080ed4bb93da3'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $html = curl_exec($ch); curl_close($ch);
Имитация браузера
На многих сайтах есть защита от парсинга. Она основана на том что браузер передает серверу user agent , referer , cookie . Сервер проверяет эти данные и возвращает нормальную страницу. При подключение через curl эти данные не передаются и сервер отдает ошибку 404 или 500. Чтобы имитировать браузер нужно добавить заголовки:
$headers = array( 'cache-control: max-age=0', 'upgrade-insecure-requests: 1', 'user-agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36', 'sec-fetch-user: ?1', 'accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3', 'x-compress: null', 'sec-fetch-site: none', 'sec-fetch-mode: navigate', 'accept-encoding: deflate, br', 'accept-language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7', ); $ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_COOKIEFILE, __DIR__ . '/cookie.txt'); curl_setopt($ch, CURLOPT_COOKIEJAR, __DIR__ . '/cookie.txt'); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, true); $html = curl_exec($ch); curl_close($ch); echo $html;
HTTP авторизация
Basic Authorization
Если на сервере настроена HTTP авторизация, например с помощью .htpasswd, подключится к нему можно с помощью параметра CURLOPT_USERPWD .
$ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_USERPWD, 'login:password'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $html = curl_exec($ch); curl_close($ch); echo $html;
OAuth авторизация
$ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: OAuth TOKEN')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); $html = curl_exec($ch); curl_close($ch); echo $html;
Получить HTTP код ответа сервера
$ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, false); curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); echo $http_code; // Выведет: 200
Если CURL возвращает false
Какая произошла ошибка можно узнать с помощью функции curl_errno() .
$ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, false); curl_exec($ch); $res = curl_exec($ch); var_dump($res); // false if ($errno = curl_errno($ch)) < $message = curl_strerror($errno); echo "cURL error ():\n "; // Выведет: cURL error (35): SSL connect error > curl_close($ch);
Sending auth in headers php curl
I was getting a «content type required» error. But I just figure it out! I’ve updated the code above.
4 Answers 4
In order to get custom headers into your curl you should do something like the following:
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Some_custom_header: 0', 'Another_custom_header: 143444,12' ));
Therefore the following should work in your case (given X-abc-AUTH is the only header you need to send over):
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'X-abc-AUTH: 123456789' // you can replace this with your $auth variable ));
If you need additional custom headers, all you have to do is add on to the array within the curl_setopt.
I’m struggeling with the problem that only the first array item will be received by the server. Maybe somebody can help with this stackoverflow.com/questions/49771245/… ?
I used this for the PHP/curl auth header for AWS AppSync GraphQL. Thanks for the help boys. ‘x-api-key: ‘.$authToken
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL,"http://www.example.com/process.php"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS,$vars); //Post Fields curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $headers = array(); $headers[] = 'X-abc-AUTH: 123456789'; $headers[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'; $headers[] = 'Accept-Encoding: gzip, deflate'; $headers[] = 'Accept-Language: en-US,en;q=0.5'; $headers[] = 'Cache-Control: no-cache'; $headers[] = 'Content-Type: application/x-www-form-urlencoded; charset=utf-8'; $headers[] = 'Host: 202.71.152.126'; $headers[] = 'Referer: http://www.example.com/index.php'; //Your referrer address $headers[] = 'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:28.0) Gecko/20100101 Firefox/28.0'; $headers[] = 'X-MicrosoftAjax: Delta=true'; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $server_output = curl_exec ($ch); curl_close ($ch); print $server_output ;