1

I use curl with laravel and I need to launch a function inside a controller.

but when I put

dd('test'); 

after the namespace it's print.but when I try with the function a have a session expired

this is the code for the curl

// Préparation des données
  $data = [];
  $data["code__client"] = "VERTDIS13";
  $data["status"] = "90";
  $data["numero__incident"] = "INC544842";

  // On tranforme le tableau PHP en objet JSON
  $data = json_encode($data);

  // Envoi au serveur
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL,"http://localhost:3000/notification/server");
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, "data=" . $data);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  curl_setopt($ch, CURLOPT_COOKIESESSION, true);
  curl_setopt($ch, CURLOPT_UNRESTRICTED_AUTH, true);
  $server_output = curl_exec($ch);
  $error = curl_error($ch);
  if($error!=""){ dd($error);}
  curl_close($ch);


  // Ici pour tester j'affiche ce que le serveur renvoi
  return $server_output;

inside the controller I tried to print data but it doesn't work

do you see the issue ?

thanks for help .

2 Answers2

1

The session expired response sounds to me as if you are performing multiple consecutive curl requests to your application. If that's the case and your application depends on session cookies you can create a simple text file that is read and writeable to the script that does the curl requests, and add this to your code:

$cookie_file = "/the/path/to/your/cookiefile.txt";
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);

Change the path in $cookie_file to the full filesystem path of the text file you create and curl will persist session cookies that are being returned with responses and use them in consecutive requests. For this to work I think you should remove the line

curl_setopt($ch, CURLOPT_COOKIESESSION, true);

because this would advise curl to ignore the cookies in the file.

Besides that I think the line

curl_setopt($ch, CURLOPT_UNRESTRICTED_AUTH, true); 

is also obsolete, because you don't provide basic auth credentials in your curl request.

  • hello thanks for your help . I remove the line and I put the path to the cookie but I have the same issue ... (and I can print the file content ) – Gautier Drincqbier May 07 '18 at 07:41
0

I presume you extract data from within the application? To me, it looks like CSRF token is missing or is in fact invalid.

for ($i = 0; $i < $metas->length; $i++){
$meta = $metas->item($i);
  if($meta->getAttribute('name') == 'csrf-token')
    $csrfToken = $meta->getAttribute('content');
}
$headers = array();
$headers[] = "Cookie: X-CSRF-Token=$csrfToken";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

More about CSRF & cURL

Give this a go

Mac
  • 55
  • 8