Upload script won't upload video

This script successfully uploads IMAGES:

<?php
$target_dir = "../up/uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 5000000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

So, I wanted it to upload VIDEO files, so I changed it to this (without a successful outcome):

<?php
$target_dir = "../up/uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$videoFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is a video - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not a video.";
        $uploadOk = 0;
    }
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 5000000000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($videoFileType != "mp4" && $videoFileType != "mov" && $videoFileType != "flv" ) {
    echo "Sorry, only MP4, MOV & FLV files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

Any suggestions on how to suceed with this script to upload videos, will be appreciated:

It is possible that your server configuration is preventing it from uploading because it is too big. Try checking with phpinfo() and looking for max_upload_size and if it is too low increase the value on php.ini

1 Like

What are you trying to do? I donā€™t think a valid form of checking should be done like that. You would pull up the mime type from the file. Then compare the mime type with an array of desired mime types. If the mime type isnā€™t in the array, donā€™t allow the upload process to go any further. If the mime type is within the array, you can then proceed to upload the file. Also, getimagesize only works on image files. Other files that arenā€™t images will most likely return NULL or an empty result.

If you are using PHP 7, you can use the mime_content_type function. It was once deprecated in PHP 5, but it seems that the PHP team has brought it back. They probably rewrote it or probably mapped it to another function that checks for mime types.

1 Like

Here you go. I made a better approach and a less sloppy way of doing it. I also created a short Youtube video for you to see the results. In the video, I only showed the use with images. But the same can be done with videos since this snippet allows generic video formats like mp4, avi, and webm. You can modify it to use any kind of mime type that you desire.

<?php
// TESTED ONLY WITH PHP 7!!!!
// THIS SNIPPET MAY NOT WORK WITH OTHER VERSIONS OF PHP

// The proper way of checking if the form was submitted through POST
if($_SERVER['REQUEST_METHOD'] == 'POST') {

    $dir = 'uploads/'; // The directory the files should be stored in

    // Create an array of desired mime types.
    // Generally, mime types start with the category the file belongs in.
    // Then followed by either the extension or the actual type of file it is.
    // Here is a complete list of mime types if you are not familiar with them.
    // https://sitepoint.com/web-foundations/mime-types-complete-list/
    $array = array(
        'image/png',
        'image/jpg',
        'image/jpeg',
        'image/gif',
        'video/mp4',
        'video/webm',
        'video/avi',
        'video/mpeg',
    );

    // These are just the generic mime types for images and videos. If you want to allow other image formats and video formats, you'll need to add them into the array yourself.

    $name = $_FILES['fileToUpload']['name']; // Create the $name variable and append the name field to it.
    $tmp = $_FILES['fileToUpload']['tmp_name']; // Create the $tmp variable and append the tmp_name field to it.
    $size = $_FILES['fileToUpload']['size']; // Create the $size variable and append the size field to it.

    // Check the mime type of the file
    // Remember, mime_content_type won't work if the file is larger than the expected file size within your php.ini file.
    // mime_content_type will also not work if you are not running on PHP 7.
    // It was marked as deprecated and would complain when you used it.
    // An alternative is to use finfo_file()
    // The example usage can be found at http://php.net/manual/en/function.finfo-file.php
    $mime = mime_content_type($tmp);

    // Take the mime type of the temp file and check it against the array we created above.
    // We DO NOT want to take the "type" field from the default $_FILES[...]['type'] field,
    // Because this is not reliable and only contains the current mime type of the file extension.
    // It does not contain the original mime type that the file was created from.
    if(in_array($mime, $array)) {

        // In this if/else statement, we are checking to see if the file is an image or not.
        // Apparently, you are asking for less of a file size for images than for video files.
        // So we check to see if the image is larger than 5,000,000 bytes.
        // If the file is, tell the user that the file is too big.
        // If the file is not, proceed to uploading the file.

        // Again, this is just a few generic mime types for images.
        // If you want to allow other image formats, you'll have to add them in yourself.
        $imageType = array(
            'image/png',
            'image/jpg',
            'image/jpeg',
            'image/gif'
        );

        // Check for the very last period. This generally is the file extension.
        // We are doing this because we want to know the file extension of the file.
        // If the file has made it this far, we will assume that the file is either an image or a video.
        // So it's safe to use the file's old extension.
        // Normally, you wouldn't want to use the user's file extension and you would append your own.
        // But this is just a snippet to demonstrate that we can do this.
        $ext = substr(strrchr($name, '.'), 1);

        // Generate a hash using the current timestamp in Unix along with sha256.
        // You can generate the file name any way you'd like.
        // It doesn't have to be exactly like how everyone wants you to do it.
        $name = hash('sha256', time());

        // Combine the 3 variables ($dir, $name, $ext) together and append a period before the extension.
        // This will give you a random file name along with the original file extension. Like so.
        // 91f56c7596fdfaa1d0b64a0e9461eff5314dcca1cb51d2c8c89b830388d053f8.jpg
        // Or
        // c3e7d43db3d7be99d77112d8283cd3fff8f720ee6d8a2283b69c706493cbd003.mp4
        $file = $dir . $name . '.' . $ext;

        // Check to see if the mime content type of the temp file is an image.
        if(in_array($mime, $imageType)) {

            // Check to see if the image is larger than 5,000,000 bytes.
            if($size > 5000000) {

                print('Sorry, your file is too large.'); // Tell the user that their image size is too big.

            } else {

                // The image is just perfect so move the image to the upload directory along with
                // the new file name.
                if(move_uploaded_file($tmp, $file)) {

                    print('Good'); // A successful upload 'twas is.

                } else {

                    print('Bad upload'); // Hmm, looks like the upload was a failure.
                    // Check to make sure that the directory has the right permissions for you to
                    // Upload files to.
                    // Also, make sure that the directory you specified exists.

                }

            }

        } else {

            // The file was not an image based on the mime type.
            // We will assume it is a video if it gets this far.
            // Check to see if the video is larger than 5,000,000,000 bytes.
            if($size > 5000000000) {

                print('Sorry, your file is too large.');// Tell the user that their video size is too big.

            } else {

                // The video is just perfect so move the video to the upload directory along with
                // the new file name.
                if(move_uploaded_file($tmp, $file)) {

                    print('Good'); // A successful upload 'twas is.

                } else {

                    print('Bad upload'); // Hmm, looks like the upload was a failure.
                    // Check to make sure that the directory has the right permissions for you to
                    // Upload files to.
                    // Also, make sure that the directory you specified exists.

                }

            }

        }

    } else {

        print('Bad'); // It looks like the original mime type of the file does not meet our standards.

    }

} else {

    header('Location: /'); // Redirect the user back to whatever page they came from.
    // I would suggest changing this line if this current PHP file is located some where else
    // Or if the file used to target this current PHP file is named something different.

}

NOTE


SINCE THIS IS JUST A SAMPLE SNIPPET, THIS IS NOT PRODUCTION READY EVEN THOUGH IT HAS BEEN TESTED ON A DEVELOPMENT PHP 7. YOU SHOULD STILL DO MORE SECURITY CHECKS.


I AM NOT RESPONSIBLE FOR ANY ERRORS AFTER THIS POST. IF ANYONE HAPPENS TO MODIFY THIS WORKING SAMPLE SNIPPET AND RECEIVES ERRORS, DO NOT BLAME ME NOR THE SAMPLE SNIPPET FOR YOUR OWN MODIFICATIONS.

Thanks for that great effort. Much appreciated.
Iā€™m using PHP 5 unfortunately, but tried your code anyway and see:

Fatal error: Call to undefined function mime_content_type() ā€¦ on line 38
which is:

$mime = mime_content_type($tmp);

I really wouldnā€™t know how to integrate finfo_file, so, thanks anyway.

Looks good. One thing I would consider changing is the hard-coded 5000000000 to ini_get('post_max_size')

As for getting it to be backwards compatible for a soon to be completely dead version of PHP, it doesnā€™t seem worth the effort, but could be done I suppose.

You can try this one. It uses the example from the PHP doc. Not sure if you are using namespaces, but if you are, you might want to use the use keyword with \finfo in order to avoid errors because PHP thinks the class is within the current file, but we are actually using a global class.

<?php
// TESTED ONLY WITH PHP 7!!!!
// THIS SNIPPET MAY NOT WORK WITH OTHER VERSIONS OF PHP

// The proper way of checking if the form was submitted through POST
if($_SERVER['REQUEST_METHOD'] == 'POST') {

    $dir = 'uploads/'; // The directory the files should be stored in

    // Create an array of desired mime types.
    // Generally, mime types start with the category the file belongs in.
    // Then followed by either the extension or the actual type of file it is.
    // Here is a complete list of mime types if you are not familiar with them.
    // https://sitepoint.com/web-foundations/mime-types-complete-list/
    $array = array(
        'image/png',
        'image/jpg',
        'image/jpeg',
        'image/gif',
        'video/mp4',
        'video/webm',
        'video/avi',
        'video/mpeg',
    );

    // These are just the generic mime types for images and videos. If you want to allow other image formats and video formats, you'll need to add them into the array yourself.

    $name = $_FILES['fileToUpload']['name']; // Create the $name variable and append the name field to it.
    $tmp = $_FILES['fileToUpload']['tmp_name']; // Create the $tmp variable and append the tmp_name field to it.
    $size = $_FILES['fileToUpload']['size']; // Create the $size variable and append the size field to it.

    // Check the mime type of the file
    // Remember, mime_content_type won't work if the file is larger than the expected file size within your php.ini file.
    // mime_content_type will also not work if you are not running on PHP 7.
    // It was marked as deprecated and would complain when you used it.
    // An alternative is to use finfo_file()
    // The example usage can be found at http://php.net/manual/en/function.finfo-file.php

    // $mime = mime_content_type($tmp); <-- Only for PHP 7
    // OOP style
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime = $finfo->file($tmp);
    unset($finfo);

    // Take the mime type of the temp file and check it against the array we created above.
    // We DO NOT want to take the "type" field from the default $_FILES[...]['type'] field,
    // Because this is not reliable and only contains the current mime type of the file extension.
    // It does not contain the original mime type that the file was created from.
    if(in_array($mime, $array)) {

        // In this if/else statement, we are checking to see if the file is an image or not.
        // Apparently, you are asking for less of a file size for images than for video files.
        // So we check to see if the image is larger than 5,000,000 bytes.
        // If the file is, tell the user that the file is too big.
        // If the file is not, proceed to uploading the file.

        // Again, this is just a few generic mime types for images.
        // If you want to allow other image formats, you'll have to add them in yourself.
        $imageType = array(
            'image/png',
            'image/jpg',
            'image/jpeg',
            'image/gif'
        );

        // Check for the very last period. This generally is the file extension.
        // We are doing this because we want to know the file extension of the file.
        // If the file has made it this far, we will assume that the file is either an image or a video.
        // So it's safe to use the file's old extension.
        // Normally, you wouldn't want to use the user's file extension and you would append your own.
        // But this is just a snippet to demonstrate that we can do this.
        $ext = substr(strrchr($name, '.'), 1);

        // Generate a hash using the current timestamp in Unix along with sha256.
        // You can generate the file name any way you'd like.
        // It doesn't have to be exactly like how everyone wants you to do it.
        $name = hash('sha256', time());

        // Combine the 3 variables ($dir, $name, $ext) together and append a period before the extension.
        // This will give you a random file name along with the original file extension. Like so.
        // 91f56c7596fdfaa1d0b64a0e9461eff5314dcca1cb51d2c8c89b830388d053f8.jpg
        // Or
        // c3e7d43db3d7be99d77112d8283cd3fff8f720ee6d8a2283b69c706493cbd003.mp4
        $file = $dir . $name . '.' . $ext;

        // Check to see if the mime content type of the temp file is an image.
        if(in_array($mime, $imageType)) {

            // Check to see if the image is larger than 5,000,000 bytes.
            if($size > 5000000) {

                print('Sorry, your file is too large.'); // Tell the user that their image size is too big.

            } else {

                // The image is just perfect so move the image to the upload directory along with
                // the new file name.
                if(move_uploaded_file($tmp, $file)) {

                    print('Good'); // A successful upload 'twas is.

                } else {

                    print('Bad upload'); // Hmm, looks like the upload was a failure.
                    // Check to make sure that the directory has the right permissions for you to
                    // Upload files to.
                    // Also, make sure that the directory you specified exists.

                }

            }

        } else {

            // The file was not an image based on the mime type.
            // We will assume it is a video if it gets this far.
            // Check to see if the video is larger than 5,000,000,000 bytes.
            if($size > 5000000000) {

                print('Sorry, your file is too large.');// Tell the user that their video size is too big.

            } else {

                // The video is just perfect so move the video to the upload directory along with
                // the new file name.
                if(move_uploaded_file($tmp, $file)) {

                    print('Good'); // A successful upload 'twas is.

                } else {

                    print('Bad upload'); // Hmm, looks like the upload was a failure.
                    // Check to make sure that the directory has the right permissions for you to
                    // Upload files to.
                    // Also, make sure that the directory you specified exists.

                }

            }

        }

    } else {

        print('Bad'); // It looks like the original mime type of the file does not meet our standards.

    }

} else {

    header('Location: /'); // Redirect the user back to whatever page they came from.
    // I would suggest changing this line if this current PHP file is located some where else
    // Or if the file used to target this current PHP file is named something different.

}

@Mittineague
Hmm, that does sound like it would help, but isnā€™t that just for allowing the use of uploading larger files? There should still be some kind of limit to how large a file can be. Other wise, someone could potentially do a buffer overflow.

Thanks for the replies. Much appreciated.
I tried the modified PHP and see now this:

Class ā€˜finfoā€™ not found ā€¦ on line 41

Any additional thoughts youā€™d like to share will be welcomed.
Much thanks again.

Post the code you currently have with the modifications. Also, what exact version of PHP do you have? Is it PHP 5.3?

Yes 5.3

Iā€™m using your code, where I just changed $dir = ā€˜uploads/ā€™;

Hmm, thatā€™s weird. You should have that class because finfo() was introduced in PHP 5.3.0, you probably have a later version of PHP 5.3 which makes no sense why it isnā€™t working. I am not sure if this will work either because if the OOP version doesnā€™t work, I highly doubt the Procedural version will work. But hereā€™s a shot.

<?php
// TESTED ONLY WITH PHP 7!!!!
// THIS SNIPPET MAY NOT WORK WITH OTHER VERSIONS OF PHP

// The proper way of checking if the form was submitted through POST
if($_SERVER['REQUEST_METHOD'] == 'POST') {

    $dir = 'uploads/'; // The directory the files should be stored in

    // Create an array of desired mime types.
    // Generally, mime types start with the category the file belongs in.
    // Then followed by either the extension or the actual type of file it is.
    // Here is a complete list of mime types if you are not familiar with them.
    // https://sitepoint.com/web-foundations/mime-types-complete-list/
    $array = array(
        'image/png',
        'image/jpg',
        'image/jpeg',
        'image/gif',
        'video/mp4',
        'video/webm',
        'video/avi',
        'video/mpeg',
    );

    // These are just the generic mime types for images and videos. If you want to allow other image formats and video formats, you'll need to add them into the array yourself.

    $name = $_FILES['fileToUpload']['name']; // Create the $name variable and append the name field to it.
    $tmp = $_FILES['fileToUpload']['tmp_name']; // Create the $tmp variable and append the tmp_name field to it.
    $size = $_FILES['fileToUpload']['size']; // Create the $size variable and append the size field to it.

    // Check the mime type of the file
    // Remember, mime_content_type won't work if the file is larger than the expected file size within your php.ini file.
    // mime_content_type will also not work if you are not running on PHP 7.
    // It was marked as deprecated and would complain when you used it.
    // An alternative is to use finfo_file()
    // The example usage can be found at http://php.net/manual/en/function.finfo-file.php

    // $mime = mime_content_type($tmp); <-- Only for PHP 7
    // OOP style
    // $finfo = new finfo(FILEINFO_MIME_TYPE);
    // $mime = $finfo->file($tmp);
    // unset($finfo);

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $tmp);
    finfo_close($finfo);

    // Take the mime type of the temp file and check it against the array we created above.
    // We DO NOT want to take the "type" field from the default $_FILES[...]['type'] field,
    // Because this is not reliable and only contains the current mime type of the file extension.
    // It does not contain the original mime type that the file was created from.
    if(in_array($mime, $array)) {

        // In this if/else statement, we are checking to see if the file is an image or not.
        // Apparently, you are asking for less of a file size for images than for video files.
        // So we check to see if the image is larger than 5,000,000 bytes.
        // If the file is, tell the user that the file is too big.
        // If the file is not, proceed to uploading the file.

        // Again, this is just a few generic mime types for images.
        // If you want to allow other image formats, you'll have to add them in yourself.
        $imageType = array(
            'image/png',
            'image/jpg',
            'image/jpeg',
            'image/gif'
        );

        // Check for the very last period. This generally is the file extension.
        // We are doing this because we want to know the file extension of the file.
        // If the file has made it this far, we will assume that the file is either an image or a video.
        // So it's safe to use the file's old extension.
        // Normally, you wouldn't want to use the user's file extension and you would append your own.
        // But this is just a snippet to demonstrate that we can do this.
        $ext = substr(strrchr($name, '.'), 1);

        // Generate a hash using the current timestamp in Unix along with sha256.
        // You can generate the file name any way you'd like.
        // It doesn't have to be exactly like how everyone wants you to do it.
        $name = hash('sha256', time());

        // Combine the 3 variables ($dir, $name, $ext) together and append a period before the extension.
        // This will give you a random file name along with the original file extension. Like so.
        // 91f56c7596fdfaa1d0b64a0e9461eff5314dcca1cb51d2c8c89b830388d053f8.jpg
        // Or
        // c3e7d43db3d7be99d77112d8283cd3fff8f720ee6d8a2283b69c706493cbd003.mp4
        $file = $dir . $name . '.' . $ext;

        // Check to see if the mime content type of the temp file is an image.
        if(in_array($mime, $imageType)) {

            // Check to see if the image is larger than 5,000,000 bytes.
            if($size > 5000000) {

                print('Sorry, your file is too large.'); // Tell the user that their image size is too big.

            } else {

                // The image is just perfect so move the image to the upload directory along with
                // the new file name.
                if(move_uploaded_file($tmp, $file)) {

                    print('Good'); // A successful upload 'twas is.

                } else {

                    print('Bad upload'); // Hmm, looks like the upload was a failure.
                    // Check to make sure that the directory has the right permissions for you to
                    // Upload files to.
                    // Also, make sure that the directory you specified exists.

                }

            }

        } else {

            // The file was not an image based on the mime type.
            // We will assume it is a video if it gets this far.
            // Check to see if the video is larger than 5,000,000,000 bytes.
            if($size > 5000000000) {

                print('Sorry, your file is too large.');// Tell the user that their video size is too big.

            } else {

                // The video is just perfect so move the video to the upload directory along with
                // the new file name.
                if(move_uploaded_file($tmp, $file)) {

                    print('Good'); // A successful upload 'twas is.

                } else {

                    print('Bad upload'); // Hmm, looks like the upload was a failure.
                    // Check to make sure that the directory has the right permissions for you to
                    // Upload files to.
                    // Also, make sure that the directory you specified exists.

                }

            }

        }

    } else {

        print('Bad'); // It looks like the original mime type of the file does not meet our standards.

    }

} else {

    header('Location: /'); // Redirect the user back to whatever page they came from.
    // I would suggest changing this line if this current PHP file is located some where else
    // Or if the file used to target this current PHP file is named something different.

}

