leafsphp / leaf

🍁 The easiest way to create clean, simple but powerful web apps and APIs quickly
https://leafphp.dev
MIT License
1.12k stars 68 forks source link

Exception: strpos(): Passing null to parameter #1 ($haystack) of type string is deprecated #158

Closed swimitup closed 2 years ago

swimitup commented 2 years ago

If you try to retrieve request body using request()->body() and it was sent NULL, an errorException will throw:

Screen Shot 2022-10-06 at 9 20 50 AM

According to like 108 on /leafs/http/src/Request.php:

    } else if (Headers::get('Content-Type') !== 'application/json' && strpos(Headers::get('Content-Type'), "multipart/form-data") !== 0) {

Since there's no Content-Type header on request:

> POST /v1/?grant_type=password HTTP/1.1
> Host: localhost:5500
> User-Agent: insomnia/2022.6.0
> Cookie: PHPSESSID=ethi72jpc8nbtj89j70knnog9i
> Accept: */*
> Content-Length: 0

Headers::get('Content-Type') will obviously return NULL.

A quick workaround would be assign to a local var and, if null, assign blank:

    $contentType = Headers::get('Content-Type') ?? '';

So the whole Request::input function would be like:

  public static function input($safeData = true)
  {
    $handler = fopen('php://input', 'r');
    $data = stream_get_contents($handler);
    $contentType = Headers::get('Content-Type') ?? '';

    if ($contentType === 'application/x-www-form-urlencoded') {
      $d = $data;
      $data = [];

      foreach (explode('&', $d) as $chunk) {
        $param = explode("=", $chunk);
        $data[$param[0]] = $param[1];
      }
    } else if ($contentType !== 'application/json' && strpos($contentType, "multipart/form-data") !== 0) {
      $safeData = false;
      $data = [$data];
    } else {
      if (!$data) {
        $data = json_encode([]);
      }

      $parsedData = json_decode($data, true);
      $data = is_array($parsedData) ? $parsedData : [$parsedData];
    }

    return $safeData ? \Leaf\Anchor::sanitize($data) : $data;
  }
mychidarko commented 2 years ago

I'll check out the issue @swimitup

mychidarko commented 2 years ago

This has been fixed @swimitup. We'll publish a new version real soon.