"Hey guys, struggling with a curl_init get request in PHP. Anyone got a simple example?"
So I'm trying to fetch some data from an API using curl_init get request, but it's not returning what I expect.
Maybe I'm missing something basic? Like, do I need to set CURLOPT_RETURNTRANSFER or something?
Here's what I’ve got:
```php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://example.com/api");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
```
Is this correct? Or am I totally off?
Also, any best practices for handling errors? Sometimes it just fails silently and I’m like... *why?*
Thanks in advance! 🙏
Your curl_init get request looks mostly correct! But yeah, CURLOPT_RETURNTRANSFER is a must if you want the response stored in a variable.
For error handling, add:
```php
curl_setopt($ch, CURLOPT_FAILONERROR, true);
```
This makes curl fail if HTTP code is 400+. Also, check `curl_error($ch)` after `curl_exec` to see what went wrong.
Bro, you’re on the right track. The code’s fine for a basic GET request.
But APIs can be picky—sometimes you need headers. Try adding:
```php
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json']);
```
If the API expects JSON. Also, `var_dump($response)` to see raw output.
For debugging, use `curl_getinfo($ch)` after execution. It gives you HTTP status, timings, etc.
Your curl_init get request is correct, but APIs sometimes redirect. Add:
```php
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
```
to handle 3xx redirects automatically.
If it’s failing silently, always check `curl_errno($ch)` and `curl_error($ch)`.
Also, some APIs need a user-agent. Try:
```php
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
```
Weird, but some block empty UAs.
Pro tip: Use `file_get_contents` for super simple GET requests if the API allows it:
```php
$response = file_get_contents('https://example.com/api');
```
No curl_init get request needed! But yeah, curl is more flexible.
Your code’s good, but for better error handling, wrap it in a try-catch and check the HTTP code:
```php
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode != 200) {
throw new Exception("API returned $httpCode");
}
```
Makes debugging way easier.
Sometimes the SSL cert fails silently. Add:
```php
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
```
But only for testing! Disabling SSL checks in prod is a bad idea.
Hey everyone, thanks for the tips! I added error handling with `curl_error` and saw it was a SSL issue. Fixed it with `CURLOPT_SSL_VERIFYPEER` for now (will secure it later).
Also, Postman helped debug the headers—turns out the API needed a `Content-Type`.
One last Q: How do I handle timeouts? Sometimes the API is slow, and the script just hangs. `CURLOPT_TIMEOUT`?