/    Sign up×
Community /Pin to ProfileBookmark

File Upload Error

My Php Buddies,

I am building a script where only video file uploading is allowed and the max size limit is 1MB.
Do have a look at the following code of mine and tell me which lines to fix substituting with what code from you.

I got 2 issues.
ISSUE 1: If I try uploading the same file then I should get error:

[code]
$Errors[] = “Error: You have already uploaded a video file to verify your ID!”;
[/code]

But, I do not get the error. Why is that ?
Code snippet is this:

[code]
//Grab Uploading File Extension details.
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
if(file_exists(“$directory_path . $user/ . $file_name”)) //THIS LINE IS NOT GIVING THE ERROR THAT FILE HAS ALREADY BEEN UPLOADED. INSTEAD GIVES THE ECHO THAT IS 26 LINES BELOW HERE: “Your Video File “$file_name” has been uploaded successfully!”
//if(file_exists($directory_path . $user . ‘/’ . $file_name)) //THIS LINE IS NOT GIVING THE ERROR THAT FILE HAS ALREADY BEEN UPLOADED. INSTEAD SHOWING BLANK WHITE PAGE.
{
$Errors[] = “Error: You have already uploaded a video file to verify your ID!”;
exit();
}
[/code]

ISSUE 2: When I upload a file over 1MB max limit, I do not get the error as supposed to. Snippet looks like this:

[code]
//Verify File Extension.
if(!array_key_exists($file_extension, $allowed_file_extensions)) die(“Error: Select a valid video file format. Select an Mp4 file.”);
//Verify MIME Type of the File.
elseif(!in_array($file_type, $allowed_file_extensions))
{
$Errors[] = “Error: There was a problem uploading your file $file_name! Make sure your file is an MP4 video file. You may try again.”; //IS THIS LINE CORRECT ?
}
//Verify File Size. Allowed Max Limit: 1MB.
elseif($file_size>$max_file_size_allowed) die(“Error: Your Video File Size is larger than the allowed limit of: $max_file_size_allowed_in_megabytes.”);
//Move uploaded File to newly created directory on the server.
move_uploaded_file(“$file_tmp”, “$directory_path” . “$user/” . “$file_name”); //IS THIS LINE CORRECT ?
//Notify user their Id Verification Video File was uploaded successfully.
echo “Your Video File “$file_name” has been uploaded successfully!”;
exit();
[/code]

QUESTION 3:
I need to know if the following 2 lines are correct or not. If not, then how should they be ?
Check the comment lines:

[code]
//Feed Id Verification Video File Upload Directory path.
$directory_path = “uploads/videos/id_verifications/”;
//Make Directory under $user in ‘uploads/videos/id_verifications’ Folder.
if(!is_dir($directory_path . $user)) //IS THIS LINE CORRECT ?
{
$mode = “0777”;
mkdir($directory_path . $user, “$mode”, TRUE); //IS THIS LINE CORRECT ?
}
[/code]

The full script is:

[code]
<?php
//Required PHP Files.
include ‘header_account.php’; //Required on all webpages of the Site.
?>

<?php

if (!$conn)
{
$error = mysqli_connect_error();
$errno = mysqli_connect_errno();
print “$errno: $errorn”;
exit();
}

