DEV Community

Aaron Junker
Aaron Junker

Posted on • Updated on • Originally published at blog.aaron-junker.ch

Get temporary dictionary in PHP

Inspired by: https://bit.ly/2NaI8oN

If you want to get a temporary dictionary you could use sys_get_temp_dir(). But this doesn’t guarantee that you have write access to this dictionary. So, you can also get the upload_tmp_dir property from the php.ini file.

You can combine this for simplicity in a function:

<?php
    function get_temp():string{
        // Returns a temporary dictionary path.
        // When it can't find one, it returns false.
        if(is_writable(sys_get_temp_dir())){
            return sys_get_temp_dir();
        }elseif(is_writable(ini_get("upload_tmp_dir"))){
             return ini_get("upload_tmp_dir");
        }else{
            return false;
        }
    }
    echo get_temp();
?>
Enter fullscreen mode Exit fullscreen mode

Or the short form:

<?php
    function get_temp():string|bool{
        return is_writable(sys_get_temp_dir())?sys_get_temp_dir():(is_writable(ini_get("upload_tmp_dir"))?ini_get("upload_tmp_dir"):false);
    }
?>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)