2013-02-28 2 views
0

사용자가 내 웹 사이트에 이미지를 업로드 할 수있게하려고합니다. 현재 사용중인 PHP 코드는 업로드 된 파일 형식이 잘못되었음을 나타냅니다. 나는 많은 수의 이미지를 시도했으며 모두이 오류를 제공합니다.특정 파일 형식을 PHP에서 허용하기

다음은 PHP 코드입니다.

<?php 
    // Configuration - Your Options 
     $allowed_filetypes = array('.jpg','.gif','.bmp','.png','.jpeg'); // These will be the types of file that will pass the validation. 
     //$max_filesize = 524288; // 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. 

    // Check if the filetype is allowed, if not DIE and inform the user. 
    if(!in_array($ext,$allowed_filetypes)) 
     die('The file you attempted to upload is not allowed.'); 

    // Now check the filesize, if it is too large then DIE and inform the user. 
    if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize) 
     die('The file you attempted to upload is too large.'); 

    // Check if we can upload to the specified path, if not DIE and inform the user. 
    if(!is_writable($upload_path)) 
     die('You cannot upload to the specified directory, please CHMOD it to 777.'); 

    // Upload the file to your specified path. 
    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. 
     else 
     echo 'There was an error during the file upload. Please try again.'; // It failed :(. 

?> 

다음은 HTML 양식 코드입니다.

<form action="upload.php" method="post" enctype="multipart/form-data"> 
    <p> 
     <label for="file">Select a file:</label> <input type="file" name="userfile" id="file"> <br /> 
     <button>Upload File</button> 
    <p> 
</form> 
+0

양식에 제출 버튼이없는 것 같습니다 –

+0

잘못된 코드입니다. 업로드가 성공했다고 가정합니다. 업 로더가 파일 이름 (예 : ren nastyvirus.exe cutekittens.jpg)을 위조하지 않았다고 가정하고 서버 레벨에서 시행되어야하는 크기 검사를 시작하고 사용자가 경로를 지정하도록 허용합니다 ** AND * * 파일 이름을 사용하여 서버의 모든 디렉토리를 쓸어 넘길 수 있습니다. –

답변

0

이 코드에는 파일 확장명을 가져 오는 코드가 일반적으로 올바르게 작동하지 않는 문제가 있습니다. 이로 교체, 또한 현재의 문제를 해결해야합니다

$ext = pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION); 
$allowed_filetypes = array('jpg','gif','bmp','png','jpeg'); 

당신은 또한 확실히 위의 Marc의 경고에주의해야한다.

+0

파일을 업로드 할 때 여전히 오류가 발생합니다. – eek

+0

@WillGilstrap : 음,'$ ext'의 가치는 무엇입니까? – Jon

+0

나는 잘 모른다. 나는 PHP에 매우 기초적이다. – eek

관련 문제