2016-05-15 83 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