2015-11-03 121 views
1

我正在製作一個人們可以上傳圖片的網站。但是,當最終用戶上傳包含特殊字符或外來字符的圖像時,圖像確實會上傳,但不能在網站上顯示,就像服務器上不存在圖像一樣。從文件名中刪除特殊字符

我看到很多人回答的另一篇文章說,我需要使用preg_replace

但事實是,我真的不知道如何使用它。我將如何在我的代碼中使用它。

這裏是我的控制器方法:

public function upload(Requests\CreatePostsRequest $request) 
{ 
     $target_dir = "uploads/"; 
     $target_file = $target_dir . basename($_FILES['fileToUpload']["name"]); 
     $uploadOk = 1; 
     $findme = "."; 
     $pos = strpos($target_file, $findme); 
     //echo $target_file; 
     //dd($_POST); 
     echo ini_get('upload_max_filesize'); 
     echo $_FILES["fileToUpload"]["error"]; 
     $imageFileType = strtolower(substr($target_file,$pos+1)); 
     if(isset($_POST["submit"])) { 
      $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); 
       //$check = true; 
       //dd($check); 
      if($check !== false) { 
       echo "File is an image - " . $check["mime"] . "."; 
       $uploadOk = 1; 
      } else { 
       echo "File is not an image."; 
       $uploadOk = 0; 
      } 
     } 
     $filecheck = 0; 
     $orgFileName = $target_file; 
     while (file_exists($target_file)) { 
      $target_file = substr($orgFileName,0,$pos).$filecheck.substr($orgFileName,$pos); 
      $filecheck++; 

      $uploadOk = 1; 
     } 

     if ($_FILES["fileToUpload"]["size"] > 500000000*8) { 
      echo "Sorry, your file is too large."; 
      $uploadOk = 0; 
     } 

     if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" 
     && $imageFileType != "gif") { 
      echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; 
       echo $imageFileType; 
      $uploadOk = 0; 
     } 

     if ($uploadOk == 0) { 
      echo "Sorry, your file was not uploaded."; 

     } else { 
      if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { 
       echo "The file ". basename($_FILES["fileToUpload"]["name"]). " has been uploaded."; 

         $post = new Posts($request->all()); 
         $post->fileToUpload = $target_file; 
         Auth::user()->posts()->save($post); 
      } else { 
       echo "Sorry, there was an error uploading your file."; 
      } 
     } 
     return redirect(''); 
     echo $target_file; 
    } 

回答

6

使用預浸取代:

$target_file = $target_dir . preg_replace("/[^A-Za-z0-9\_\-\.]/", '', basename($_FILES['fileToUpload']["name"])); 

這將刪除,這不是一個字母(az),數字(0-9)或所有字符短劃線,下劃線或點(我們希望保留文件擴展名)。

+0

這不起作用,它不會刪除文件名中的「+」。我做對了嗎? '$ target_dir =「uploads /」; \t \t \t $ target_file = $ target_dir。基名($ _ FILES [ 'fileToUpload'] [ 「名稱」]); \t \t \t $ TARGET_FILE = preg_replace函數( 「/ [^ A-ZA-Z0-9 \ _ \ - ] /」, '',$ TARGET_FILE);' –

+0

喔NVM!我沒有看到你編輯答案,謝謝它工作! –

+1

@EiðurGeirVilhelmsson - 真棒。是的,我保存按鈕有點快。有做過幾次改變.. Lycka直到:) –