Magento 2 How To Fix Media Directory Trim PHP8.1 Deprecated And Apply m2-hotfixes

As of Magento 2.4.4, the system requirement has been changed from PHP7.4 to PHP8.1. However, not all of Magento 2 core code has been fully compatible with PHP8.1. There are various of incompatibility, but currently we want to share one of the instance faced by the community as seen on this post.

The error is like this:

trim(): Passing null to parameter #1 ($string) of type string is deprecated in /app/vendor/magento/module-media-storage/App/Media.php on line 151

 You can try to extend and replace the problematic line on your custom extension or you can apply this patch: (do not forget to copy the new line after the last line of code)

diff --git a/vendor/magento/module-media-storage/App/Media.php b/vendor/magento/module-media-storage/App/Media.php
index b98dc8ef41e..bc0ac5e56d6 100644
--- a/vendor/magento/module-media-storage/App/Media.php
+++ b/vendor/magento/module-media-storage/App/Media.php
@@ -148,7 +148,7 @@ class Media implements AppInterface
             DirectoryList::MEDIA,
             Filesystem\DriverPool::FILE
         );
-        $mediaDirectory = trim($mediaDirectory);
+        $mediaDirectory = $mediaDirectory === null ? '' : trim($mediaDirectory);
         if (!empty($mediaDirectory)) {
             // phpcs:ignore Magento2.Functions.DiscouragedFunction
             $this->mediaDirectoryPath = str_replace('\\', '/', $file->getRealPath($mediaDirectory));

Do the followings to apply the patches:

  1. In Magento 2 root folder, if you do not have a folder named "m2-hotfixes", create one.
  2. Save the above patch source code in a file (e.g. media-trim_2.4.4.patch and put it on folder m2-hotfixes
  3. apply patches by running this script:
<magento_root>/vendor/bin/ece-patches apply

From our observation this error happens when someone (or bot) is accessing an non-existing images and triggers server PHP error.
With the same idea as the above, by checking the variable first before trimming it, you can fix the incompatibility issue of Magento 2.4.4 with PHP8.1