当上传zip文件夹验证只有.jpg,.png文件将保存在zip文件夹+ php内

时间:2014-08-22 05:46:22

标签: php

<?php

    $fileName = $_FILES["uploaded_file"]["name"]; 
    $fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"];
    $fileType = $_FILES["uploaded_file"]["type"]; 
    $fileSize = $_FILES["uploaded_file"]["size"]; 
    $fileErrorMsg = $_FILES["uploaded_file"]["error"]; 
    $fileName = preg_replace('#[^a-z.0-9]#i', '', $fileName); 
    $kaboom = explode(".", $fileName); 
    $fileExt = end($kaboom);

    $foldername= $_SESSION['user_name'];
    $fileName = $_SESSION['user_name']."_".session_id().".".$fileExt;

    $path= "upload"/" $foldername";

    if (!$fileTmpLoc) 
{ 
        echo "<script type='text/javascript'>alert('ERROR: Please browse for a file before clicking the upload button.')</script>";
        exit();
    } 

    else if (!preg_match("/.(rar|zip|tar)$/i", $fileName) ) 
{
         echo "<script type='text/javascript'>alert('ERROR: Your Folder was not .rar, .zip, or .tar .')</script>";
         unlink($fileTmpLoc);
         exit();
    } 
    else if ($fileErrorMsg == 1) 
{   
        echo "<script type='text/javascript'>alert('ERROR: An error occured while processing the file. Try again.')</script>";
        exit();
    }

    else if(!preg_match("/.(jpg|png|jpeg)$/i",$path))
{
        echo "<script type='text/javascript'>alert('ERROR: Your Files inside zip was not .jpg, .png, or .jpeg .')</script>";
        exit();
    }


    $moveResult = move_uploaded_file($fileTmpLoc, "upload/$foldername/$fileName");

    if ($moveResult != true) {
        echo "<script type='text/javascript'>alert('ERROR: File not uploaded. Try again.')</script>";
        exit();
    }

    echo "<script type='text/javascript'>alert('The file named $fileName uploaded successfuly. It is $fileSize bytes in size.')</script>";

    }
?>

1 个答案:

答案 0 :(得分:0)

欢迎来到SO,如果你想得到一个很好的答案而且不想被低估,我建议你提出一个很好的问题,不要只提供你的代码,等待有人修理你的东西。

除此之外,您还可以使用php ZipArchive函数来完成工作

http://php.net/manual/en/class.ziparchive.php

// validate against zip folder
// ...

$zip = new ZipArchive(); 
$zip->open($file['temp_dir']); 

if( $zip === true )
{
    $invalid = false;
    for( $i = 0; $i < $za->numFiles; $i++ ){ 
        $stat = $za->statIndex( $i ); 
        if( !in_array(strtolower(pathinfo(basename($stat['name'] )), PATHINFO_EXTENSION), array('jpg','png')) )
        {
            $invalid = true;
            break;
        }
    }

    if( $invalid )
    {
        // error other files then jpg and png
    } else {
        // ok!
    }

} else {
    // error open zip file
}