if($_SERVER[“REQUEST_METHOD”] == “POST”)
{
//Check whether the file was uploaded or not without any errors.
if(!isset($_FILES[“id_verification_video_file”]) && $_FILES[“id_verification_video_file”][“Error”] == 0)
{
$Errors = Array();
$Errors[] = “Error: ” . $_FILES[“id_verification_video_file”] [“ERROR”];
print_r($_FILES); ?><br><?php
print_r($_ERRORS);
exit();
}
else
{
//Feed Id Verification Video File Upload Directory path.
$directory_path = “uploads/videos/id_verifications/”;
//Make Directory under $user in ‘uploads/videos/id_verifications’ Folder.
if(!is_dir($directory_path . $user)) //IS THIS LINE CORRECT ?
{
$mode = “0777”;
mkdir($directory_path . $user, “$mode”, TRUE); //IS THIS LINE CORRECT ?
}

//Grab Uploading File details.
$Errors = Array(); //SHOULD I KEEP THIS LINE OR NOT ?
$file_name = $_FILES[“id_verification_video_file”][“name”];
$file_tmp = $_FILES[“id_verification_video_file”][“tmp_name”];
$file_type = $_FILES[“id_verification_video_file”][“type”];
$file_size = $_FILES[“id_verification_video_file”][“size”];
$file_error = $_FILES[‘id_verification_video_file’][‘error’];

//Grab Uploading File Extension details.
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
if(file_exists(“$directory_path . $user/ . $file_name”)) //THIS LINE IS NOT GIVING THE ERROR THAT FILE HAS ALREADY BEEN UPLOADED. INSTEAD GIVES THE ECHO THAT IS 26 LINES BELOW HERE: “Your Video File “$file_name” has been uploaded successfully!”
//if(file_exists($directory_path . $user . ‘/’ . $file_name)) //THIS LINE IS NOT GIVING THE ERROR THAT FILE HAS ALREADY BEEN UPLOADED. INSTEAD SHOWING BLANK WHITE PAGE.
{
$Errors[] = “Error: You have already uploaded a video file to verify your ID!”;
exit();
}
else
{
//Feed allowed File Extensions List.
$allowed_file_extensions = array(“mp4” => “video/mp4”);

//Feed allowed File Size.
$max_file_size_allowed_in_bytes = 1024*1024*1; //Allowed limit: 100MB.
$max_file_size_allowed_in_kilobytes = 1024*1;
$max_file_size_allowed_in_megabytes = 1;

$max_file_size_allowed = “$max_file_size_allowed_in_bytes”;

//Verify File Extension.
if(!array_key_exists($file_extension, $allowed_file_extensions)) die(“Error: Select a valid video file format. Select an Mp4 file.”);
//Verify MIME Type of the File.
elseif(!in_array($file_type, $allowed_file_extensions))
{
$Errors[] = “Error: There was a problem uploading your file $file_name! Make sure your file is an MP4 video file. You may try again.”; //IS THIS LINE CORRECT ?
}
//Verify File Size. Allowed Max Limit: 1MB.
elseif($file_size>$max_file_size_allowed) die(“Error: Your Video File Size is larger than the allowed limit of: $max_file_size_allowed_in_megabytes.”);
//Move uploaded File to newly created directory on the server.
move_uploaded_file(“$file_tmp”, “$directory_path” . “$user/” . “$file_name”); //IS THIS LINE CORRECT ?
//Notify user their Id Verification Video File was uploaded successfully.
echo “Your Video File “$file_name” has been uploaded successfully!”;
exit();
}
}
}
?>

<form METHOD=”POST” ACTION=”” enctype=”multipart/form-data”>
<fieldset>
<p align=”left”><h3><?php $site_name ?> ID Video Verification Form</h3></p>
<div class=”form-group”>
<p align=”left”<label>Video File: </label>
<input type=”file” name=”id_verification_video_file” id=”id_verification_video_file” value=”uploaded ‘Id Verification Video File.'”></p>
</div>
</fieldset>
<p align=”left”><button type=”submit” class=”btn btn-default” name=”id_verification_video_file_submit”>Submit!</button></p>
</form>

</body>
</html>

<?php
include ‘footer_account.php’; //Required on all webpages of the Site.
?>

[/code]

I need you good peoples’ immediate attention on this.
Someone told me to try fileinfo() or finfo(). Can’t remember. She said that is more reliable. I don’t have access to her any more. And so, someone be kind enough to fix my code with fileinfo() or finfo() or whatever and show the code here so that I can learn from you ?
root ? nogdog ? ginerjm ? Anyone ?
Was not much help:
http://php.net/manual/en/function.finfo-file.php

Thanks!

to post a comment
PHP

10 Comments(s)

