Computer >> 컴퓨터 >  >> 프로그램 작성 >> PHP

여러 파일을 업로드하고 PHP로 폴더에 저장하는 방법은 무엇입니까?

<시간/>

다음은 여러 파일을 업로드하고 폴더에 저장하는 단계입니다 -

  • 입력 이름은 배열로 정의되어야 합니다. 즉, name="inputName[]"
  • 입력 요소는 multiple="multiple"이거나 여러 개여야 합니다.
  • PHP 파일에서 "$_FILES['inputName']['param'][index]" 구문 사용
  • 배열에 빈 문자열이 포함될 수 있으므로 빈 파일 이름과 경로를 확인해야 합니다. 이 문제를 해결하려면 count 전에 array_filter()를 사용하십시오.

아래는 코드의 데모입니다 -

HTML

<input name="upload[]" type="file" multiple="multiple" />

PHP

$files = array_filter($_FILES['upload']['name']); //Use something similar before processing files.
// Count the number of uploaded files in array
$total_count = count($_FILES['upload']['name']);
// Loop through every file
for( $i=0 ; $i < $total_count ; $i++ ) {
   //The temp file path is obtained
   $tmpFilePath = $_FILES['upload']['tmp_name'][$i];
   //A file path needs to be present
   if ($tmpFilePath != ""){
      //Setup our new file path
      $newFilePath = "./uploadFiles/" . $_FILES['upload']['name'][$i];
      //File is uploaded to temp dir
      if(move_uploaded_file($tmpFilePath, $newFilePath)) {
         //Other code goes here
      }
   }
}

파일이 나열되고 'total_count' 변수에 업로드해야 하는 파일의 개수가 저장됩니다. 임시 파일 경로가 생성되고 폴더가 있는 이 임시 경로에 모든 파일이 반복적으로 배치됩니다.