2016-05-15 88 views
-1

我对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 />";}' 
+0

只有一行代码没有完成剪切。从上传手册开始并进行错误检查。 –

+0

什么是NewDir?它应该是一个变种?或一个字符串? – Jeff

+0

这里需要指定的路径是相对于web-root的。并且你需要把它作为字符串在这里传递:'move_upload_file($ _ FILES ['file'] ['tmp_name'],“NewDir /”。$ _ FILES ['file'] ['name'];' – Jeff

回答

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']); 
+0

嗨,劳埃德,非常感谢,这有助于很多,当我上传我但是不认为该文件被上传到NewDir目录 - Root-> NewDir(在此文件夹内) – phenom5001

+0

@ phenom5001你可以检查,看看是否httpd/apache用户有权写入根网站文件夹? –

+0

我可能会听起来超级笨拙,但我会在哪里找到这些信息,我正在使用这些免费托管网站之一(www.freewebhostingarea.com/) – phenom5001