PHP FTP上传错误:警告:ftp_put()[function.ftp-put]:文件名不能为空

时间:2012-10-11 13:26:49

标签: php file upload ftp

我在使用PHP完成FTP文件上传器时遇到了一些麻烦。我正在使用php.net中的示例:http://php.net/manual/en/ftp.examples-basic.php并稍微修改了代码。

<?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); 

&GT;

但是,代码适用于某些文件,但不适用于其他文件。当它不起作用时,它会给出错误:

  

警告:ftp_put()[function.ftp-put]:第48行的文件名不能为空。

3 个答案:

答案 0 :(得分:1)

如果发送文件时出错,则可能未设置name。这会导致您尝试上传到members/userUploads/,这会导致ftp_upload正确地抱怨空文件名。

错误的常见原因是超出了允许的最大文件大小。在尝试FTP上传之前,请至少检查文件的error条目中的$_FILES

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

答案 1 :(得分:0)

这可能来自$ name或$ source_file为空,也许文件上传有时会失败并导致问题。您可以尝试在某处使用if来确保上传文件,例如:

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

请注意,除非您在字符串中使用变量,例如:

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

最好使用单引号。从技术上讲,双引号的速度更快,因为它不会扫描字符串中的变量。另外我认为它看起来更整洁! :)

答案 2 :(得分:0)

第48行需要更改,请注意双引号并删除。'/'。根据您尝试上传的文件的名称,您可能正在逃避其名称的一部分。

$upload = ftp_put($conn_id, "$paths/$name", $source_file, FTP_BINARY);