Файловый сервер работает для первой загрузки, но не для второй - PullRequest
0 голосов
/ 29 марта 2012

У меня есть файловый сервер, который правильно проверяет допустимые типы и размеры файлов и помещает файл на сервер. Если загружено несколько разрешенных файлов, они заархивируются и архив помещается на сервер.

Это все работает. Страница является 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 голосов
/ 29 марта 2012

Вы получаете эту ошибку из-за этой строки кода

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

Возможные причины

A.Имя файла, который вы пытаетесь загрузить $fileName[$i], показывает «K», что означает, что у него нет расширения.Пожалуйста, попробуйте переименовать файл правильно

B.Вы загружаете файл с неправильным расширением

C.in_array чувствителен к регистру, поэтому, если у вас есть расширение файла с TXT! = Txt

Решение

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

И наконец ... Я думаю, что это безопаснее использовать тип файла

Надеюсь, это поможет

Спасибо :)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...