Table des matières

Upload de fichier en PHP

Notes :

Quelques fonctions utilitaires liées à l'envoi de fichier via un formulaire avec <input type="file">.

public static function getFileUploadMaxSize() {
    $upload_max_filesize = ini_get('upload_max_filesize');
    $upload_max_filesize_bytes = self::sizeStringToByte($upload_max_filesize);
 
    $post_max_size = ini_get('post_max_size');
    $post_max_size_bytes = self::sizeStringToByte($post_max_size);
 
    if($upload_max_filesize_bytes < $post_max_size_bytes) {
        return $upload_max_filesize;
    } else {
        return $post_max_size;
    }
}
 
public static function sizeStringToByte($string) {
    $size = (float)mb_substr($string, 0, -1);
    $unit = mb_strtolower(mb_substr($string, -1));
 
    return (int)round($size * pow(1024, strpos('bkmgtpezy', $unit)));
}
 
public static function sizeByteToString($bytes) {
    $units = 'bkmgtpezy';
    $value = $bytes;
    while ($value > 1024 && $unit_rank < 8) {
        $value / 1024;
        $unit_rank++;
    }
 
    return round($value, 2).$units[$unit_rank]);
}