2011-02-23 3 views
2

잘 작동하는이 간단한 스크립트가 있지만 현재 중복 된 이름으로 파일을 덮어 씁니다. 어떻게 이것을 피할 수 있습니까?덮어 쓰기를 방지하기 위해 업로드 된 파일의 이름을 변경하십시오.

<?php 
    // Configuration - Your Options 
    $allowed_filetypes = array('.mp3'); // These will be the types of file that will pass the validation. 
    $max_filesize = 1048576; // Maximum filesize in BYTES (currently 0.5MB). 
    $upload_path = './uploads/'; // The place the files will be uploaded to (currently a 'files' directory). 

    $filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension). 
    $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename. 

    if(!in_array($ext,$allowed_filetypes)) 

     header('Location: http://www.website.com/five/error'); 

    if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize) 

     header('Location: http://www.website.com/five/error'); 

    if(!is_writable($upload_path)) 

     header('Location: http://www.website.com/five/error'); 

    if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename)) 

//   echo 'Your file upload was successful, view the file <a href="' . $upload_path . $filename . '" title="Your File">here</a>'; // It worked. 
     header('Location: http://www.website.com/five/sent'); 

    else 

     header('Location: http://www.website.com/five/error'); 

?> 
+1

당신은 정말'exit()를 추가해야합니다에 대한 좋은 확장 '리디렉션합니다. 그렇지 않으면 헤더를 보낸 후에도 여전히 업로드를 완료하려고 시도 할 수 있습니다. 이 경우에도'if' 문 각각에'{}'중괄호를 사용해야합니다. – Adam

+0

이 답변은 매우 흥미 로울 수 있습니다 :
[ "PHP로 업로드 스크립트를 만들었습니다. 어떻게 파일을 덮어 쓰는 것을 피합니까?"] (http://stackoverflow.com/questions/846340/i-made-an- php-how-do-i-avoid-overwriting-file에서 스크립트 업로드/7267751 # 7267751) – SteakOverflow

답변

2

업로드하기 전에 if (file_exists($upload_path.$filename))을 추가하고 $filename을 다른 것으로 설정하십시오.

0

원본 대신 사용자 이름을 사용하십시오.

이것은 예 uniqid()

0

상점 이름 등의 해시 파일을 통해 생성 될 수 있으며, 해시와 함께 데이터베이스/플랫 파일의 원래 이름을 저장한다.

플랫 파일을 사용하려는 경우 사용자 파일이 .dat로 저장되고 파일 정보가 .json 또는 .xml 또는 원하는 경우 직렬화 된 PHP 개체로 저장 될 수 있습니다.

또한 파일 확장명 검색 논리는 파일 이름에 점 (마침표)이 두 개 이상 있으면 즉시 실패합니다.

1

하나의 옵션은 고유 한 ID와 함께 원래 이름을 저장하는 데이터베이스를 사용하는 것입니다.

그런 다음 원하는 고유 한 이름으로 파일을 저장할 수 있습니다.

  • 를 사용하여 바로 아이디 ... 파일 = 1
  • 사용하여 ID와 확장 = ID와 이름의 1.MP3
  • 사용 조합 = 1_name_of_file.mp3
  • 또는 다른 독특한 이름 지정 옵션.

그런 다음 파일을 제공하기 위해 PHP를 사용합니다. 원래 파일 이름으로 헤더 설정.

사용자는 파일을 저장하는 방법을 알지 못합니다. 동일한 이름의 여러 파일을 해당 이름으로 업로드 및 다운로드 할 수 있지만 서버에 고유하게 저장됩니다.

<?php 

$actualFile = './uploads/'.$id; 

// Can use some smarts to determine the mime type here 
header('Content-type: application/force-download'); 

// The user will be prompted to save it as the filename given here. 
header('Content-Disposition: attachment; filename="'.$originalName.'"'); 
header("Content-Length: ".filesize($actualFile)); 


// The actual file on the server 
readfile($actualFile); 
?> 

캐싱 등에 설정할 수있는 여러 가지 다른 헤더 옵션이 있습니다. 반환``또는;`은`헤더의 각 후()

http://php.net/manual/en/function.header.php

에서는 FileInfo가 결정 MIME 형식

http://www.php.net/manual/en/function.finfo-file.php

관련 문제