[PHP]Image Upload

Results 1 to 5 of 5
  1. #1
    Account Upgraded | Title Enabled! Intelext is offline
    MemberRank
    Mar 2007 Join Date
    EuropeLocation
    1,228Posts

    [PHP]Image Upload

    This is my function that uploads images and you can resize them. All you have to do is include this in your script and pass the $_FILE[''] value (array) to it. Script will do the rest. Very copy/paste friendly.

    PHP Code:
    <?php

    /**
     * -----------------------------------------------------------------------------
     * Image Uploading Script
     * by Steve Moss (Dr.Qmal@gmail.com)
     * -----------------------------------------------------------------------------
     * @imgUpload Function takes parameters, then renames the original file to
     * random generated name (32 chars long), resizes it if one of parameters are
     * set and then uploads it into desired directory.
     * -----------------------------------------------------------------------------
     *
     * @param <array> $img - Our file array
     * @param <string> $upload_dir - Directory where we want to upload our image
     * @param <int> $newWidth - New width of image, null by default
     * @param <int> $newHeight - New height of image, null by default
     * @return <string> - Eather it's error type or uploaded image link
     */
    function imgUpload($img$upload_dir$newWidth null$newHeight null)
    {
        
    //First we will check if there are no errors
        
    if ($img['error'] == 0)
        {
            
    //We will check if it is an image (pjpeg, x-png needed SPECIALLY for IE -.-)
            
    if (   $img['type'] == "image/gif"
                
    || $img['type'] == "image/jpeg"
                
    || $img['type'] == "image/pjpeg"
                
    || $img['type'] == "image/png"
                
    || $img['type'] == "image/x-png")
            {
                
    //We need to check if image is not too big (6291456b or 6mb is default value)
                
    if ($img['size'] < 6291456)
                {
                    
    //Setting up file name
                    
    $imgName $img['name'];

                    
    //Setting up the extension
                    
    $imgExtension end(explode("."$imgName));

                    
    //Creating random file name by using MD5 HASH from Unique ID generator (32 char long)
                    
    $imgNewName md5(uniqid()) . "." $imgExtension;

                    
    //Checking if file with this name already exists, if it does we generate new name
                    
    while (file_exists($upload_dir $imgNewName) == true)
                        
    $imgNewName md5(uniqid()) . "." $imgExtension;

                    
    //Checking if we want to resize the image
                    
    if ($newWidth != null || $newHeight != null)
                    {
                        
    //First we get the old Width and Height in case one of parameters are "null"
                        
    list($oldWidth$oldHeight) = getimagesize($img['tmp_name']);

                        
    //If $newWidth or $newHeight is "null" we will change that to original Height/Width
                        
    if ($newWidth == null)
                            
    $newWidth $oldWidth;
                        if (
    $newHeight == null)
                            
    $newHeight $oldHeight;

                        
    //Creating image from old one depending on its extension
                        
    if ($imgExtension == "jpeg" || $imgExtension == "jpg")
                            
    $source imagecreatefromjpeg($img['tmp_name']);
                        if (
    $imgExtension == "png")
                            
    $source imagecreatefrompng($img['tmp_name']);
                        if (
    $imgExtension == "gif")
                            
    $source imagecreatefromgif($img['tmp_name']);

                        
    //Creating new image with desiered dimension
                        
    $newImage imagecreatetruecolor($newWidth$newHeight);

                        
    //Resizing our image with some manual corrections for optimal transition
                        
    imagecopyresized($newImage$source0000$newWidth$newHeight 1$oldWidth 2$oldHeight);

                        
    //Moving our image to designated folder
                        
    imagejpeg($newImage"$upload_dir/$imgNewName");
                    }
                    else
                    {
                        
    //If we don't want to resize our image just upload it
                        
    move_uploaded_file($img['tmp_name'], "$upload_dir/$imgNewName");
                    }

                    return 
    "$upload_dir/$imgNewName";
                }
                else
                    return 
    "sizeError";
            }
            else
                return 
    "fileError";
        }
        else
            return 
    "Error: " $img['error'];
    }


  2. #2
    Ginger by design. jMerliN is offline
    MemberRank
    Feb 2007 Join Date
    2,497Posts

    Re: [PHP]Image Upload

    You can accept more with fileinfo and be more secure by not trusting the mime type passed to you by the client. You can set it up so that you have a list of valid image mimes and their extensions and just use that to place the files and test them (fileinfo will give you mimetype information).

  3. #3
    :-) s-p-n is offline
    DeveloperRank
    Jun 2007 Join Date
    Next DoorLocation
    2,098Posts

    Re: [PHP]Image Upload

    This might be an improved version, it includes a disclaimer and less nesting. Also, it checks the extension since the mime-type can be fooled pretty easily.

    PHP Code:
    <?php 
     
    /*
     WEB DEVELOPERS USING THIS SCRIPT
     PLEASE READ:
        
     ------>>> This script is not secure when the allowed types or
            extensions defined in this script are granted permission
            by the server to execute PHP code.
            
            (Who would let the server parse PHP code inside an image?)
     
     * ----------------------------------------------------------------------------- 
     * Image Uploading Script 
     * By: Steve Moss (Dr.Qmal@gmail.com) 
     * (Edited By: Spencer Lockhart; Spence@WysGui.com)
     * ----------------------------------------------------------------------------- 
     * @imgUpload Function takes parameters, then renames the original file to 
     * random generated name (32 chars long), resizes it if one of parameters are 
     * set and then uploads it into desired directory. 
     * ----------------------------------------------------------------------------- 
     * 
     * @param <array> $img - Our file array 
     * @param <string> $upload_dir - Directory where we want to upload our image 
     * @param <int> $newWidth - New width of image, null by default 
     * @param <int> $newHeight - New height of image, null by default 
     * @return <string> - Eather it's error type or uploaded image link 
     *
     */ 
    function bad_type($name$type$allowed_types$allowed_extensions)
    {
        
    $imgExtension strtolower
                    
    end
                        
    explode"."$name 
                    ) 
                );
        
        return !
    in_array($type$allowed_types) || !in_array($extension$allowed_extensions)
    }
     
    function 
    imgUpload($img$upload_dir$newWidth null$newHeight null

        
    //List the allowed image mime-types
        
    $allowed_types = array('image/gif',
                    
    'image/jpeg',
                    
    'image/pjpeg',
                    
    'image/png',
                    
    'image/x-png')
        
        
    $allowed_extensions = array('gif',
                    
    'jpg',
                    
    'jpeg',
                    
    'jpeg',
                    
    'png')
        
        
    //First we will check if there are no errors 
        
    if ($img['error'] != 0
        {
            return 
    "Error: " $img['error'];
        }
        
        
    //Check to make sure the size is less than 6MB
        
    if($img['size'] > 6291456//6MB
        
    {
            return 
    'File must be 6MB or less in size.'
        }
        
        
    //We will try to check if it is a safe image
            /*
              The best we can do in PHP is check the 
              mime-type and the extension.
            */
        
        
        
    $type_error 'File-Type is not supported. Try a JPEG, GIF, or PNG image less than 6MB in size.';
        
        if(
    bad_type($img['name'], $img['type'], $allowed_types$allowed_extensions)) 
        {
            return 
    $type_error;
        }
        
        
        
    //Creating random file name by using MD5 HASH from Unique ID generator (32 char long) 
        
    $imgNewName md5(uniqid()) . "." $imgExtension
        
        
    //Checking if file with this name already exists, if it does we generate new name 
        
    while (file_exists($upload_dir $imgNewName) == true)
        {
            
    $imgNewName md5(uniqid()) . "." $imgExtension
        }
        
        
    //Checking if we want to resize the image 
        
    if ($newWidth != null || $newHeight != null
        {
            
    //First we get the old Width and Height in case one of parameters are "null" 
            
    list($oldWidth$oldHeight$type) = getimagesize($img['tmp_name']); 
            
            
    //Double Check the type.. Maybe redundant idk
            
    if(!in_array($type$allowed_types))
            {
                return 
    $type_error;
            }
            
            
            
    //If $newWidth or $newHeight is "null" we will change that to original Height/Width 
            
    if ($newWidth == null
                
    $newWidth $oldWidth
            
            if (
    $newHeight == null
                
    $newHeight $oldHeight
            
            
            
    //Creating image from old one depending on its extension 
            
    if ($imgExtension == "jpeg" || $imgExtension == "jpg"
                
    $source imagecreatefromjpeg($img['tmp_name']); 
            
            if (
    $imgExtension == "png"
                
    $source imagecreatefrompng($img['tmp_name']); 
            
            if (
    $imgExtension == "gif"
                
    $source imagecreatefromgif($img['tmp_name']); 
            
            
            
    //Creating new image with desiered dimension 
            
    $newImage imagecreatetruecolor($newWidth$newHeight); 
            
            
    //Resizing our image with some manual corrections for optimal transition 
            
    imagecopyresized($newImage$source0000$newWidth$newHeight 1$oldWidth 2$oldHeight); 

            
    //Moving our image to designated folder 
            
    imagejpeg($newImage"$upload_dir/$imgNewName"); 
        } else
        {
            
    //If we don't want to resize our image just upload it
            
    move_uploaded_file($img['tmp_name'], "$upload_dir/$imgNewName");
            
            
    //Double Check Type when NOT resizing.. Again, dunno if it's redundant quite yet, they're different checks but both don't completely work....
            
    if(!in_array(exif_imagetype("$upload_dir/$imgNewName"), $allowed_types))
            {
                
    unlink("$upload_dir/$imgNewName");
                return 
    $type_error;
            }

        }
        
        return 
    "$upload_dir/$imgNewName";
    }
    [Not tested]
    Last edited by s-p-n; 16-02-11 at 05:23 PM.

  4. #4
    Infraction Baɴɴed holthelper is offline
    MemberRank
    Apr 2008 Join Date
    1,765Posts

    Re: [PHP]Image Upload

    how about something along the lines of:
    Code:
    exif_imagetype($imageURL);

  5. #5
    :-) s-p-n is offline
    DeveloperRank
    Jun 2007 Join Date
    Next DoorLocation
    2,098Posts

    Re: [PHP]Image Upload

    Quote Originally Posted by holthelper View Post
    how about something along the lines of:
    Code:
    exif_imagetype($imageURL);
    No difference..

    Quote Originally Posted by http://php.net/manual/en/function.exif-imagetype.php
    When a correct signature is found, the appropriate constant value will be returned otherwise the return value is FALSE. The return value is the same value that getimagesize() returns in index 2 but exif_imagetype() is much faster.
    Unfortunately, these kinds of checks are STILL incomplete (not completely secure), and can't be used until AFTER the image is uploaded.

    Please see these links:
    http://ha.ckers.org/blog/20070604/pa...-getimagesize/
    http://www.phpclasses.org/blog/post/...IF-images.html

    So I dunno, since PHP.net claims exif_image() returns the SAME value as getimagesize's mime value, I assume it has the same problems.

    Ty and I did include that function in the part of the script where the image isn't resized, as it needed the same check as the resizing part has.

    I'm not sure how to secure this if, for example, 'png' type files are granted permission to execute PHP code, with the above script snippet present on the server.

    If that extreme case happens, this script could very well be a blind security hole for an unsuspecting web designer.
    Last edited by s-p-n; 16-02-11 at 05:33 PM.



Advertisement