Getting the physical path of a temporary PHP file

Published on 2021-07-25 • Modified on 2021-07-25

In this snippet, we see how to get the physical path of a temporary PHP file. In this case, we use the tmpfile() function to create it. This function returns a resource object. We can use the stream_get_meta_data() function to retrieve all the metadata associated with it. In the case of a file the uri key returns the full file path.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet156Trait
{
    public function snippet156(): void
    {
        $tmpFileResource = tmpfile();
        if (!\is_resource($tmpFileResource)) {
            throw new \RuntimeException('Unable to create a temporary file.');
        }

        $meta = stream_get_meta_data($tmpFileResource);
        $path = $meta['uri'];

        // Here, we are sure the uri key if the $path variable is defined and contains
        // a string that's why PHPStan throws a warning if we do this kind of test
        // if (!is_string($path)) {
        // 29     Call to function is_string() with string will always evaluate to true.
        // Excellent!

        echo pathinfo($path, PATHINFO_FILENAME); // avoid using pathinfo($path)['filename']

        fclose($tmpFileResource);

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  Random snippet

  Work with me!