2015-05-03 2 views
1

Я создаю сценарий загрузки, чтобы загружать несколько фотографий в одну папку и одновременно загружать их в другую папку.PHP 'mkdir(): Файл существует, когда размер файла слишком велик?

Моя проблема в том, что я получаю сообщение об ошибке: mkdir(): File exists, когда я загружаю файлы размером более 2.5 Мб ... Я думаю. Мой phpinfo(); показывает, что мой post_max_size составляет 8M, а upload_max_filesize - 40M. Поэтому я не уверен, почему это делается только в больших или многих файлах. Если я загружу более мелкие изображения (~ 1 мб), тогда все будет хорошо. Но когда я загружаю большие файлы, я получаю эту ошибку.

Внимание: Стена сценария ...

Вот функции:

<?PHP 
    function makeFile($gallery_title, $gallery_date, $target_dir){ 
     $new_file = fopen($target_dir . "info.php", "w") or die("Unable to open file!"); 
     $txt = '<div class="info"><div class="title">'.$gallery_title.'</div><div class="date">'.$gallery_title.'</div><div class="enter">Enter</div></div>'; 
     fwrite($new_file, $txt); 
     fclose($new_file); 
    } 
    function resize($file, $width, $height, $target_dir, $new_name, $image_type){ 
     /* Get original image x y*/ 
     list($w, $h) = getimagesize($file); 
     /* calculate new image size with ratio */ 
     $ratio = max($width/$w, $height/$h); 
     $h = ceil($height/$ratio); 
     $x = ($w - $width/$ratio)/2; 
     $w = ceil($width/$ratio); 
     /* new file name */ 
     $path = $target_dir.$new_name; 
     /* read binary data from image file */ 
     $imgString = file_get_contents($file); 
     /* create image from string */ 
     $image = imagecreatefromstring($imgString); 
     $tmp = imagecreatetruecolor($width, $height); 
     imagecopyresampled($tmp, $image, 
      0, 0, 
      $x, 0, 
      $width, $height, 
      $w, $h); 
     /* Save image */ 
     switch ($image_type) { 
      case 'image/jpeg': 
       imagejpeg($tmp, $path, 100); 
       break; 
      case 'image/png': 
       imagepng($tmp, $path, 0); 
       break; 
      case 'image/gif': 
       imagegif($tmp, $path); 
       break; 
      default: 
       exit; 
       break; 
     } 
     return $path; 
     /* cleanup memory */ 
     imagedestroy($image); 
     imagedestroy($tmp); 
    } 
?> 

А вот сценарий:

<?PHP 
    error_reporting(E_ALL); 
    $gallery_name = $_POST['galleryName']; 
    $gallery_title = $_POST['galleryTitle']; 
    $gallery_date = $_POST['galleryDate']; 
    $target_dir = "../galleries/".$gallery_name."/"; 
    $target_dir_high = $target_dir."high/"; 
    $target_dir_low = $target_dir."low/"; 
    $valid_formats = array("jpg", "png", "gif", "zip", "bmp"); 
    $max_file_size = 1024000000; //1mb 
    $count = 0; 

    if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){ 
     if (mkdir($target_dir, 0777, true) && mkdir($target_dir_high, 0777, true) && mkdir($target_dir_low, 0777, true)) { 
      makeFile($gallery_title, $gallery_date, $target_dir); //Makes the info file 
      // Loop $_FILES to execute all files 
      foreach ($_FILES['files']['name'] as $f => $name) {  
       if ($_FILES['files']['error'][$f] == 4) { 
        $message[] = "$name has an error"; 
        continue; // Skip file if any error found 
       }   
       if ($_FILES['files']['error'][$f] == 0) {    
        if(! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats)){ 
         $message[] = "$name is not a valid format"; 
         continue; // Skip invalid file formats 
        } else { // No error found! Move uploaded files 
         $old_name = $_FILES['files']['name'][$f]; 
         $ext = end((explode(".", $old_name))); 
         $count_padded = sprintf("%02d", $count); 
         $new_name = $gallery_name."-".$count_padded.".".$ext; 
         $image_type = $_FILES['files']['type'][$f]; 

         if(move_uploaded_file($_FILES['files']['tmp_name'][$f], resize($_FILES['files']['tmp_name'][$f], 1920, 1080, $target_dir_high, $new_name, $image_type))){ 
          list($w, $h) = getimagesize($target_dir_high.$new_name); 
          $max_size = 500; 
          $long_side = max($w, $h); 
          $ratio = ($max_size/$long_side); //This is a percentage 
          $new_width = floor($w*$ratio); 
          $new_height = floor($h*$ratio); 
          $destImage = imagecreatetruecolor($new_width, $new_height); 
          $sourceImage = imagecreatefromjpeg($target_dir_high.$new_name); 
          imagecopyresampled($destImage, $sourceImage, 0, 0, 0, 0, $new_width, $new_height, $w, $h); 
          imagejpeg($destImage, $target_dir_low.$new_name, 100); 
          imagedestroy($destImage); 
          imagedestroy($sourceImage); 
          if($count == 0){ 
           copy($target_dir_low.$new_name, $target_dir.$new_name); 
          } 
          $count++; 
          echo $message = 'Congratulations! The file '.$target_dir.$new_name.' was accepted.<br />'; 
         } 
        } 
       } 
      } 
     } else { 
      die('This gallery exists. Go back and rename.'); 
     } 
    } 
?> 
+2

http://stackoverflow.com/a/22032554/2079345 – chiliNUT

+0

вы говорите, ваш загружаете несколько файлов? го суммарного размера всех из них не может превышать max_post_size, поэтому в вашем случае 8mb – Augwa

+0

Вы должны использовать 'basename ($ galleryName)' для инициализации '$ target_dir'. Представьте, что произойдет, если кто-нибудь войдет в заголовок, который начинается с (несколько) '../'. – axiac

ответ

1

Прежде всего, необходимо проверить, если реж уже существует , используйте для этого is_dir(). т.е .:

$dir = "/home/path/dir"; 
if(is_dir($dir)) 
    { 
    echo ("dir $dir already exists"); 
    } 
else 
    { 
    echo ("dir $dir doesn't exist"); 
    } 

is_dir 

(PHP 4, PHP 5)

is_dir — Tells whether the filename is a directory
Returns TRUE if the filename exists and is a directory, FALSE otherwise.

+0

Педро, спасибо. Я думаю, что проблема в том, что я достигаю my 'post_max_size', и это вызывает эту ошибку. Поэтому, если бы я должен был разместить код в том, что вы предлагаете, я просто получаю сообщение об ошибке «каталог уже существует». Я буду больше смотреть в 'post_max_size' – ntgCleaner

Смежные вопросы