In this PHP example tutorial we will create make a curl HTTP request in laravel. The PHP cURL library is used to send HTTP queries to any web server. In PHP CURL, four stages are repeated in every PHP cURL script:
Activate PHP cURL.
Set the settings, such as the destination URL, POST data, and so on. There are several possibilities.
CURL should be executed, and any PHP CURL problems should be handled.
Disconnect the PHP cURL connection.
Example 1
In this example, we use PHP CURL to upload data. We will use the json encode() function to transform array data to JSON data, and then we will send data using PHP CURL
<?php // A sample PHP Script to POST data using cURL $data = array( 'name' => 'tutsmake', 'email' => 'tutsmake@gmail.com', 'mobile' => '9898989898', ); $post_data = json_encode($data); // Prepare new cURL resource $crl = curl_init('https://example.com/api/user'); curl_setopt($crl, CURLOPT_RETURNTRANSFER, true); curl_setopt($crl, CURLINFO_HEADER_OUT, true); curl_setopt($crl, CURLOPT_POST, true); curl_setopt($crl, CURLOPT_POSTFIELDS, $post_data); // Set HTTP Header for POST request curl_setopt($crl, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($payload)) ); // Submit the POST request $result = curl_exec($crl); // handle curl error if ($result === false) { // throw new Exception('Curl error: ' . curl_error($crl)); //print_r('Curl error: ' . curl_error($crl)); $result_noti = 0; die(); } else {
$result_noti = 1; die(); } // Close cURL session handle curl_close($crl); ?> |
Example 2
In this example, we are going to make the curl http request in a laravel application.
Step 1: First of all run the following command to make a User Controller
Php make:controller UserController |
A user controller is created in the app/Http/Controllers
Open your UserController.php and paste the code below
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Http; class UserController extends Controller {
function index() { return Http::get("http://reqres.in/api/user?page=1"); } } |
Step 2: Create a route. To do this open your Route/web.php and paste the code below
<?php
use Illuminate\Support\Facades\Route; //use App\Http\Controllers\UserController;
/* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group that | contains the "web" middleware group. Now create something great! | */
Route::get('/', function () { return view('welcome'); });
Route::get("users",[UserController::class,'index']); |
If you now run your application in the browser, the data from the api will be displayed
In this php laravel tutorial we covered how to make HTTP curl request
Article Contributed By :
|
|
|
|
1465 Views |