- Примеры использования cURL в PHP
- GET запрос
- GET-запрос с параметрами
- POST запрос
- Отправка JSON через POST-запрос
- PUT запрос
- DELETE запрос
- Запрос через proxy
- Отправка файлов на другой сервер
- До PHP 5.5
- Скачивание файлов
- Отправить и получить cookie
- Имитация браузера
- HTTP авторизация
- Basic Authorization
- OAuth авторизация
- Получить HTTP код ответа сервера
- Если CURL возвращает false
- DELETE request with file_get_contents
- Answer by Delilah Larsen
- Answer by Landon Payne
- Answer by Eduardo Hubbard
- Answer by Jakobe Rogers
- Answer by Danna Kerr
Примеры использования 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);
DELETE request with file_get_contents
thinhpc Customize Follow Following Sign up Log in Copy shortlink Report this content View post in Reader Manage subscriptions Collapse this bar , Change and Update WordPress URLS in Database When Site is Moved to new Host , You are commenting using your Google account. ( Log Out / Change ) , You are commenting using your Twitter account. ( Log Out / Change )
$postdata = http_build_query( array( 'var1' => 'value 1', 'var2' => 'value 2' ) ); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://example.com/submit.php', false, $context);
$result = file_get_contents( 'http://example.com/submit.php', false, stream_context_create(array( 'http' => array( 'method' => 'DELETE' ) )) );
$params = array('key1' => 'value1', 'key2' => 'value2', ); $url = 'https://example.com/api/example'?' . http_build_query($params); $response = file_get_contents($url);
$result = file_get_contents( 'http://example.com/submit.php', false, stream_context_create(array( 'http' => array( 'method' => 'PUT' ) )) );
Answer by Delilah Larsen
stream_context_create() — Creates a stream context,$http_response_header, A valid context resource created with stream_context_create(). If you don’t need to use a custom context, you can skip this parameter by null. ,Example #4 Using stream contexts
Answer by Landon Payne
file_get_contents() Function: This PHP function is used to retrieve the contents of a file. The contents can be stored as a string variable. Alternatively, it also simulates HTTP transactions, involving requests via GET method and responses using POST method respectively. Primarily, it is best-suited for simple HTTP manipulations and to get single-line JSON responses. ,Multidimensional Associative Array in PHP,Difference between file_get_contents and cURL in PHP,Iterate associative array using foreach loop in PHP
Answer by Eduardo Hubbard
This will give you an array, $post_vars, with the request data.,Both file_get_contents(“php://input”) and $_REQUEST does not seem to output anything ,Following is the code I am using to make a REST request…The $data variable contains the data in array() format…,The in PHP, the data for incoming PUT and DELETE requests is available via the php://input stream. You can get the contents of the stream using file_get_contents(«php://input») but the data is returned as a query string, so you’ll probably want to parse that out into separate variables:
On the server I have this code in my index.php file where the request is being made.
//index.php echo $_SERVER['REQUEST_METHOD'], ''; print_r($_REQUEST); print_r(getallheaders())
Answer by Jakobe Rogers
$data[] = $_POST['data']; $inp = file_get_contents('results.json'); $tempArray = json_decode($inp); array_push($tempArray, $data); $jsonData = json_encode($tempArray); file_put_contents('results.json', $jsonData);
Answer by Danna Kerr
In PHP it is possible to detect request method in following way.,Note: $_PUT and $_DELETES arrays are not supported in php it means php://input stream should be parsed.,Note: ajax.htm and backend.php should be placed on php server both.
, success: function (data) < handle.innerHTML = 'Response:\n' + data; >, error: function(error) < handle.innerText = 'Error: ' + error.status; >>);