Magento 2 cURL

Following code get content from an external site using cURL.

<?php
 namespace PHPCodez\Layout\Block;
 
 class Footer extends \Magento\Framework\View\Element\Template {
 
 protected $_httpClientFactory;
 
 public function __construct(\Magento\Framework\View\Element\Template\Context $context,
 \Magento\Framework\HTTP\ZendClientFactory $httpClientFactory) {
 $this->_httpClientFactory = $httpClientFactory;
 parent::__construct($context);
 }

public function getFooterContent() {
 $url = "http://127.0.0.1:81/content/footer.php";
 $client = $this->_httpClientFactory->create();
 $client->setUri($url);
 return $response = $client->request(\Zend_Http_Client::POST)->getBody(); 
 }
 }

For more option you can check vendor\magento\framework\HTTP\Client\Curl.php

addHeader()
setCredentials()
addCookie()
get() // for get request
makeRequest() // for make request
setOption() // set curl options

Leave a Reply

Your email address will not be published. Required fields are marked *