diff --git a/core/lib/Drupal/Component/PhpStorage/MTimeProtectedFastFileStorage.php b/core/lib/Drupal/Component/PhpStorage/MTimeProtectedFastFileStorage.php
index 3e660a0a724e8a719f92464006abbc92029b7500..ff1286baf9a1e0494e2c5e16566c4e9494390cd9 100644
--- a/core/lib/Drupal/Component/PhpStorage/MTimeProtectedFastFileStorage.php
+++ b/core/lib/Drupal/Component/PhpStorage/MTimeProtectedFastFileStorage.php
@@ -152,6 +152,14 @@ protected function getFullPath($name, &$directory = NULL, &$directory_mtime = NU
    * Returns the full path of the containing directory where the file is or should be stored.
    */
   protected function getContainingDirectoryFullPath($name) {
+    // Remove the .php file extension from the directory name.
+    // Within a single directory, a subdirectory cannot have the same name as a
+    // file. Thus, when switching between MTimeProtectedFastFileStorage and
+    // FileStorage, the subdirectory or the file cannot be created in case the
+    // other file type exists already.
+    if (substr($name, -4) === '.php') {
+      $name = substr($name, 0, -4);
+    }
     return $this->directory . '/' . str_replace('/', '#', $name);
   }
 
diff --git a/core/tests/Drupal/Tests/Component/PhpStorage/MTimeProtectedFileStorageBase.php b/core/tests/Drupal/Tests/Component/PhpStorage/MTimeProtectedFileStorageBase.php
index 062b857da622af277f913634549a4b952c80f7a1..46387fbf4a568e6d7179f4926c00268008400224 100644
--- a/core/tests/Drupal/Tests/Component/PhpStorage/MTimeProtectedFileStorageBase.php
+++ b/core/tests/Drupal/Tests/Component/PhpStorage/MTimeProtectedFileStorageBase.php
@@ -66,7 +66,12 @@ public function testSecurity() {
     $name = 'simpletest.php';
     $php->save($name, '<?php');
     $expected_root_directory = sys_get_temp_dir() . '/php/simpletest';
-    $expected_directory = $expected_root_directory . '/' . $name;
+    if (substr($name, -4) === '.php') {
+      $expected_directory = $expected_root_directory . '/' . substr($name, 0, -4);
+    }
+    else {
+      $expected_directory = $expected_root_directory . '/' . $name;
+    }
     $directory_mtime = filemtime($expected_directory);
     $expected_filename = $expected_directory . '/' . hash_hmac('sha256', $name, $this->secret . $directory_mtime) . '.php';