Showing posts with label images. Show all posts
Showing posts with label images. Show all posts

Thursday, 2 May 2013

Upload files and rename


We have faced some issue like file duplication or replacing image or file with same name when using upload function. 

Here is the tested script which checks exists files with being uploaded file and check if the same name is exists or not. If any file with the same name exist in your UPLOAD directory then it will rename your files with numeric post fix, that escape you from overwritten existing files. Hope it helps


<form name="form1" method="post" action="" enctype="multipart/form-data">
<label>Upload files : </label><input type="file" name="file" value="" />
<input type="submit" name="submit" value="submit" />
</form>

<?php


$path = "upload/";
if($_POST['submit'])

{
$name = $_FILES['file']['name'];
$name = if_exist_rename($name,$path);
if(move_uploaded_file($_FILES['file']['tmp_name'],"upload/".$name))
    {

        echo "File uploaded successfully";
    }else
    {
        echo "Problem in Upload";
    }

}

function if_exist_rename($name,$path)   
{
$actual_name = pathinfo($name,PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo($name, PATHINFO_EXTENSION);

$i = 1;
while(file_exists($path.$actual_name.".".$extension))
    {          
       $actual_name = (string)$original_name.'-'.$i;
       $name = $actual_name.".".$extension;
       $i++;
    }
    return $name;
}
?>

Thursday, 22 November 2012

Extract zip images and Upload

<?php

$supload = isset($_POST["supload"]) ? $_POST["supload"] : "";

if($supload != ""){
    $dir = "upload/"; //The folder to store your images
    $fileName = $_FILES['sfile']['name']; //get the file name
    $fileSize = $_FILES['sfile']['size']; //get the size
    $fileError = $_FILES['sfile']['error']; //get the error code
    if($fileSize > 0 || $fileError == 0){ //check if the file is corrupt or error
        //$fname = $dir.$fileName;
        $zip = zip_open($_FILES['sfile']['tmp_name']);
        if(is_resource($zip)){
            do_upload($dir,$_FILES['sfile']['tmp_name']);
        }
    }else{
        echo "error! ".$fileSize." ".$fileError;
    }
}

function do_upload($dir,$path){
    $allowed_type = array("jpeg","jpg","gif","png","bmp","pjpeg");
    $zip = new ZipArchive;
    if ($zip->open($path) === true) {
        for($i = 0; $i < $zip->numFiles; $i++) {
            $filename = $zip->getNameIndex($i);

            //Get file informatin eg: filename, file extension, etc..
            $fileinfo = pathinfo($filename);
            $fname = $dir.$fileinfo['basename'];

            //Only proceed if it has an extension
            if(isset($fileinfo['extension'])){
                //Check if the file extension is an image file
                if(in_array($fileinfo['extension'],$allowed_type)){
                    //Now extract the file
                    if(copy("zip://".$path."#".$filename, $fname)){
                        echo "File ".$filename." uploaded. ";
                        //Create new filename for thumbnail
                        $newfilename = "th_".$fileinfo['basename'];

                        //Second check, To get the real MIME type
                        $imgInfo = getimagesize($fname);
                        echo "File Type: ".$imgInfo['mime']."<br />";
                        if(checkFileType($imgInfo['mime'])){
                            //Now resize the image
                            resize($fname, $dir.$newfilename);
                        }
                    }
                }else{
                    echo $filename." is not an image!<br />";
                }
            }
        }
        $zip->close();
        return true;
    }
}

function checkFileType($file){
    $imgType = array(
            "Gif"=>"image/gif",
            "JPG" => "image/jpg",
            "JPEG" => "image/jpeg",
            "PJPEG" => "image/pjpeg",
            "PNG" => "image/png",
            "BMP" => "image/bmp");
    if(in_array($file,$imgType))
            return true;
    else return false;
}

function resize($img, $newfilename) {
    //Check if GD extension is loaded
    if (!extension_loaded('gd') && !extension_loaded('gd2')) {
        trigger_error("GD is not loaded", E_USER_WARNING);
        return false;
    }
    $w = 100;
    $h = 100;

    //Get Image size info
    $imgInfo = getimagesize($img);
    switch ($imgInfo[2]) {
        case 1: $im = imagecreatefromgif($img); break;
        case 2: $im = imagecreatefromjpeg($img);  break;
        case 3: $im = imagecreatefrompng($img); break;
        default:  trigger_error('Unsupported filetype!', E_USER_WARNING);  break;
    }

    //If image dimension is smaller, do not resize
    if ($imgInfo[0] <= $w && $imgInfo[1] <= $h) {
        $nHeight = $imgInfo[1];
        $nWidth = $imgInfo[0];
    }else{
        //resize it, but keep it proportional
        if ($w/$imgInfo[0] > $h/$imgInfo[1]) {
            $nWidth = $w;
            $nHeight = $imgInfo[1]*($w/$imgInfo[0]);
            }else{
            $nWidth = $imgInfo[0]*($h/$imgInfo[1]);
            $nHeight = $h;
        }
    }
    $nWidth = round($nWidth);
    $nHeight = round($nHeight);

    $newImg = imagecreatetruecolor($nWidth, $nHeight);

    /* Check if this image is PNG or GIF, then set if Transparent*/
    if(($imgInfo[2] == 1) OR ($imgInfo[2]==3)){
        imagealphablending($newImg, false);
        imagesavealpha($newImg,true);
        $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
        imagefilledrectangle($newImg, 0, 0, $nWidth, $nHeight, $transparent);
    }
    imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $imgInfo[0], $imgInfo[1]);

    //Generate the file, and rename it to $newfilename
    switch ($imgInfo[2]) {
        case 1: imagegif($newImg,$newfilename); break;
        case 2: imagejpeg($newImg,$newfilename);  break;
        case 3: imagepng($newImg,$newfilename); break;
        default:  trigger_error('Failed resize image!', E_USER_WARNING);  break;
    }

    return $newfilename;
}
?>
<form name="fsupload" action="" method="post" enctype="multipart/form-data">
    <div>
    Add Image: <input type="file" name="sfile" id="sfile" />
    <input type="submit" name="supload" value="Upload" />
    </div>
</form>