DEV Community

Aaron Junker
Aaron Junker

Posted on • Edited 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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay