How to get Contents of a Webpage using PHP curl
PHP cURL module allows you to connect to remote websites and API endpoints to exchange data. To see if you have php-curl enabled, you can check phpinfo() page or run the command “php -m’ and look for curl.
1 2 3 |
boby@sok-01:~$ php -m | grep curl curl boby@sok-01:~$ |
If php-curl module is not installed, you can install it on Ubuntu/Debian with the command
1 |
apt-get install php-curl |
To access the content of a remote web server or API endpoint, you can use the following PHP code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php $url = "https://serverok.in"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); // set the option to return the response instead of printing it curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // set the user agent curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 11.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'); // execute the cURL request $response = curl_exec($ch); // check for errors if(curl_errno($ch)) { echo 'cURL error: ' . curl_error($ch); } // close the cURL session curl_close($ch); // print the response echo $response; |
To make script work with invalid or self signed SSL, add following
1 2 |
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); |
If you want to make a POST request, you can use the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php $url = "https://serverok.in"; $data = array( 'name' => 'Yujin Boby', ); $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 11.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'); $response = curl_exec($ch); curl_close($ch); |
Back to PHP