Copy linkTweet thisAlerts:
@site-developerauthorFeb 21.2019 — I am experimenting with the sample code found on this tutorial:

https://www.sanisoft.com/blog/2010/05/17/how-to-use-php-fileinfo-extension-to-get-file-mime-type/
Copy linkTweet thisAlerts:
@site-developerauthorFeb 26.2019 — No one knows the answer ?

This issue is frustrating me like hell! No way round it! How-about you ?
Copy linkTweet thisAlerts:
@ginerjmFeb 26.2019 — When you find the problematic section of code that you want help with I think we would be more than happy to help if we could only see it....
Copy linkTweet thisAlerts:
@rootFeb 27.2019 — PROBLEM No.

#1 - YOU post too many subjects at once

#2 - despite being told from the outset, you post the whole code and not the part you are having issues with, as in the PHP that is causing the error, if its a form, then the section of the code for the HTML that it relates to.

#3 - IF you must provide a full listing, UPLOAD as an attachment as a .txt file type so that people can see the whole code if they need to.

When you plaster (shotgun approach) the same code several times and you have 3 or 4 different problems, chances are they are the same issue but you have not read the error message or looked it up.

You might learn more by simply employing your search engine more often to look up errors.

APPROACH each error in turn, first by seeking out syntax and typo errors.

Retry code and get NEW errors and maybe same errors, who knows... the point is that you can often solve problems and learn at the same time and learning to troubleshoot is a skill you have to learn and how to resolve, it is part and parcel of programming and one that you need to concentrate more on.

I haven't bothered to go over the posts but I am going to hazard a guess that the biggest part of your coding issues is a combination of not understanding PHP and HTML and JavaScript and how they all interact and have to be utilised and a persistent failing to resolve typos and syntax.

You learn the basics, it holds true for many other languages on their structure and naming conventions, it pays to spend an hour doing that rather than continuing the way you are.

The appropriate analogy is You're trying to run and you'r still a toddler which is where we all start from, wanting to run, it doesn't work like that, to learn faster, it helps to understand the rules first.

So help people here to help you by only posting ONE post and resolve that problem before wanting 20 other things resolved.

ALSO REMEMBER THAT THIS IS NOT A FREE CODE SITE.

People are not obligated to help you, just because you got no answer does not mean that people didn't look, think OMG that too much and left. Ever thought that your posts are putting people off?

You can improve your chances of a response ten fold by only posting as requested, one problem at a time, snippets and upload the whole code as a .txt file.

Good Luck.
Copy linkTweet thisAlerts:
@ginerjmFeb 27.2019 — > @root#1601292 So help people here to help you by only posting ONE post and resolve that problem before wanting 20 other things resolved.
>
> ALSO REMEMBER THAT THIS IS NOT A FREE CODE SITE.
>
> People are not obligated to help you, just because you got no answer does not mean that people didn't look, think OMG that too much and left. Ever thought that your posts are putting people off?
>
> You can improve your chances of a response ten fold by only posting as requested, one problem at a time, snippets and upload the whole code as a .txt file.


What a great Post from Root!!! I agree wholeheartedly. If only the OP reads and comprehends this better than he reads our attempts to help him with his posted problems.....
Copy linkTweet thisAlerts:
@site-developerauthorMar 14.2019 — @ginerjm#1601302

Well,I just read it now after 16 days and gonna test and see if you lot stick by your word. Here goes in this forum .....
Copy linkTweet thisAlerts:
@site-developerauthorMar 14.2019 — My Php Buddies!

I found 30 code samples and are only listing 15 here that do not seem scary to me. Meaning not too hard to learn with your help.

https://hotexamples.com/examples/-/-/finfo_file/php-finfo_file-function-examples.html

