Examples of using cURL in PHP

cURL PHP is a library for receiving and transmitting data via protocols such as HTTP, FTP, HTTPS. The library is used to receive data as XML, JSON and directly into HTML, parsing, uploading and transferring files, etc.

2

POST request

$array = array(
	'login'    => 'admin',
	'password' => '1234'
);		

$ch = curl_init('https://example.com');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $array); 

// Or pass the array as a string:
// 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;
PHP

file_get_contents() can also send POST requests:

$headers = stream_context_create(array(
	'http' => array(
		'method' => 'POST',
		'header' => 'Content-Type: application/x-www-form-urlencoded' . PHP_EOL,
		'content' => 'login=admin&password=1234',
	),
));

echo file_get_contents('https://example.com', false, $headers);
PHP

Отправка 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);
PHP
14.11.2017, updated 21.09.2021
329

Comments

to add a comment.

Other publications

Regular Expression Shortcodes
Often on sites, it becomes necessary to insert dynamic information blocks into the texts of pages - banners, phones...
25
0
Checking data with regular expressions
A collection of regular expressions with examples in PHP for validating data from form fields.
49
0
Automatic setting of the user's time zone
date_default_timezone_set sets the default timezone used by all date / time functions.
113
0
Serialize function, possible problems
The serialize () function returns a string representation of any value (array, object, etc.). Using serialize on an...
32
0
How to set up Last-Modified
The Last-Modified header helps to optimize the loading of web pages and make the job easier for search engines.
100
0
How to find out if a request came via AJAX
To distinguish between direct and AJAX requests, simply check the value of the $ _SERVER global variable
61
0