2012-10-11 32 views
0

我在使用PHP完成我的FTP文件上傳器時遇到了一些麻煩。我使用php.net中的示例在這裏找到:http://php.net/manual/en/ftp.examples-basic.php並稍微修改了代碼。PHP FTP上傳錯誤:警告:ftp_put()[function.ftp-put]:文件名不能爲空

<?php 
//Start session(); 
session_start(); 

// Checking the users logged in 
require_once('config.php'); 

//Connect to mysql server 
    $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); 
    if(!$link) { 
     die('Failed to connect to server: ' . mysql_error()); 
    } 

    //Select database 
    $db = mysql_select_db(DB_DATABASE); 
    if(!$db) { 
     die("Unable to select database"); 
    } 

$ftp_server="*"; 

$ftp_user_name="*"; 

$ftp_user_pass="*"; 

$paths="members/userUploads"; 

$name=$_FILES['userfile']['name']; 

$source_file=$_FILES['userfile']['tmp_name']; 

// set up basic connection 
$conn_id = ftp_connect($ftp_server); 

// login with username and password 
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); 

// check connection 
if ((!$conn_id) || (!$login_result)) { 
    echo "FTP connection has failed!"; 
    echo "Attempted to connect to $ftp_server for user $ftp_user_name"; 
    exit; 
} else { 
    echo "Connected to $ftp_server, for user $ftp_user_name"; 
} 

// upload the file 
$upload = ftp_put($conn_id, $paths.'/'.$name, $source_file, FTP_BINARY); 

// check upload status 
if (!$upload) { 
    echo "FTP upload has failed!"; 
} else { 
    $CurrentUser = $_SESSION['CurrentUser']; 
    $qry = "SELECT * FROM members WHERE username='$CurrentUser'"; 
    $result = mysql_query($qry); 
    $result = mysql_fetch_array($result); 
    $CurrentUser = $result[memberID]; 
    $qry = "INSERT into uploads (UploadPath, UploadUser) VALUES('$file_name', '$CurrentUser')"; 
    echo "Uploaded $source_file to $ftp_server as $paths.'/'.$name"; 
} 

// close the FTP stream 
ftp_close($conn_id); 

?>

然而,代碼將一些文件,但不是別人的工作。當它不工作,它給人的錯誤:

Warning: ftp_put() [function.ftp-put]: Filename cannot be empty in ... on line 48.

+0

什麼文件這不起作用?檢查$ _FILES ['userfile'] ['name']','$ _FILES ['userfile'] ['tmp_name']'總是有值。 – pankar

回答

1

name可以發送文件時不如果有一個錯誤設置。這會導致您嘗試上傳到members/userUploads/,這會導致ftp_upload正確地抱怨空文件名。

錯誤的常見原因是超過了允許的最大文件大小。最起碼,檢查$_FILES進入你的文件error嘗試的FTP上傳前:

if ($_FILES['userfile']['error'] != UPLOAD_ERR_OK) { 
    // handle the error instead of uploading, e.g. give a message to the user 
} 

您可以找到PHP手冊的description of the possible error codes

0

這可能來自$ name或$ source_file爲空,也許文件上傳有時會失敗並導致問題。你可以嘗試使用,如果某處,以確保文件被上傳,例如:

if (empty($name)) { 
    die('Please upload a file'); 
} 

只是要注意,除非你正在使用的字符串變量,比如:

echo "Connected to $ftp_server, for user $ftp_user_name"; 

其最好使用單引號。從技術上講,它更快,雙引號,因爲它不掃描字符串的變量。另外我認爲它看起來更整潔! :)

0

第48行需要更改,請注意雙引號和。'/'的消除。根據您嘗試上傳的文件的名稱,您可能會轉義其部分名稱。

$upload = ftp_put($conn_id, "$paths/$name", $source_file, FTP_BINARY); 
相關問題