在数据库中存储多个上载文件的最佳方法

时间:2011-08-01 20:30:56

标签: php loops upload

我目前有一个PHP上传表单,可以让用户上传多个文件。这是上传文件的后端脚本。

while(list($key,$value) = each($_FILES[images][name]))
{
if(!empty($value)){   // this will check if any blank field is entered
$filename = $value;    // filename stores the value


$filename=str_replace(" ","_",$filename);// Add _ inplace of blank space in file name, you can remove this line


$file_ext = @strtolower(@strrchr($filename,"."));
$file_ext = @substr($file_ext, 1); // remove dot
$filename = md5(uniqid(rand(), true)) . '.' . $file_ext;


$add = "/html/uploaded/$filename";   // upload directory path is set
copy($_FILES[images][tmp_name][$key], $add);     //  upload the file to the server
chmod("$add",0777); 

}
}

在这个while循环之后,我运行一个SQL查询将信息插入到我的数据库中。如何确保第一个文件存储为$ file1,第二个文件存储为$ file2等。

我尝试计算循环以确定哪个数字文件是哪个,但它无效。

2 个答案:

答案 0 :(得分:2)

将文件存储在数据库中通常被认为是一个坏主意。将文件放在服务器的本地光盘上并将 filename 存储在数据库中,可以更好地服务。

看看你的代码,看来你实际上是在尝试这样做,所以你的问题标题有点用词不当。

您的代码存在一些结构性问题。试试这个代码:

$errors = array();
$files = array();
foreach ($_FILES['images'] as $k=>$image) {

    // handle upload errors
    if ($image['error'] != 0 && $image['error'] != 4) {         
        switch ($image['error']) {
            case '1':
            case '2':
                $err = 'The uploaded file exceeds the maximum file size.';
                break;                  
            case '3':
                $err = 'The upload was inturupted, transfer failed.';
                break;
            case '6':
            case '7':
            case '8':
                $err = 'Server error.  Please try again later.';
                break;
        }
        // record error and move on
        $errors[] = array('image'=>$k, 'error'=>$err);
        continue;
    } elseif ($image['error'] == 4) {
        // error 4 means no image was sent
        continue;
    }

    // determine the extension
    $ext = explode('.', $image['name']);
    if (count($ext) != 2) {
        $errors[] = array('image'=>$k, 'error'=>'Could not determine file extension.');
        continue;
    } else {
        switch ($ext[1]) {
            case 'jpg':
            case 'jpeg':
            case 'gif':
            case 'png':
                break;
            default:
                $errors[] = array('image'=>$k, 'error'=>'Unsupported file extension.');
                continue;
                break;
        }
    }

    // make a random-ish filename
    $filename = time().uniqid(rand(), true) . '.' . $ext[1];
    $path = '/html/uploaded/'.$filename;   // upload directory path is set

    move_uploaded_file($image['tmp_name'], $path);     //  upload the file to the server
    // this is a bad idea right here! Use 775 at least, if possible
    chmod($path,0777);
    $files[] = array('name'=>$filename, 'path'=>$path);
}

// now loop the $files array and put the paths into the database

// you also should do something with the errors listed in $errors

修改

所以这是将这些文件放入数据库的快速而肮脏的示例。我注意到你有sizeext字段 - 如果这应该记录文件和图像的扩展名...哪一个?无论如何,如果你填写其他变量,下面的代码将把文件名放入db。

我想建议你 - 这个数据库设计有缺陷。如果您想要超过5张图片怎么办?您必须更改db表的结构并编辑代码。如果创建一个关系表结构,为每个文件插入一行并使用ID将它们全部绑定在一起(即album_id,那么你会有更好的表格,然后你有一个名为albums的表,里面有顶级信息)。

// start building up the SQL query, start with
// some fields that are straightforward
$sql = '
    INSERT INTO table_name (
        `id`,
        `status`,
        `user`,
        `title`,';

// now loop the list of files (5 only), 
// add each needed field
for ($i=1; $i < count($files) && $i < 5; $i++) {
    $sql .= '`file'.$i.'`,';
}

// build out the rest of the query, add values
// for the straightforward fields
$sql .= '
    `size`,
    `ext`,
    `ip`,
    `date`
) VALUES (
    NULL, 
    "'.$status.'",
    "'.$user.'",
    "'.$title.'",
';

// loop the files
$ct = 1;
foreach ($files as $f) {
    $sql .= '"'.$f['name'].'",';
    // only allow 5 files
    if ($ct == 5)
        break;
    $ct++;
}

// wrap up building the query
$sql .= '
    "'.$size.'",
    "'.$ext.'",
    "'.$ip.'",
    "'.$date.'"
)';

mysql_query($sql);

答案 1 :(得分:1)

首先,在for循环中访问$ _FILES等关联数组时应该使用撇号。

关于您的问题:为什么不使用$filename = sprintf('%s%d.%s', md5(uniqid(rand(), true)), $key, $file_ext);之类的内容替代$filename = md5(uniqid(rand(), true)) . '.' . $file_ext;