I have a few questions for you:

  • 1. Out of these 15, which samples you deem suitable to learn for a beginner and which one for an intermediate ?

  • 2. Can you rank these 15 where your most favourite is on the top and your least favourite on the bottom ?

    That way, I can decide which ones to seriously look into to try to learn from. And then give your reasons why you ranked them the way you did.

  • 3. Anything else I should know ?

    Seriously! I am spoiled for choice. Which one should I learn from ? The code must be foolproof so uploaders cannot upload viruses. I was told to learn the finfo() function use as it is foolproof and can detect file types.

    My pals, nogdog, root, jinergm!


  • Sample 1:

    <i>
    </i> function mime_type($file_path)
    {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime_type = finfo_file($finfo, $file_path);
    finfo_close($finfo);
    return $mime_type;
    }


    Sample 2
    <i>
    </i> /**
    * @return string
    */
    public function getContentType()
    {
    if (is_null($this-&gt;content_type)) {
    $this-&gt;content_type = finfo_file(finfo_open(FILEINFO_MIME_TYPE), $this-&gt;getFullPath());
    }
    return $this-&gt;content_type;
    }


    Sample 3
    <i>
    </i>function getMIME($fname)
    {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $fname);
    finfo_close($finfo);
    return $mime;
    }


    Sample 4
    <i>
    </i>public function getType()
    {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $type = finfo_file($finfo, $this-&gt;getFullPath());
    finfo_close($finfo);
    return $type;
    }


    Sample 5
    <i>
    </i>function mime_content_type($filename)
    {
    $finfo = finfo_open(FILEINFO_MIME);
    $mimetype = finfo_file($finfo, $filename);
    finfo_close($finfo);
    return $mimetype;
    }


    Sample 6
    <i>
    </i>function getUploadedFile($name)
    {
    $tmp_name = $_FILES[$name]['tmp_name'];
    $info = finfo_open(FILEINFO_MIME_TYPE);
    $mime_type = finfo_file($info, $tmp_name);
    finfo_close($info);
    $extension = '';
    switch ($mime_type) {
    case 'image/jpeg':
    $extension = 'jpg';
    break;
    case 'image/gif':
    $extension = 'gif';
    break;
    case 'image/png':
    $extension = 'png';
    break;
    default:
    $extension = '';
    }
    if ($extension != '') {
    $image_name = pathinfo($_FILES[$name]['name'])['filename'] . '.' . $extension;
    $image_file = 'img-uploads/' . $image_name;
    try {
    move_uploaded_file($tmp_name, $image_file);
    } catch (Exception $e) {
    print_r($e);
    }
    }
    return $image_name;
    }


    Sample 7
    <i>
    </i>/**
    * @param string $file
    * @return FileAnalysisResult
    */
    public static function analyse($file)
    {
    //check if file exists
    if (false === file_exists($file)) {
    return null;
    }
    //is not a file
    if (false === is_file($file)) {
    return null;
    }
    //get file size
    $size = filesize($file);
    $mimeType = null;
    //mime type getter
    if (function_exists('finfo_open')) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mimeType = finfo_file($finfo, $file);
    } else {
    if (function_exists('mime_content_type')) {
    $mimeType = mime_content_type($file);
    }
    }
    //default mime type
    if (strlen($mimeType) == 0) {
    //default mime type
    $mimeType = 'application/octet-stream';
    }
    return new FileAnalysisResult($mimeType, $size, $file);
    }


    Sample 8
    <i>
    </i> /**
    * Detects the MIME type of a given file
    * @param string $fileName The full path to the name whose MIME type you want to find out
    * @return string The MIME type, e.g. image/jpeg
    */
    static function getMimeType($fileName)
    {
    $mime = null;
    // Try fileinfo first
    if (function_exists('finfo_open')) {
    $finfo = finfo_open(FILEINFO_MIME);
    if ($finfo !== false) {
    $mime = finfo_file($finfo, $fileName);
    finfo_close($finfo);
    }
    }
    // Fallback to mime_content_type() if finfo didn't work
    if (is_null($mime) &amp;&amp; function_exists('mime_content_type')) {
    $mime = mime_content_type($fileName);
    }
    // Final fallback, detection based on extension
    if (is_null($mime)) {
    $extension = self::getTypeIcon(getTypeIcon);
    if (array_key_exists($extension, self::$mimeMap)) {
    $mime = self::$mimeMap[$extension];
    } else {
    $mime = "application/octet-stream";
    }
    }
    return $mime;
    }


    Sample 9
    <i>
    </i> private function fileMimeType($filePath)
    {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $type = finfo_file($finfo, $filePath);
    finfo_close($finfo);
    return $type;
    }


    Sample 10
    <i>
    </i>function get_file_mime_type($filename, $debug = false)
    {
    if (function_exists('finfo_open') &amp;&amp; function_exists('finfo_file') &amp;&amp; function_exists('finfo_close')) {
    $fileinfo = finfo_open(FILEINFO_MIME);
    $mime_type = finfo_file($fileinfo, $filename);
    finfo_close($fileinfo);
    if (!empty($mime_type)) {
    if (true === $debug) {
    return array('mime_type' =&gt; $mime_type, 'method' =&gt; 'fileinfo');
    }
    return $mime_type;
    }
    }
    if (function_exists('mime_content_type')) {
    $mime_type = mime_content_type($filename);
    if (!empty($mime_type)) {
    if (true === $debug) {
    return array('mime_type' =&gt; $mime_type, 'method' =&gt; 'mime_content_type');
    }
    return $mime_type;
    }
    }
    $mime_types = array('ai' =&gt; 'application/postscript', 'aif' =&gt; 'audio/x-aiff', 'aifc' =&gt; 'audio/x-aiff', 'aiff' =&gt; 'audio/x-aiff', 'asc' =&gt; 'text/plain', 'asf' =&gt; 'video/x-ms-asf', 'asx' =&gt; 'video/x-ms-asf', 'au' =&gt; 'audio/basic', 'avi' =&gt; 'video/x-msvideo', 'bcpio' =&gt; 'application/x-bcpio', 'bin' =&gt; 'application/octet-stream', 'bmp' =&gt; 'image/bmp', 'bz2' =&gt; 'application/x-bzip2', 'cdf' =&gt; 'application/x-netcdf', 'chrt' =&gt; 'application/x-kchart', 'class' =&gt; 'application/octet-stream', 'cpio' =&gt; 'application/x-cpio', 'cpt' =&gt; 'application/mac-compactpro', 'csh' =&gt; 'application/x-csh', 'css' =&gt; 'text/css', 'dcr' =&gt; 'application/x-director', 'dir' =&gt; 'application/x-director', 'djv' =&gt; 'image/vnd.djvu', 'djvu' =&gt; 'image/vnd.djvu', 'dll' =&gt; 'application/octet-stream', 'dms' =&gt; 'application/octet-stream', 'doc' =&gt; 'application/msword', 'dvi' =&gt; 'application/x-dvi', 'dxr' =&gt; 'application/x-director', 'eps' =&gt; 'application/postscript', 'etx' =&gt; 'text/x-setext', 'exe' =&gt; 'application/octet-stream', 'ez' =&gt; 'application/andrew-inset', 'flv' =&gt; 'video/x-flv', 'gif' =&gt; 'image/gif', 'gtar' =&gt; 'application/x-gtar', 'gz' =&gt; 'application/x-gzip', 'hdf' =&gt; 'application/x-hdf', 'hqx' =&gt; 'application/mac-binhex40', 'htm' =&gt; 'text/html', 'html' =&gt; 'text/html', 'ice' =&gt; 'x-conference/x-cooltalk', 'ief' =&gt; 'image/ief', 'iges' =&gt; 'model/iges', 'igs' =&gt; 'model/iges', 'img' =&gt; 'application/octet-stream', 'iso' =&gt; 'application/octet-stream', 'jad' =&gt; 'text/vnd.sun.j2me.app-descriptor', 'jar' =&gt; 'application/x-java-archive', 'jnlp' =&gt; 'application/x-java-jnlp-file', 'jpe' =&gt; 'image/jpeg', 'jpeg' =&gt; 'image/jpeg', 'jpg' =&gt; 'image/jpeg', 'js' =&gt; 'application/x-javascript', 'kar' =&gt; 'audio/midi', 'kil' =&gt; 'application/x-killustrator', 'kpr' =&gt; 'application/x-kpresenter', 'kpt' =&gt; 'application/x-kpresenter', 'ksp' =&gt; 'application/x-kspread', 'kwd' =&gt; 'application/x-kword', 'kwt' =&gt; 'application/x-kword', 'latex' =&gt; 'application/x-latex', 'lha' =&gt; 'application/octet-stream', 'lzh' =&gt; 'application/octet-stream', 'm3u' =&gt; 'audio/x-mpegurl', 'man' =&gt; 'application/x-troff-man', 'me' =&gt; 'application/x-troff-me', 'mesh' =&gt; 'model/mesh', 'mid' =&gt; 'audio/midi', 'midi' =&gt; 'audio/midi', 'mif' =&gt; 'application/vnd.mif', 'mov' =&gt; 'video/quicktime', 'movie' =&gt; 'video/x-sgi-movie', 'mp2' =&gt; 'audio/mpeg', 'mp3' =&gt; 'audio/mpeg', 'mpe' =&gt; 'video/mpeg', 'mpeg' =&gt; 'video/mpeg', 'mpg' =&gt; 'video/mpeg', 'mpga' =&gt; 'audio/mpeg', 'ms' =&gt; 'application/x-troff-ms', 'msh' =&gt; 'model/mesh', 'mxu' =&gt; 'video/vnd.mpegurl', 'nc' =&gt; 'application/x-netcdf', 'odb' =&gt; 'application/vnd.oasis.opendocument.database', 'odc' =&gt; 'application/vnd.oasis.opendocument.chart', 'odf' =&gt; 'application/vnd.oasis.opendocument.formula', 'odg' =&gt; 'application/vnd.oasis.opendocument.graphics', 'odi' =&gt; 'application/vnd.oasis.opendocument.image', 'odm' =&gt; 'application/vnd.oasis.opendocument.text-master', 'odp' =&gt; 'application/vnd.oasis.opendocument.presentation', 'ods' =&gt; 'application/vnd.oasis.opendocument.spreadsheet', 'odt' =&gt; 'application/vnd.oasis.opendocument.text', 'ogg' =&gt; 'application/ogg', 'otg' =&gt; 'application/vnd.oasis.opendocument.graphics-template', 'oth' =&gt; 'application/vnd.oasis.opendocument.text-web', 'otp' =&gt; 'application/vnd.oasis.opendocument.presentation-template', 'ots' =&gt; 'application/vnd.oasis.opendocument.spreadsheet-template', 'ott' =&gt; 'application/vnd.oasis.opendocument.text-template', 'pbm' =&gt; 'image/x-portable-bitmap', 'pdb' =&gt; 'chemical/x-pdb', 'pdf' =&gt; 'application/pdf', 'pgm' =&gt; 'image/x-portable-graymap', 'pgn' =&gt; 'application/x-chess-pgn', 'png' =&gt; 'image/png', 'pnm' =&gt; 'image/x-portable-anymap', 'ppm' =&gt; 'image/x-portable-pixmap', 'ppt' =&gt; 'application/vnd.ms-powerpoint', 'ps' =&gt; 'application/postscript', 'qt' =&gt; 'video/quicktime', 'ra' =&gt; 'audio/x-realaudio', 'ram' =&gt; 'audio/x-pn-realaudio', 'ras' =&gt; 'image/x-cmu-raster', 'rgb' =&gt; 'image/x-rgb', 'rm' =&gt; 'audio/x-pn-realaudio', 'roff' =&gt; 'application/x-troff', 'rpm' =&gt; 'application/x-rpm', 'rtf' =&gt; 'text/rtf', 'rtx' =&gt; 'text/richtext', 'sgm' =&gt; 'text/sgml', 'sgml' =&gt; 'text/sgml', 'sh' =&gt; 'application/x-sh', 'shar' =&gt; 'application/x-shar', 'silo' =&gt; 'model/mesh', 'sis' =&gt; 'application/vnd.symbian.install', 'sit' =&gt; 'application/x-stuffit', 'skd' =&gt; 'application/x-koan', 'skm' =&gt; 'application/x-koan', 'skp' =&gt; 'application/x-koan', 'skt' =&gt; 'application/x-koan', 'smi' =&gt; 'application/smil', 'smil' =&gt; 'application/smil', 'snd' =&gt; 'audio/basic', 'so' =&gt; 'application/octet-stream', 'spl' =&gt; 'application/x-futuresplash', 'src' =&gt; 'application/x-wais-source', 'stc' =&gt; 'application/vnd.sun.xml.calc.template', 'std' =&gt; 'application/vnd.sun.xml.draw.template', 'sti' =&gt; 'application/vnd.sun.xml.impress.template', 'stw' =&gt; 'application/vnd.sun.xml.writer.template', 'sv4cpio' =&gt; 'application/x-sv4cpio', 'sv4crc' =&gt; 'application/x-sv4crc', 'swf' =&gt; 'application/x-shockwave-flash', 'sxc' =&gt; 'application/vnd.sun.xml.calc', 'sxd' =&gt; 'application/vnd.sun.xml.draw', 'sxg' =&gt; 'application/vnd.sun.xml.writer.global', 'sxi' =&gt; 'application/vnd.sun.xml.impress', 'sxm' =&gt; 'application/vnd.sun.xml.math', 'sxw' =&gt; 'application/vnd.sun.xml.writer', 't' =&gt; 'application/x-troff', 'tar' =&gt; 'application/x-tar', 'tcl' =&gt; 'application/x-tcl', 'tex' =&gt; 'application/x-tex', 'texi' =&gt; 'application/x-texinfo', 'texinfo' =&gt; 'application/x-texinfo', 'tgz' =&gt; 'application/x-gzip', 'tif' =&gt; 'image/tiff', 'tiff' =&gt; 'image/tiff', 'torrent' =&gt; 'application/x-bittorrent', 'tr' =&gt; 'application/x-troff', 'tsv' =&gt; 'text/tab-separated-values', 'txt' =&gt; 'text/plain', 'ustar' =&gt; 'application/x-ustar', 'vcd' =&gt; 'application/x-cdlink', 'vrml' =&gt; 'model/vrml', 'wav' =&gt; 'audio/x-wav', 'wax' =&gt; 'audio/x-ms-wax', 'wbmp' =&gt; 'image/vnd.wap.wbmp', 'wbxml' =&gt; 'application/vnd.wap.wbxml', 'wm' =&gt; 'video/x-ms-wm', 'wma' =&gt; 'audio/x-ms-wma', 'wml' =&gt; 'text/vnd.wap.wml', 'wmlc' =&gt; 'application/vnd.wap.wmlc', 'wmls' =&gt; 'text/vnd.wap.wmlscript', 'wmlsc' =&gt; 'application/vnd.wap.wmlscriptc', 'wmv' =&gt; 'video/x-ms-wmv', 'wmx' =&gt; 'video/x-ms-wmx', 'wrl' =&gt; 'model/vrml', 'wvx' =&gt; 'video/x-ms-wvx', 'xbm' =&gt; 'image/x-xbitmap', 'xht' =&gt; 'application/xhtml+xml', 'xhtml' =&gt; 'application/xhtml+xml', 'xls' =&gt; 'application/vnd.ms-excel', 'xml' =&gt; 'text/xml', 'xpm' =&gt; 'image/x-xpixmap', 'xsl' =&gt; 'text/xml', 'xwd' =&gt; 'image/x-xwindowdump', 'xyz' =&gt; 'chemical/x-xyz', 'zip' =&gt; 'application/zip');
    $ext = strtolower(array_pop(explode('.', $filename)));
    if (!empty($mime_types[$ext])) {
    if (true === $debug) {
    return array('mime_type' =&gt; $mime_types[$ext], 'method' =&gt; 'from_array');
    }
    return $mime_types[$ext];
    }
    if (true === $debug) {
    return array('mime_type' =&gt; 'application/octet-stream', 'method' =&gt; 'last_resort');
    }
    return 'application/octet-stream';
    }


    Sample 11
    <i>
    </i> /**
    * 获取文件的mime-type
    * @param string $file
    */
    public static function getMimeType($file)
    {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $type = finfo_file($finfo, $file);
    finfo_close($finfo);
    return $type;
    }


    Sample 12
    <i>
    </i>/**
    * Returns (if possible) the mimetype of the given file
    *
    * @param string $file
    * @param array $options
    */
    public function mime($file, $options = array())
    {
    $file = realpath($file);
    $options = array_merge(array('default' =&gt; null, 'extension' =&gt; strtolower(pathinfo($file, PATHINFO_EXTENSION))), $options);
    $mime = null;
    if (function_exists('finfo_open') &amp;&amp; ($f = finfo_open(FILEINFO_MIME, getenv('MAGIC')))) {
    $mime = finfo_file($f, $file);
    finfo_close($f);
    }
    if (!$mime &amp;&amp; in_array($options['extension'], array('gif', 'jpg', 'jpeg', 'png'))) {
    $image = getimagesize($file);
    if (!empty($image['mime'])) {
    $mime = $image['mime'];
    }
    }
    if (!$mime &amp;&amp; $options['default']) {
    $mime = $options['default'];
    }
    if ((!$mime || $mime == 'application/octet-stream') &amp;&amp; $options['extension']) {
    static $mimes;
    if (!$mimes) {
    $mimes = parse_ini_file(pathinfo(__FILE__, PATHINFO_DIRNAME) . '/MimeTypes.ini');
    }
    if (!empty($mimes[$options['extension']])) {
    return $mimes[$options['extension']];
    }
    }
    return $mime;
    }


    Sample 13
    <i>
    </i>/**
    * @desc Retrieve the corresponding MIME type, if one exists
    * @param String $file File Name (relative location such as "image_test.jpg" or full "http://site.com/path/to/image_test.jpg")
    * @return String $MIMEType - The type of the file passed in the argument
    */
    public function getMimeType($file = NULL)
    {
    if (is_file($file)) {
    /**
    * Attempts to retrieve file info from FINFO
    * If FINFO functions are not available then try to retrieve MIME type from pre-defined MIMEs
    * If MIME type doesn't exist, then try (as a last resort) to use the (deprecated) mime_content_type function
    * If all else fails, just return application/octet-stream
    */
    if (!function_exists("finfo_open")) {
    $extension = $this-&gt;getExtension($file);
    if (array_key_exists($extension, $this-&gt;mimeTypes)) {
    return $this-&gt;mimeTypes[$extension];
    } else {
    if (function_exists("mime_content_type")) {
    $type = mime_content_type($file);
    return !empty($type) ? $type : "application/octet-stream";
    } else {
    return "application/octet-stream";
    }
    }
    } else {
    $finfo = finfo_open(FILEINFO_MIME);
    $MIMEType = finfo_file($finfo, $file);
    finfo_close($finfo);
    return $MIMEType;
    }
    } else {
    return "##INVALID_FILE##FILE=" . $file . "##";
    }
    }


    Sample 14
    <i>
    </i>public static function getMimetype($path)
    {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $path);
    finfo_close($finfo);
    return $mime;
    }


    Sample 15
    <i>
    </i> public function getMimeType($sourceFile)
    {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $sourceFile);
    finfo_close($finfo);
    return $mime;
    }
    Copy linkTweet thisAlerts:
    @site-developerauthorMar 14.2019 — I reckon sample 13 is best. The so-called "unlucky 13". What do you say, folks ?
    Copy linkTweet thisAlerts:
    @ginerjmMay 21.2019 — Two months later..... Take The Hint!
    ×

    Success!

    Help @site-developer spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 4.18,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,

    tipper: @Samric24,
    tipped: article
    amount: 1000 SATS,
    )...