2013-05-28 34 views
0

我有两个文件(html和php)。用户上传html表单中的文件,php文件包含脚本以将文件上传到服务器上。 它完美的工作,我的问题是当用户1上传'wordThing.docx'和用户2出现并上传'wordThing.docx'时,用户1的文件将被覆盖。如何在PHP中添加输入文件名的详细信息

这里是我的HTML代码:

<html> 
<body> 
<form action="upload_file.php" method="post" enctype="multipart/form-data"> 
<label for="file">Filename:</label> 
<input type="file" name="file" id="file"><br /> 

<label for="yourName">Your name:</label> 
<input type="textbox" name="yourName" id="yourName" /><br /> 
<input type="submit" name="submit" value="Submit"><br /> 
</form> 
</body> 
</html> 

这是我的PHP脚本:

<?php 
$userName=$_POST['yourName']; 
$target_path = "uploads/"; 
$target_path = $target_path . basename($_FILES['uploadedfile']['name']); 
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) 
{ 
    echo "The file ". basename($_FILES['uploadedfile']['name']). 
    " has been uploaded"; 
} 
else 
{ 
    echo "There was an error uploading the file, please try again!"; 
} 
?> 

我想用户将进入 'YOURNAME' 文本连接。因此,服务器包含不同的文件名,并且不必重写。 因此,假设用户具有不同的名称,我想知道如何将文件保存在服务器上并附上名称。例如:用户1的文件上传将是'wordThingSusan.docx'

我希望这不是太多的信息。我只是想要清楚准确。 为了防止有人试图使用此代码,您需要在目录下有一个名为“uploads”的文件夹才能使用。

+0

您的代码假定上传总是成功。 **不是**一个好主意。总是检查'$ _FILES ['uploadedfile'] ['error']'非零代码,这表明失败。 –

+0

谢谢,马克。将研究它。 –

回答

2

变化

$target_path = $target_path . basename($_FILES['uploadedfile']['name']); 

$target_path = $target_path . time() . rand(11, 99) . basename($_FILES['uploadedfile']['name']); 

所产生的名字会像上传/ 123456789052wordThing.docx

时间()会给你时间格式1234567890,兰特( 11,99)将产生11到99之间的随机数,因此即使2个人同时上传同一文件,该文件也不会被覆盖。

+0

谢谢,Deepsy。我希望我能想到这一点。使一个很大的意义... –

+0

Deepsy,有没有一个原因,我不能上传PDF文件与我的脚本?我尝试了其他文件,图像,文档等...但我的PDF文件不会上传。 –

+0

@EliSkywalker我在下面的代码中看不到任何格式限制,它应该适用于每种格式。你有什么错误吗?你确定文件没有被破坏吗?您可以尝试打印$ _FILES ['uploadedfile'] ['error']以查看它是否返回任何错误代码。还有move_uploaded_file()失败? – Deepsy

1

只需添加一个Unix时间戳的文件名开头:

<?php 
    $userName=$_POST['yourName']; 
    $target_path = "uploads/"; 
    $target_path = $target_path . date('U') . '_' . basename($_FILES['uploadedfile']['name']); 
    if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) 
    { 
     echo "The file ". basename($_FILES['uploadedfile']['name']). " has been uploaded"; 
    } else { 
     echo "There was an error uploading the file, please try again!"; 
    } 

>

+0

谢谢,菲尔... –

0

我会看看到file_exists方法:

http://php.net/manual/en/function.file-exists.php

如果检查出来回到文件已经存在我会重命名文件,然后用新名称保存它。

这就是我将如何尝试它。

+0

啊,是的......检查文件是否存在,如果条件为真保存在不同的名称中,否则就保存。尼斯。 –

相关问题