我正在学习PHP并尝试创建一个简单的php上传和下载脚本连接到mysql数据库。我使用uid()为每个文件生成一个特殊的id并将其存储在数据库中。我差不多完成但问题是我无法弄清楚如何编写download.php代码? 请帮我。我正在分享我的index.php,upload.php和download.php当前文件。
我的index.html有这个表单
<form enctype="multipart/form-data" action="uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
我的Uploader.php文件包含此代码
$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";
}
$uid = uniqid();
$filename = basename( $_FILES['uploadedfile']['name']);
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'INSERT INTO replitz_file '.
'(file_uid,file_name) '.
'VALUES ( "$uid", "$filename" )';
mysql_select_db('replitz');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "http://localhost/Project/download.php?$uid";
mysql_close($conn);
我的Download.php代码是
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$db = mysql_select_db('replitz', $con);
$file = $_GET['_'];
$query = "SELECT * FROM replitz_files WHERE id='$file_uid'";
$result = mysql_query($query);
$r = mysql_fetch_array($result);
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Link Not Valid: ' . mysql_error());
echo "Link Not Valid";
mysql_close($conn);
现在请告诉我应该在Download.php中使用哪些代码从存储在数据库中的uid()生成的代码下载文件。
答案 0 :(得分:0)
您可以直接从dowload.php下载文件,方法是指定自定义标头并使用readfile包含该文件。查看此堆栈问题: How to return a file in PHP