Search code examples
phpcodeigniterhttpcurlpost

Codeigniter 4 redirecting POST request to "/" when call made from cURL


I am writing an API and one of the methods is a POST that processes the data passed in the call and sets a response status. When I make a call to this method from a website form submission, it works fine, but when I make the same call from the command line via cURL, it redirects to "/". Do you know why that is?

cURL:

curl --location --request POST \
-H "Content-Type: application/json" \
-d '{"name":"John Doe","email":"johndoe@example.com"}' \
-w "Status: %{http_code}" \
http://localhost:8080/api/test 

Method:

namespace App\Controllers;

use CodeIgniter\Controller;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;

class Api extends Controller
{
    public function test()
    {
        $postData = $this->request->getPost();

        if (!empty($postData)) {
            $name = $postData['name'];
            $email = $postData['email'];

            echo "Received data: Name = $name, Email = $email";

            $responseStatus = 'success'; // Example: 'success', 'error', etc.

            return $this->response->setJSON(['status' => $responseStatus]);
        } else {
            return $this->response->setJSON(['status' => 'error', 'message' => 'No data received']);
        }
    }
}

For reference, I have this route set in Routes.php:

$routes->post('api/test', 'Api::test');

Solution

  • I found the issue! It was the CSRF protection. I just had to update it to exclude API calls:

    public $globals = [
        'before' => [
            // 'honeypot',
            'csrf' => ['except' => ['api/*]],
            // 'invalidchars',
        ],
        'after' => [
            'toolbar',
            // 'honeypot',
            // 'secureheaders',
        ],
    ];