0

I'm having some trouble finishing my FTP file uploader using PHP. I'm using the example from php.net found here: http://php.net/manual/en/ftp.examples-basic.php and have modified the code slightly.

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

?>

However, the code will work for some files but not others. When it doesn't work it gives the error:

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

4

3 回答 3

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 手册中找到可能的错误代码的描述。

于 2012-10-11T13:37:19.207 回答
0

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

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

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

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

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

于 2012-10-11T13:38:48.980 回答
0

第 48 行需要更改,注意双引号和 .'/' 的消除。根据您尝试上传的文件的名称,您可能会转义部分名称。

$upload = ftp_put($conn_id, "$paths/$name", $source_file, FTP_BINARY); 
于 2013-11-01T22:44:27.670 回答