How to connect to a URL in PHP?

Any URL can be connected to PHP easily by making use of the library called cURL. This comes as a default library with the standard installation of PHP.

The term cURL stands for client-side URL. cURL make use of libcurl(client-side URL Transfer Library) which supports many protocols like FTP, FTPS, HTTP/1, HTTP POST, HTTP PUT, HTTP proxy, HTTPS, IMAP, Kerberos etc. It allows you to connect to a URL and retrieve and display information from that page – like the HTML content of the page, HTTP headers, and their associated data, etc.

Steps for connecting with URL using PHP cURL POST are given below:

  • Initialize cURL session.
  • Define the URL where you want to post the request. We can directly enter this URL into the URL section inset option parameter or we can assign it to an object.
  • Now, define the cURL options that you want to execute with the post option.
  • After setting all the functions then it’s time to execute our cURL.
  • After this, close the cURL and echo your object to check their response.
//Step 1 To initialize curl
 $ch = curl_init();
//Step 2 To set url where you want to post
 $url = ‘http://www.localhost.com’;
//Step 3 Set curl functions which are needs to you
 curl_setopt($ch,CURLOPT_URL,$url);
 curl_setopt($ch,CURLOPT_POST,true);
 curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
 curl_setopt($ch,CURLOPT_POSTFIELD,’postv1 = value1&postv2 = value2’);
//Step 4 To execute the curl
 $result = curl_exec($ch);
//Step 5 Close curl
 curl_close($ch);