doutou1922 2012-03-29 05:15
浏览 54

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

I have a file server that correctly checks for allowed filetypes and sizes and places the file on the server. If multiple allowed files are uploaded the files are zipped and the zip is placed on the server.

This all works. The page is ajax-ified so you should be able to use the form a second time, but it always fails on the second submit.

The response from upload.php for the second post is:

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

Here are my index.php and 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>   

Thanks for any and all help!

  • 写回答

1条回答 默认 最新

  • doumi1912 2012-03-29 07:59
    关注

    You are having that error because of this line of code

        $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;}
    

    Possible Reasons

    A. The file name you are trying to upload $fileName[$i] is showing "K" which means it has no extension. Please try and rename the file properly

    B. You are uploading file with Wrong extension

    C. in_array is case sensitive so if you have file extension with TXT != txt

    Solution

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

    Lastly ... I think its saver to use file type

    I hope this helps

    Thanks :)

    评论

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图