If this one doesnā€™t work as well, then I highly suggest you upgrade your PHP version. It is obsolete at this point. I highly suggest switching to a hosting provider that supports PHP 7. If you are using a localhost of some sort, I highly highly recommend un-installing your current localhost whether itā€™s XAMPP, WAMP, MAMP, or whatever and install PHP 7 the way I have demonstrated in this topic.

1 Like

Check the Online PHP Manual for the return value of getimagesize() and you will find false is returned if the file is not an image. Videos are not images.

If you want to "convert" value returned by "getimagesize()" as index "2" 
into something more human-readable, 
you may consider using a function like this one:

    $imageTypeArray = array
    (
        0=>'UNKNOWN',
        1=>'GIF',
        2=>'JPEG',
        3=>'PNG',
        4=>'SWF',
        5=>'PSD',
        6=>'BMP',
        7=>'TIFF_II',
        8=>'TIFF_MM',
        9=>'JPC',
        10=>'JP2',
        11=>'JPX',
        12=>'JB2',
        13=>'SWC',
        14=>'IFF',
        15=>'WBMP',
        16=>'XBM',
        17=>'ICO',
        18=>'COUNT'  
    );
    
    $size = getimagesize($filename);
    
    $size[2] = $imageTypeArray[$size[2]];

Or something similar.

Thanks for the replies and effort, tried your latest ā€œhereā€™s a shotā€ however:

Fatal error: Call to undefined function finfo_open() ā€¦ on line 45

I have used ini_set to tweak up both size and time limits before, albeit only very rarely and then almost exclusively for my localhost ā€œhackyā€ scripts.

AFAIK ini_get would return the existing config values. A better use for it might be to display a type of ā€œmust be less thanā€ message before a user attempts to do an upload. But I donā€™t see why it couldnā€™t be used in a control too as a maximum.
As for buffer overflow, I donā€™t know. Iā€™m guessing that PHP would abort the upload if the limit was reached and not try to put the larger file into memory. If so then it would limit the usefulness of testing against it in the script and error handling would be a better approach.

Are you using a localhost or a live server? If youā€™re using a localhost, are you using Windows or Linux? If you are using Windows, look in your php.ini file for this line

;extension=php_fileinfo.dll

If itā€™s commented out like above, uncomment it by removing the ;

This should solve the problem if you are using a localhost. If you are using a live server, ask your hosting provider to uncomment that line for you in your php.ini file.

1 Like

Thanks again

How is it going for you?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.