-1

I am very new to PHP(Laravel) and got some project. This is the explanation:

  • One device exists someplace and it gathers some data.
  • My project needs to log in to the device and need to get data by JSON file.

I used this code for that work:

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "$url.0.json");
    curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 40);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    
    $response = curl_exec($ch);
    $errno = curl_errno($ch);
    $error = curl_error($ch);
    $code = -1;   
    
    if (!$errno) $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

It returns 302 found error so I added this line of code:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);  

After that, I got 200 code but the response is HTML code for the login page.(Not JSON)

When I copy and paste the URL("$url.0.json") in the web browser, it redirects to the login page

I think the login cannot work successfully.

Please give me some advice. I appreciate it in advance

P.Lee
  • 59
  • 1
  • 10
  • Does this answer your question? [CURL to access a page that requires a login from a different page](https://stackoverflow.com/questions/12399087/curl-to-access-a-page-that-requires-a-login-from-a-different-page) – Don't Panic Sep 28 '21 at 07:12
  • Or if you want to use Guzzle: https://stackoverflow.com/questions/25089960/how-to-get-past-login-screen-on-guzzle-call – Don't Panic Sep 28 '21 at 07:14

1 Answers1

0

Don't use Curl if you're using Laravel. Assuming you're using Laravel 7 or later, you can use the Laravel HTTP Client. This is much easier than Curl.

Laravel Docs: https://laravel.com/docs/8.x/http-client

use Illuminate\Support\Facades\Http; 

$response = Http::withBasicAuth($username, $password)->get($url);

If you are using an earlier version of Laravel, use Guzzle HTTP Client.

Guzzle Docs: https://docs.guzzlephp.org/en/stable/quickstart.html

use GuzzleHttp\Client;

$client = new Client;
$response = $client->request('GET', $url, ['auth' => [$username, $password']]);
Ernesto Jaboneta
  • 71
  • 1
  • 1
  • 4