Browse Source

Implement a warning for large cookies

Florian Krämer 8 years ago
parent
commit
1f92036673

+ 10 - 1
src/Http/Cookie/CookieCollection.php

@@ -223,8 +223,17 @@ class CookieCollection implements IteratorAggregate, Countable
         $cookies = array_merge($cookies, $extraCookies);
         $cookiePairs = [];
         foreach ($cookies as $key => $value) {
-            $cookiePairs[] = sprintf("%s=%s", rawurlencode($key), rawurlencode($value));
+            $cookie = sprintf("%s=%s", rawurlencode($key), rawurlencode($value));
+            $size = mb_strlen($cookie);
+            if ($size > 4096) {
+                triggerWarning(sprintf(
+                    'The cookie `%s` exceeds the recommended maximum cookie length of 4096 bytes.',
+                    $key
+                ));
+            }
+            $cookiePairs[] = $cookie;
         }
+
         if (empty($cookiePairs)) {
             return $request;
         }

+ 16 - 0
tests/TestCase/Http/Cookie/CookieCollectionTest.php

@@ -374,6 +374,22 @@ class CookieCollectionTest extends TestCase
     }
 
     /**
+     * Testing the cookie size limit warning
+     *
+     * @expectedException \PHPUnit\Framework\Error\Warning
+     * @expectedExceptionMessage The cookie `default` exceeds the recommended maximum cookie length of 4096 bytes.
+     * @return void
+     */
+    public function testCookieSizeWarning()
+    {
+        $collection = new CookieCollection();
+        $collection = $collection
+            ->add(new Cookie('default', random_bytes(9000), null, '/', 'example.com'));
+        $request = new ClientRequest('http://example.com/api');
+        $collection->addToRequest($request);
+    }
+
+    /**
      * Test adding cookies from the collection to request.
      *
      * @return void