开发者

How to attach mysql_insert_id in a file upload?

how do we attach mysql_insert_id() in a file uploads so that each file gets unique name ? I did try the following code but didn't work. please advice. Yhanks

$id = mysql_insert_id();
$dest = trim($uploaddir. $id. basename($_FILES['p开发者_高级运维hoto']['name']));


This should be

if(false !== ($id = mysql_insert_id())
{
    $dest = sprintf("%s%d_%s",$uploaddir,$id,trim(basename($_FILES['photo']['name']));
    if(!file_exists($dest))
    {
        //move_uploaded_file
    }else
    {
        //You cant program :(
    }
}else
{
    //DB Error.
}

You should write your code so you add the file to the directory before you add to database.

  • Get the data from $_FILES
  • Sanitize the data and validate the file Size,Ext,Headers,Name
  • Make sure the file does not already exists
  • Generate a UniqueID and create a hash from a static string, Example 1
  • Store the file on the server and verify its move ok
  • Add meta data to the database along with the unique ID and file location
  • Bobs your uncle.

Example 1:

define('FILE_NAME_SALT','MySecret$alt');

$uid = md5(rand(0,100) . $uid . FILE_NAME_SALT . $FileName);

Store file like HASH.ext


This is a problem that you can take some steps to solve yourself before asking. For starters, print out $id. Is it a valid Id? Or is it FALSE (it might be). Then echo out $uploaddir, $_FILES['photo']['name'], and basename($_FILES['photo']['name']). Finally, echo out $dest. I'd be rather surprised if you don't catch the mistake by doing these simple debugging exercises.


You could use a hashing function to do this. For example, md5 or sha1 are good choices for unique filenames. You could use a filename that the md5() function returns given the file's initial name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