2015-02-07 2 views
0

현재 내 코드는 사용자가 제출 한 이미지의 이름으로 이미지 파일을 업로드합니다. 이제 분명히 문제를 덮어 쓰지 않기 위해 이것을 바꾸고 싶습니다. 자, 다른 제안을 한 번 보았습니다 만, 코드로 작업 할 수없는 것 같습니다 (필자는 몇 달 동안 PHP 만 배웠습니다). 그래서, 너희들이 나를 도울 수 있니? 여기업로드 후 파일 이름을 변경하는 방법 PHP

<?php 
$target_dir = "avatars/"; 
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); 
$uploadOk = 1; 
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); 
// Check if image file is a actual image or fake image 
if(isset($_POST["submit"])) { 
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); 
    if($check !== false) { 
     //echo "File is an image - " . $check["mime"] . "."; 
     $uploadOk = 1; 
    } else { 
     echo "File is not an image."; 
     $uploadOk = 0; 
    } 
} 
// Check if file already exists 
if (file_exists($target_file)) { 
    echo "Sorry, file already exists."; 
    $uploadOk = 0; 
} 
// Check file size 
if ($_FILES["fileToUpload"]["size"] > 500000) { 
    echo "Sorry, your file is too large."; 
    $uploadOk = 0; 
} 
// Allow certain file formats 
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" 
&& $imageFileType != "gif") { 
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; 
    $uploadOk = 0; 
} 
// Check if $uploadOk is set to 0 by an error 
if ($uploadOk == 0) { 
    echo "Sorry, your file was not uploaded."; 
// if everything is ok, try to upload file 
} else { 
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { 
     //echo "The file ". basename($_FILES["fileToUpload"]["name"]). " has been uploaded."; 
    } else { 
     echo "Sorry, there was an error uploading your file."; 
    } 
} 
?> 

내 생각 엔 내가 move_uploaded_file 코드를 변경해야 할 것입니다 업로드 코드입니까? 어떤 도움을 주셔서 감사합니다!

+0

그것은 이미 스크립트처럼 보인다 감지합니다. 이것에

$target_dir = "avatars/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); 

같은 이름이 주어지면 –

+0

예, 원래 이미지의 이름을 가져 왔지만 이미지를 서로 덮어 쓰지 않도록 업로드 한 후에 이미지 이름을 변경하고 싶습니다. – MyNameIsNotSoCool

+0

'$ target_file'은 이름과 위치가 잘 맞습니다. '싼'방법은 이름에 타임 스탬프를 추가하는 것입니다 (바쁜 사이트에서는 사용하지 마십시오) –

답변

4

변경이 : 당신이 그것을 이동하기 전에

$rand = rand(10000000, 999999999); 
$time = time(); 
$file_name = $rand.$time.$_FILES["fileToUpload"]["name"]; 
$target_dir = "avatars/"; 
$target_file = $target_dir . $file_name; 
+0

타임 스탬프 'time()'을 사용하여 rand 또는 by-its 자체를 사용하는 것이 좋습니다. –

+0

@Dagon Yep, 그게 더 잘 작동합니다. 두 가지 개념을 결합하는 코드를 업데이트합니다. – three3

+0

고마워요 :) 이것으로 해결되었습니다! – MyNameIsNotSoCool

1

이 파일의 이름을 바꿉니다 (가 종료 된 경우)

// Check if file already exists 
if (file_exists($target_file)) { 
    $temp = explode(".", $_FILES["fileToUpload"]["name"]); //getting the image extension 
    $target_file = $target_dir . rand(1,99999).'.'.end($temp); 
    $uploadOk = 0; 
} 
+0

@Dagon 이것은 당신이 장님이되기 전에입니까? – julekgwa

+0

@ 대각군 임시 폴더에 아직 있습니다. – julekgwa

+0

@ 대각선 내 코드가 무엇인지보고, 지정된 디렉토리에 이미지가 있는지 확인한 다음 새 이름을 지정하면 파일을 이동할 때 새 이름을 사용할 수 있습니다. – julekgwa

관련 문제