将文件上载到目录

时间:2016-05-15 19:35:10

标签: php file

我是PHP的新手,我正在尝试将文件上传到我的ftp服务器上新创建的目录,例如新的目录名是newDir,位于根目录中,我不太清楚PHP中的路径是如何工作的,我如何在PHP中对其进行编码,但不上传文件,是我的路径,我指的是错误的?

<?php
if($_FILES){
//checking if a file is selected
if($_FILES['file']['name'] != ""){
//check if file is of type plain text file if not exit
 if(isset($_FILES) && $_FILES['file']['type'] != 'text/plain') {
 echo "<span>  This is not an accepted file format, upload a .txt   
 document</span>";

exit();
 }
 echo "<center><span id='Content'> Contents of ".$_FILES['file']['name']."  
 File</span></center>";
//Getting and storing the temporary file name of the uploaded file
 $fileName = $_FILES['file']['tmp_name'];
 //echo "File has been uploaded and saved as" . "upload/" . $_FILES['file'] 
 ['name'];
 //open file or display an error message if file cant open
 $file=fopen($fileName,"r") or exit("Sorry unable to open the selected 
 file");
//reading the contents of the .txt document line by line
while(!feof($file)){ 
echo fgets($file) . " "; 
}
// reading a .txt file character by character
while(!feof($file)){ 
echo fgetc($file); 
}
fclose($file);
}
//check if user selects a file to upload
else
  {
if(isset($_FILES) && $_FILES['file']['type'] == '')
echo "<span> Please choose a file by clicking on the 'Browse' or 'Choose     
file' buttons. </span>";
}
}
//if the user clicks on the upload
//save the file to the new created directory on the server
if(isset($_POST['submit'])){
//upload file to the server
move_uploaded_file($_FILES['file']['tmp_name'], "upload/" . $_FILES['file']
['name']);
//create a variable message to hold the file name of the uploaded file
$msg = "New file ".$_FILES['file']['name']." has been uploaded to the server
 <br />";}'

1 个答案:

答案 0 :(得分:0)

这是将文件从临时缓存文件夹移动到您希望存储文件的位置的行:

move_uploaded_file($_FILES['file']['tmp_name'], "upload/" . $_FILES['file']['name']);

现在,您正在将文件移动到此脚本当前所在目录中名为upload的目录中。这就是文件夹结构的样子:

-Current folder
    -this_script.php
    -upload
        -my_new_file.txt

如果要将脚本移动到根Web服务器文件夹下名为newDir的文件夹,则需要使用以下内容:

move_uploaded_file($_FILES['file']['tmp_name'],  $_SERVER['DOCUMENT_ROOT'] . '/newDir/' . $_FILES['file']['name']);