Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] PHP CURL Post and Get request with example

#1
PHP CURL Post and Get request with example

<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2022/05/php-curl-post-and-get-request-with-example.jpg" width="550" height="335" title="" alt="" /></div><div><div class="modified-on" readability="7.0243902439024"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on May 6th, 2022.</div>
<p>PHP cURL is a library that allows clients to access a remote server via a URL. It sends HTTP requests to the endpoint from a different application or component.</p>
<p>It allows inter-application hits to get a response over the network. This mechanism is useful to work with <a href="https://phppot.com/php/php-restful-web-service/">PHP RESTful services</a>, API interactions, and etc.</p>
<p>There are many use case scenarios where PHP cURL post is exactly suited. For example,</p>
<ol>
<li><a href="https://phppot.com/php/extract-content-using-php-and-preview-like-facebook/">Extracting content</a> from a webpage.</li>
<li>Preparing feed from external sources.</li>
<li>SDK-free API’s direct access methods.</li>
</ol>
<p>This quick example gives a straightforward code to implement a PHP cURL post.</p>
<div class="post-section-highlight" readability="40">
<h2>Quick example</h2>
<pre class="prettyprint"><code class="language-php">
&lt;?php
$postParameter = array( 'name' =&gt; 'Jane', 'dateOfBirth' =&gt; '1974-8-17'
); $curlHandle = curl_init('http://domain-name/endpoint-path');
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $postParameter);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); $curlResponse = curl_exec($curlHandle);
curl_close($curlHandle); </code></pre>
</div>
<p>Apart from this, we will see more use case examples of PHP cURL post requests in the upcoming sections.</p>
<h2>Part 1 – Basics of PHP cURL</h2>
<p>The following are the steps to perform a basic PHP cURL request-response cycle.</p>
<ul>
<li>Initialize cURL session.</li>
<li>Set cURL options.</li>
<li>Execute request.</li>
<li>Close session.</li>
</ul>
<h2>How to configure PHP cURL?</h2>
<p>PHP contains <strong>libcurl</strong> library to let the environment work with cURL. This library will be enabled by default.</p>
<p>If not, do the following steps to enable <a href="https://www.php.net/curl" target="_blank" rel="noopener">PHP cURL</a> module in your environment.</p>
<ol>
<li>Open <a href="https://phppot.com/php/php-ini-file/">PHP configuration file php.ini</a></li>
<li>Check for the <code>extension=php_curl.dll</code> initiation.</li>
<li>Remove the semicolon (Wink at the beginning of the above line.</li>
<li>Restart the A<em>pache</em> server.</li>
</ol>
<p><img loading="lazy" class="alignnone size-large wp-image-16713" src="https://phppot.com/wp-content/uploads/2022/04/php-curl-life-cycle-flow-550x335.jpg" alt width="550" height="335" srcset="https://phppot.com/wp-content/uploads/2022/04/php-curl-life-cycle-flow-550x335.jpg 550w, https://phppot.com/wp-content/uploads/20...00x183.jpg 300w, https://phppot.com/wp-content/uploads/20...68x468.jpg 768w, https://phppot.com/wp-content/uploads/20...e-flow.jpg 800w" sizes="(max-width: 550px) 100vw, 550px"></p>
<h2>Set PHP cURL POST requests – Alternate methods</h2>
<p>There are many ways to send PHP cURL post parameters.</p>
<ol>
<li>JSON format.</li>
<li>HTTP query string.</li>
<li>POST array format.</li>
</ol>
<p><strong>JSON format:</strong></p>
<pre class="prettyprint"><code class="language-php"> &lt;?php curl_setopt($ch, CURLOPT_POSTFIELDS, "{key1:value1,key2:value2}");
?&gt;</code></pre>
<p><strong>HTTP query string:</strong></p>
<pre class="prettyprint"><code class="language-php"> &lt;?php curl_setopt($ch, CURLOPT_POSTFIELDS, "key1=value1&amp;key2=value2"); ?&gt;</code></pre>
<p><strong>PHP cURL POST array format</strong></p>
<p>The <code class="language-php">CURLOPT_POSTFIELDS</code> may have a <a href="https://phppot.com/php/power-of-php-arrays/">PHP array</a> to pass the parameters to the endpoint.</p>
<pre class="prettyprint"><code class="language-php"> &lt;?php curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'); curl_setopt($ch, CURLOPT_POSTFIELDS, array("key1"=&gt;"value1", "key2"=&gt;"value2"); ?&gt;</code></pre>
<h2>Set cURL header options</h2>
<p>To set PHP cURL header, the CURLOPT_HTTPHEADER constant is used. A cURL header can have more information. The following keys are some of the examples to add PHP cURL header options.</p>
<ul>
<li>Accept-Encoding</li>
<li>Cache-Control</li>
<li>Host</li>
<li>Content-Type</li>
<li>Accept-Language</li>
<li>User-Agent</li>
</ul>
<p>This program sets the cURL header options to set the content type. There are options to send custom headers also. It is to send non-standard key-value pairs. Use prefix <strong>X-</strong> to send non-standard headers. Example,</p>
<pre class="prettyprint"><code class="language-php">
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'X-key: value'
));
</code></pre>
<p>The CURLOPT_HEADER constant is set with boolean <em>true</em>. It is for allowing the header information attached with the return response.</p>
<pre class="prettyprint"><code class="language-php">
&lt;?php
$url = "http://domain-name/endpoint-path"; $curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $headers = array( "X-Custom-Header: header-value", "Content-Type: application/json"
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_HEADER, true);
$response = curl_exec($curl);
curl_close($curl);
echo $response; </code></pre>
<h2>Part 2 – Example use cases</h2>
<p>With some basic knowledge, it will be easy to understand the following examples. It deals with some of the use case scenarios of PHP cURL post or get <a href="https://phppot.com/php/php-request-methods/">request methods</a>.</p>
<h2>HTTP POST form data</h2>
<p>PHP cURL allows posting parameters to the server. It uses any one of the methods we discussed earlier to post parameters via cURL.</p>
<p>The following cURL script shows how to post an array to an endpoint URL. The <code class="language-php">CURLOPT_POST</code> and the <code class="language-php">CURLOPT_POSTFIELDS</code> are to send the values via PHP cURL post.</p>
<pre class="prettyprint"><code class="language-php">
&lt;?php
$url = 'http://domain-name/endpoint-path'; $curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $data = "name=jane&amp;age=23"; curl_setopt($curl, CURLOPT_POSTFIELDS, $data); $result = curl_exec($curl);
curl_close($curl);
?&gt;
</code></pre>
<h3>PHP cURL POST to upload file</h3>
<p>It is also possible to upload files to the server via PHP cURL post. The below code shows <a href="https://phppot.com/php/php-file-upload/">how to upload an image file</a> to the server.</p>
<p>It prepares the object with the file data. It uses PHP curl_file_create() function to prepare the file post content.</p>
<p>By sending the ‘<em>fileParam’</em> bundle in this way, the endpoint code can access it via <em>$_FILES[]</em> array.</p>
<pre class="prettyprint"><code class="language-php">
&lt;?php
$url = 'https://domain-name/path-to-endpoint/php-curl-post-file-endpoint.php'; if (function_exists('curl_file_create')) { $fileContent = curl_file_create("cherry.jpeg", 'image/jpeg');
} else { $fileContent = '@' . realpath("cherry.jpeg", 'image/jpeg');
} $data = array('fileParam'=&gt; $fileContent); $curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST,true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$result=curl_exec ($curl);
curl_close ($curl); print $result;
?&gt;
</code></pre>
<p>Put the following endpoint code in the server. Then hit the endpoint via the above cURL script. The PHP curl post request sends the file input to this endpoint. This PHP code accesses the uploaded file from the $_FILES array.</p>
<p class="code-heading">php-curl-post-file-endpoint.php</p>
<pre class="prettyprint"><code class="language-php">
&lt;?php
$targetDir = 'uploads';
if ($_FILES["fileParam"]["tmp_name"] != "") { $tmp_name = $_FILES["fileParam"]["tmp_name"]; // basename() may prevent filesystem traversal attacks; // further validation/sanitation of the filename may be appropriate $name = basename($_FILES["fileParam"]["name"]); if(move_uploaded_file($tmp_name, $targetDir . "/" . $name)) { print "Image uploaded."; } else { print "Image upload failed."; } }
?&gt;
</code></pre>
<h2>HTTP GET request to grab a webpage</h2>
<p>In the cURL request, the default method is GET. This program calls the server via cURL with the default GET request method.</p>
<p>Unlike PHP cURL POST, it sends data as the query string. To pass parameters to a GET request, it should be built as part of the URL.</p>
<p>It <a href="https://phppot.com/php/extracting-title-description-thumbnail-using-youtube-data-api/">grabs the HTML of the website</a> specified as the cURL endpoint. It prints the response and renders the target website’s HTML in the browser.</p>
<pre class="prettyprint"><code class="language-php">
&lt;?php
$url = 'http://domain-name/endpoint-path'; $curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($curl);
curl_close($curl);
print $response; </code></pre>
<h3>Grab website HTML via cURL and write to a file</h3>
<p>Instead of printing the website layout to the browser, it can also be <a href="https://phppot.com/php/php-file-handling/">written into a file</a>.</p>
<p>This code creates a filehandle and writes the cURL HTML response into a file. It uses the file handle as the reference.</p>
<p>It will be useful if you want to download and save the website HTML into the server permanently.</p>
<pre class="prettyprint"><code class="language-php">
&lt;?php
$url = 'http://domain-name/endpoint-path';
$file = fopen("site-content.html", "w"); $curl = curl_init($url);
curl_setopt($curl, CURLOPT_FILE, $file); curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false); curl_exec($curl);
curl_close($curl);
fclose($file); </code></pre>
<p>The PHP&nbsp;<a href="https://phppot.com/php/php-file_get_contents/"><em>file_get_contents()&nbsp;</em>function</a> is also used to grab the content of the target URL.</p>
<p>But, the server configuration should allow reading the content by using this method.</p>
<h2>PHP CURL post and receive JSON data</h2>
<p>This example shows how to send a PHP cURL post in JSON format. It also receives the cURL response in the format of JSON.</p>
<p>This code guides creating API services to get requests and send <a href="https://phppot.com/jquery/read-display-json-data-using-jquery-ajax/">responses in JSON format</a>.</p>
<pre class="prettyprint"><code class="language-php">
&lt;?php
$url = 'https://domain-name/path/php-curl-post-endpoint-json.php';
$data = array( "first_name" =&gt; "Jane", "last_name" =&gt; "Mclane", "email" =&gt; "[email protected]", "addresses" =&gt; array( "address1" =&gt; "21/A", "city" =&gt; "Los Angels", "country" =&gt; "USA", "phone" =&gt; "555-1212", "pincode" =&gt; "82312" )
);
$encodedData = json_encode($data);
$curl = curl_init($url);
$data_string = urlencode(json_encode($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt( $curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $encodedData);
$result = curl_exec($curl);
curl_close($curl);
print $result; </code></pre>
<p>This code prepares the JSON response by setting the content-type using PHP header(). It sets the application/json as the content type.</p>
<p class="code-heading">php-curl-post-endpoint-json.php</p>
<pre class="prettyprint"><code class="language-php">
&lt;?php
header("Content-Type:application/json");
$data = file_get_contents('php://input');
print $data; </code></pre>
<h2>Handle redirects (HTTP 301,302)</h2>
<p>The CURLOPT_FOLLOWLOCATION is set to true to perform the 3XX <a href="https://phppot.com/php/php-redirect/">redirect via PHP</a> cURL.</p>
<p>During the redirect, the cURL will send a GET request on successive redirects. To change this, the CURLOPT_POSTREDIR has to be set.</p>
<p>This program sets CURL_REDIR_POST_ALL to send PHP cURL POST requests on successive attempts.</p>
<p>It limits the number of redirects by using the CURLOPT_MAXREDIRS constant.</p>
<pre class="prettyprint"><code class="language-php">
&lt;?php
$url = 'http://domain/path';
$data = array( "first_name" =&gt; "Jane", "last_name" =&gt; "Mclane"
);
$encodedData = json_encode($data);
$curl = curl_init($url);
$data_string = urlencode(json_encode($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $encodedData); curl_setopt($curl, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl,CURLOPT_MAXREDIRS, 3);
$result = curl_exec($curl);
$info = curl_getinfo($curl);
curl_close($curl);
print "&lt;PRE&gt;";
print_r($info);
print_r($result); </code></pre>
<p>This program will return more information as shown below.</p>
<ul>
<li><a href="https://phppot.com/javascript/javascript-redirect/">Redirects</a> count.</li>
<li>Time to redirect.</li>
<li>A header with the 3XX status.</li>
</ul>
<p><img loading="lazy" class="alignnone size-full wp-image-16737" src="https://phppot.com/wp-content/uploads/2022/05/php-curl-post-3xx-redirect.jpg" alt="php curl post 3xx redirect" width="500" height="848" srcset="https://phppot.com/wp-content/uploads/2022/05/php-curl-post-3xx-redirect.jpg 500w, https://phppot.com/wp-content/uploads/20...77x300.jpg 177w" sizes="(max-width: 500px) 100vw, 500px"></p>
<h2>Writing cURL error logs into a file</h2>
<p>Keeping logs is a best practice for audit purposes. When the site is live, sometimes the logs are very <a href="https://phppot.com/php/php-error-handling/">useful for debugging</a> also.</p>
<p>Since it is a remote call, logging cURL errors into a file will help to analyze and fix the issue.</p>
<p>This code guides how to log the error that occurred during the PHP cURL post. It uses PHP curl_error() function to</p>
<pre class="prettyprint"><code class="language-php">
&lt;?php
$logFileHandle = fopen("log/curl-error-log.txt", 'a+');
$curl = curl_init("http://domain_name/path");
if(curl_exec($curl) === false)
{ $date = date("m/d/Y"); $errorMessage = curl_error($curl); $curlError = $date . ' Error: ' . $errorMessage . "\n\n";
}
curl_close($curl);
fwrite($logFileHandle, $curlError);
fclose($logFileHandle);
</code></pre>
<h3>Write cURL log using CURLOPT_STDERR constant</h3>
<p>There is an alternate method to log the PHP cURL error into a file. The CURLOPT_STDERR writes the error message with the reference of the file handle.</p>
<pre class="prettyprint"><code class="language-php">
&lt;?php
$logFileHandle = fopen("log/curl-error-log.txt", 'a+');
$curl = curl_init("http://domain_name/path");
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_VERBOSE, true);
curl_setopt($curl, CURLOPT_FILE, $logFileHandle);
curl_setopt($curl, CURLOPT_STDERR, $logFileHandle);
curl_exec($curl);
curl_close($curl);
fclose($logFileHandle); </code></pre>
<p>This program will return the following output.<br /><img loading="lazy" class="alignnone size-full wp-image-16741" src="https://phppot.com/wp-content/uploads/2022/05/php-curl-error-log.jpg" alt="php curl error log" width="400" height="105" srcset="https://phppot.com/wp-content/uploads/2022/05/php-curl-error-log.jpg 400w, https://phppot.com/wp-content/uploads/20...300x79.jpg 300w" sizes="(max-width: 400px) 100vw, 400px"></p>
<h2>Part 3 – Creating PHP cURL script to extract images from a website</h2>
<p>In this part of the article, we are going to create a end-to-end cURL component. It will do the following to achieve <a href="https://phppot.com/php/extract-images-from-url-in-excel-with-php-using-phpspreadsheet/">grabbing images from a webpage</a>.</p>
<ol>
<li>Create API service to instantiate DOM to load response.</li>
<li>Create cURL service to instantiate, configure and execute requests.</li>
<li>Read cURL response and load it into the DOM object.</li>
<li>Get the image source URL by accessing the DOM object.</li>
<li><a href="https://phppot.com/php/bootstrap-cards-shopping-cart/">Create a photo gallery</a> by using the PHP cURL response array.</li>
</ol>
<h3>API service class to initiate cURL and create DOM object</h3>
<p>This <em>GrabImageAPI</em> class creates PHP DOMDocument instants to load the site HTML.</p>
<p>The <a href="https://phppot.com/php/php-constructors-destructors/">constructor</a> initiates cURL and grabs the complete HTML response of the URL. Then, it loads this response into the DOM object.</p>
<p>With the reference of the object, the getWebsiteImage() gets the image source URLs.</p>
<p>This function reads all images by using&nbsp;<em>getElementsByTagName()</em>. By iterating the image data array, it prepares the JSON bundle of image URLs.</p>
<p class="code-heading">Service/GrabImageAPI.php</p>
<pre class="prettyprint"><code class="language-php">
&lt;?php
namespace Phppot\Service; use \Phppot\Service\CurlService;
use DOMDocument; class GrabImageAPI
{ private $dom; public function __construct($url) { require_once __DIR__ . '/CurlService.php'; $curlService = new CurlService($url); $siteHTML = $curlService-&gt;executeCurl(); $this-&gt;dom = new DOMDocument(); @$this-&gt;dom-&gt;loadHTML($siteHTML); } function getWebsiteImage() { // Parse DOM to get Images $images = $this-&gt;dom-&gt;getElementsByTagName('img'); $imageSourceURL = array(); for ($i = 0; $i &lt; $images-&gt;length; $i ++) { $image = $images-&gt;item($i); $src = $image-&gt;getAttribute('src'); if(filter_var($src, FILTER_VALIDATE_URL)) { $imageSourceURL[] = $src; } } $imageSourceJSON = json_encode($imageSourceURL); return $imageSourceJSON; }
} </code></pre>
<h3>Create cURL service to perform routine life cycle operations</h3>
<p>This class is nothing but for performing basic curl operations we have seen at the beginning.</p>
<p>The GrabImageAPI constructor includes this service and creates the cURL instance.</p>
<p class="code-heading">Service/CurlService.php</p>
<pre class="prettyprint"><code class="language-php">
&lt;?php
namespace Phppot\Service; class CurlService
{ private $curl; private $endpoint; private $response; function __construct($url) { $this-&gt;endpoint = $url; $this-&gt;curl = curl_init($this-&gt;endpoint); } function setCurlOption() { curl_setopt($this-&gt;curl, CURLOPT_HEADER, 0); curl_setopt($this-&gt;curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($this-&gt;curl, CURLOPT_FOLLOWLOCATION, 1); } function executeCurl() { $this-&gt;setCurlOption(); $this-&gt;response = curl_exec($this-&gt;curl); curl_close($this-&gt;curl); return $this-&gt;response; }
}
</code></pre>
<h3>Trigger API to grab images via PHP cURL post</h3>
<p>This code will hit the API to grab images via PHP cURL post. It requires the <a href="https://www.php.net/manual/en/ref.curl.php">API class reference</a> on which it creates the <a href="https://phppot.com/wordpress/how-to-create-an-image-gallery-in-wordpress/">dynamic image gallery</a> using cURL.</p>
<p>This code is useful to <a href="https://phppot.com/wordpress/how-to-create-wordpress-widget/">create a gallery widget</a> for your external shop independently.</p>
<p class="code-heading">php-curl-grab-image.php</p>
<pre class="prettyprint"><code class="language-php">
&lt;?php
namespace Phppot; use \Phppot\Service\GrabImageAPI; require_once __DIR__ . '/Service/GrabImageAPI.php';
$url = "https://domain-name-here/";
$imageSourceArray = array();
try { // Call image grab PHP cURL script $grabImageAPI = new GrabImageAPI($url); // Get image source array in JSON format via PHP cURL $imageSource = $grabImageAPI-&gt;getWebsiteImage(); $imageSourceArray = json_decode($imageSource, true);
} catch (Exception $e) { // Handle API request failure $statusMsg = $e-&gt;getMessage(); print $statusMsg; exit;
} // Iterate response and form image gallery in UI
foreach($imageSourceArray as $imageSource) { ?&gt; &lt;img src="&lt;?php echo $imageSource; ?&gt;" style="width: 300px; margin: 20px;" /&gt; &lt;?php } </code></pre>
<h2>Conclusion</h2>
<p>Hope this article helps you to know a deep knowledge about PHP cURL post and other request methods.</p>
<p>The short and end-to-end examples might be useful to create a cURL component for your application.</p>
<p>I welcome your comments to continue giving more value-adds to the learners.<br /><a class="download" href="https://phppot.com/downloads/php-curl-post.zip">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/php/php-curl-post/#top" class="top">↑ Back to Top</a> </p>
</div>


https://www.sickgaming.net/blog/2022/05/...h-example/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016