Tags
Asked 3 years ago
9 Jun 2021
Views 216
jignesh

jignesh posted

curl request with url in variable in php ?

curl request with url in variable in php ?
denyy

denyy
answered Apr 26 '23 00:00

To make a cURL request with a URL stored in a variable in PHP, you can pass the variable as the value of the CURLOPT_URL option.

Here's an example:


$url = "https://www.example.com/api";

// Initialize cURL session
$ch = curl_init();

// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url); // pass the URL variable
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return response as string

// Execute cURL session
$response = curl_exec($ch);

// Check for errors
if(curl_errno($ch)) {
    echo 'Error: ' . curl_error($ch);
}

// Close cURL session
curl_close($ch);

// Process the response
echo $response;

In this example, the $url variable contains the URL that we want to make a cURL request to. We pass this variable as the value of the CURLOPT_URL option using the curl_setopt () function.

The remaining code sets other cURL options, executes the cURL session, checks for errors, and processes the response.

Note that you can also use string concatenation to include variables in the URL, like this:


$endpoint = "/users";
$params = array("id" => 123);

$url = "https://www.example.com/api" . $endpoint . "?" . http_build_query($params);

This will create a URL like https://www.example.com/api/users?id=123, which includes the endpoint and parameters as query string parameters. You can then pass this URL variable to the CURLOPT_URL option as before.
Post Answer