2012-02-16 4 views
1

Хорошо, я пытаюсь создать веб-страницу, где она загружает фотографию в папку в htdocs Apache. И ... ну ... это не работает ... Я искал везде учебники по этому поводу, и все это нужно делать на PHP (некоторым HTML также разрешено [No flash]).PHP Загрузка файла в папку (в apache)

Вот что у меня есть ....

<p>Browse For a File on your computer to upload it!</p> 
<form enctype="multipart/form-data" action="upload_photos.php" method="POST"> 
<input type="hidden" name="MAX_FILE_SIZE" value="250000" /> 
Choose a file to upload: <input name="uploadedfile" type="file" /><br /> 
<input type="submit" value="Upload File" /> 
</form> 


     <?PHP  

    if ($uploadedfile_size >250000) 
    {$msg=$msg."Your uploaded file size is more than 250KB so please reduce the file size and then upload.<BR>"; 
    $file_upload="false";} 

    else{ 

    if (!($uploadedfile_type<>"image/jpeg" OR $userfile_type<>"image/tiff" OR $userfile_type<>"image/png")) 
    {$msg=$msg."Your uploaded file must be of JPG, PNG, or tiff. Other file types are not allowed<BR>"; 
    $file_upload="false";} 

    } 
     ?> 

     <!-- 
    •enctype="multipart/form-data" - Necessary for our PHP file to function properly. 
    •action="upload_photos.php" - The name of our PHP page that was created. 
    •method="POST" - Informs the browser that we want to send information to the server using POST. 
    •input type="hidden" name="MA... - Sets the maximum allowable file size, in bytes, that can be uploaded. This safety mechanism is easily bypassed and we will show a solid backup solution in PHP. We have set the max file size to 100KB in this example. 
    •input name="uploadedfile" - uploadedfile is how we will access the file in our PHP script. 

     --> 

</form> 

    </label> 
</form> 

Теперь он получает за эту точку, однако, как только он попадает на другую страницу (upload_photos.php) он говорит: «Был ошибка загрузки файла , пожалуйста, попробуйте снова!"

<?php 

/* 
When the uploader.php file is executed, the uploaded file exists in a temporary storage area on the server. If the file is not moved to a different location it will be destroyed! To save our precious file we are going to need to make use of the $_FILES associative array. 

The $_FILES array is where PHP stores all the information about files. There are two elements of this array that we will need to understand for this example. 
•uploadedfile - uploadedfile is the reference we assigned in our HTML form. We will need this to tell the $_FILES array which file we want to play around with. 
•$_FILES['uploadedfile']['name'] - name contains the original path of the user uploaded file. 
•$_FILES['uploadedfile']['tmp_name'] - tmp_name contains the path to the temporary file that resides on the server. The file should exist on the server in a temporary directory with a temporary name. 

*/ 

// Where the file is going to be placed 
$target_path = "uploads/"; 

/* Add the original filename to our target path. 
Result is "uploads/filename.extension" */ 
$target_path = $target_path . basename($_FILES['uploadedfile']['name']); 


/* 
Now all we have to do is call the move_uploaded_file function and let PHP do its magic. The move_uploaded_file function needs to know 1) The path of the temporary file (check!) 2) The path where it is to be moved to (check!). 
*/ 

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { 
    echo "The file ". basename($_FILES['uploadedfile']['name']). 
    " has been uploaded"; 
} else{ 
    echo "There was an error uploading the file, please try again!"; 
} 


/* 

If the upload is successful, then you will see the text "The file filename has been uploaded". This is because move_uploaded_file returns true if the file was moved, and false if it had a problem. 

If there was a problem then the error message "There was an error uploading the file, please try again!" would be displayed. 

*/ 

?> 

Пожалуйста, помогите мне, я просмотрел его по строкам, и я не знаю, почему он это делает. Возможно, это синтаксическая ошибка или что-то еще. Я совершенно новый для PHP, поэтому я не сомневаюсь в этом. Во всяком случае, спасибо заранее.

+0

изменить $ target_path на полный путь к серверу. –

+0

Какие у вас настройки Apache? Apache также может устанавливать ограничения на типы и размеры файлов. И что говорит ваш журнал ошибок Apache? –

+0

«Я совершенно новый для PHP» --- и это отличный шанс научиться отлаживать ** ваш ** код. Никто не сделает это за вас, и это ваша повседневная работа программиста. – zerkms

ответ

0

Опускаем PHPinfo() файл вниз, и проверить, что Apache имеет для upload_max_filesize под CORE. Это может быть слишком низким.

Если вы его просмотрели, проверьте разрешения на целевой каталог. Убедитесь, что целевой каталог установлен на 775 или просто chmod целевой каталог, прежде чем писать на него.

0

изменение:

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { 
    echo "The file ". basename($_FILES['uploadedfile']['name']). 
    " has been uploaded"; 
} else{ 
    echo "There was an error uploading the file, please try again!"; 
} 

к:

то дайте нам знать, что var_dump возвращает

+0

Я сделаю это немного. Сейчас мой ноутбук в настоящее время делает обновления (конечно), и я попробую это, как только это будет сделано. (Я только что получил ноутбук недавно, так что есть много обновлений Windows) –

+0

в порядке, единственное, что возвращает var_dump, - «bool (false)». и я также попытался изменить $ target_path на полный путь ... Теперь я попробую разрешения chmod –

Смежные вопросы