文件服务器适用于首次上载,但不适用于第二次

时间:2012-03-29 05:15:04

标签: php ajax file-upload

我有一个文件服务器,可以正确检查允许的文件类型和大小,并将文件放在服务器上。如果上传了多个允许的文件,则会压缩文件并将zip文件放在服务器上。

这一切都有效。该页面是ajax-ified所以你应该能够第二次使用该表单,但它在第二次提交时总是失败。

upload.php对第二篇帖子的回复是:

<script language="javascript" type="text/javascript">window.top.window.stopUpload(
null,
"The file you attempted to upload is not allowed: K",
[],
1,
["K"],
[""]);
</script>   

这是我的index.php和upload.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <title>PTPsubs</title>
   <link href="style/style.css" rel="stylesheet" type="text/css" />

<script language="javascript" type="text/javascript">
function startUpload(){
      document.getElementById('f1_upload_process').style.visibility = 'visible';
      document.getElementById('f1_upload_form').style.visibility = 'hidden';
      return true;
}

function stopUpload(code,message,path,numFiles,fileName,ext){
    var output = '';    
    if (code == 1){
        output += 'The file was uploaded successfully!<br/>';
    }
    else {
        output = message;
    }


    result = '<span class="msg">'+output+'<\/span><br/><br/>';

    document.getElementById('f1_upload_process').style.visibility = 'hidden';
    document.getElementById('f1_upload_form').innerHTML = result + '<label>File: <input name="myfile" type="file" size="30" /><\/label><label><input type="submit" name="submitBtn" class="sbtn" value="Upload" /><\/label>';
    document.getElementById('f1_upload_form').style.visibility = 'visible';
    document.getElementById('link').innerHTML = path;      
    return true;   
}
</script>   
</head>

<body>
       <img src="style/images/ptpsubs3.gif" alt="ptpsubs" align="absmiddle" class="displayed" />
        <div id="sidediv">
            <ul>
                <li>Allowed file types: .srt, .idx, .sub, .txt
                <li>Multiple files uploaded at once will return a link to a zip archive of those files
            </ul> 
        </div><!--close the sidediv-->
        <div id="container">        
            <div id="content">                
                    <!--form starts here-->
                    <form action="upload.php" id="group" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="startUpload();" >
                         <p id="f1_upload_process">Loading...<br/><img src="loader.gif" /><br/></p>
                         <p id="f1_upload_form" align="center"><br/>
                             <label>File:  
                                  <input name="myfile[]" type="file" size="30" multiple="multiple" />
                             </label>
                             <label>
                                 <input type="submit" name="submitBtn" class="sbtn" value="Upload" multiple="multiple" />
                             </label>
                         </p>

                         <iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe>
                    </form>
                    <!--form ends here-->
            </div>
             <!--<div id="footer"><a href="" target="_blank">PTPsubs</a></div>-->
        </div>
        <div id="link"></div>            
</body>   

upload.php的:

<?php
    /* creates a compressed zip file */
    function create_zip($files = array(),$localnames=array(),$destination = '',$overwrite = false) {
  //if the zip file already exists and overwrite is false, return false
  if(file_exists($destination) && !$overwrite) { return false; }
  //vars
  $valid_files = array();
  //if files were passed in...
  if(is_array($files)) {
    //cycle through each file
    foreach($files as $file) {
      //make sure the file exists
      if(file_exists($file)) {
        $valid_files[] = $file;
      }
    }
  }
  //if we have good files...
  if(count($valid_files)) {
    //create the archive
    $zip = new ZipArchive();
    if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
      return false;
    }
    //add the files
    for ($i = 0; $i < count($valid_files); $i++) {
      $zip->addFile($valid_files[$i],$localnames[$i]);
    }
    //debug
    //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;

    //close the zip -- done!
    $zip->close();

    //check to make sure the file exists
    return file_exists($destination);
  }
  else
  {
    return false;
  }
}


    //database
    $username="";
    $password="";
    $database="";
    mysql_connect(localhost,$username,$password);
    @mysql_select_db($database) or die( "Unable to select database");

    $message = '';
    $code = array();
    $fileName = array();
    $ext = array();
    $tmpName = array();
    $path = array();
    $target_path = array();
    $prefix = substr(md5(time()),0,7); //new name of the file
    $pass = true;

    $count = count($_FILES['myfile']['name']);
    for($i=0;$i<$count;$i++)
    {   
        //file info
        $fileName[$i] = $_FILES['myfile']['name'][$i]; // Get the name of the file (including file extension).
        $ext[$i] = pathinfo($fileName[$i], PATHINFO_EXTENSION); // Get the extension from the filename.
        $tmpName[$i]  = $_FILES['myfile']['tmp_name'][$i];
        $fileSize[$i] = $_FILES['myfile']['size'][$i];
        $fileType[$i] = $_FILES['myfile']['type'][$i];  

       // Edit upload location here
        $destination_path = './files/';
        $allowed_filetypes = array('idx','sub','txt','srt');
        $max_filesize = 5242880; //bytes

        $target_path[$i] = $destination_path . $prefix .".".$ext[$i];

        // Check if the filetype is allowed, if not DIE and inform the user.
        if(!in_array($ext[$i],$allowed_filetypes)){
            $code[$i] = 2;
            $message = "The file you attempted to upload is not allowed: ".$fileName[$i];
            $pass=false;}

       // Now check the filesize, if it is too large then DIE and inform the user.
        else if(filesize($_FILES['myfile']['tmp_name'][$i]) > $max_filesize){
            $code[$i] = 3;
            $message = "The file you attempted to upload is too large.";
            $pass=false;}

        else if(!file_exists($destination_path)){
            $code[$i] = 4;
            $message = "The upload path does not exist";
            $pass=false;}

       // Check if we can upload to the specified path, if not DIE and inform the user.
        else if(!is_writable($destination_path)){
            $code[$i] = 5;
            $message = "You cannot upload to the specified directory, please CHMOD it to 777.";
            $pass=false;}



    }//closes for loop

    if($pass==true)
    {
        //NOW DO THE UPLOAD
        if($count==1)//single file upload
        {
            @move_uploaded_file($tmpName[0], $target_path[0]);

            $file_info = pathinfo($fileName[0]);
            $sql = "INSERT INTO Files SET 
                        uploader_ip = '".$_SERVER['REMOTE_ADDR']."',
                        File_Name = '".$fileName[0]."',
                        File_Type = '".$fileType[0]."',
                        File_Size = '".$fileSize[0]."',
                        File_Hash = '".$prefix.".".$file_info['extension']."',
                        File_Extension = '".$file_info['extension']."'";

            $sqlresult = mysql_query($sql);    
            // If the query was successful, give success message
            if(!$sqlresult){
                $return_code = 6;
                $return_message = "Could not add this file.";//not actually displayed
                 exit;}
            else{
                $return_message =  "New file successfully added.";//not actually displayed
                $return_code = 1;
                $path[0] = 'Your file upload was successful, view the file <a href="' . $target_path[0] . '" title="Your File">here</a><br/>';  }//code = 1
        }//$count=1

        else//zip it because its multiple files
        { 
            $ext = "zip";
            $target = './files/'.$prefix.".zip";
            $zip_file = create_zip($_FILES['myfile']['tmp_name'],$_FILES['myfile']['name'],$target);
            $sql = "INSERT INTO Files SET 
                        uploader_ip = '".$_SERVER['REMOTE_ADDR']."',
                        File_Name = '".$fileName[0]."',
                        File_Type = '".filetype($target)."',
                        File_Size = '".filesize($target)."',
                        File_Hash = '".$prefix.".zip"."',
                        File_Extension = '".$ext."'";

            $sqlresult = mysql_query($sql);    
            // If the query was successful, give success message
            if(!$sqlresult){
                $return_code = 6;
                $return_message = "Could not add this file.";//not actually displayed
                 exit;}
            else{
                $return_message =  "New file successfully added.";//not actually displayed
                $return_code = 1;
                $path[0] = 'Your file upload was successful, view the file <a href="' . $target. '" title="Your File">here</a><br/>';   }//code = 1
        }
    }//pass=true
    sleep(1);
?>

<script language="javascript" type="text/javascript">window.top.window.stopUpload(
<?php echo json_encode($return_code); ?>,
<?php echo json_encode($message); ?>,
<?php echo json_encode($path); ?>,
<?php echo json_encode($count); ?>,
<?php echo json_encode($fileName); ?>,
<?php echo json_encode($ext); ?>);
</script>   

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

由于这行代码

,您遇到了这个错误
    $allowed_filetypes = array('idx','sub','txt','srt');
    $max_filesize = 5242880; //bytes

    $target_path[$i] = $destination_path . $prefix .".".$ext[$i];

    // Check if the filetype is allowed, if not DIE and inform the user.
    if(!in_array($ext[$i],$allowed_filetypes)){
        $code[$i] = 2;
        $message = "The file you attempted to upload is not allowed: ".$fileName[$i];
        $pass=false;}

可能的原因

一个。您尝试上传的文件名$fileName[$i]显示“K”,表示它没有扩展名。请尝试正确重命名文件

B中。您正在使用错误的扩展程序上传文件

℃。 in_array区分大小写,因此如果您的文件扩展名为TXT!= txt

解决方案

   if(!in_array(strtolower($ext[$i]),$allowed_filetypes)){

最后......我认为它使用文件类型的保护程序

我希望这会有所帮助

谢谢:)