好的,所以我希望我的用户能够下载一个带有用户名的.txt
文件。
我到处都查过了,但到目前为止,我找不到我想要的东西,也找不到是否可能。
为了给你一个我试图做什么的例子,这里是我的代码:
<button type="button">Download All Your Keys On A .txt
<?php
$file = 'logs/$session->username.txt';
if(!file_exists($file)) die("I'm sorry, the file doesn't seem to exist.");
$type = filetype($file); // Get a date and timestamp $today = date("F j, Y, g:i a"); $time = time(); // Send file headers header("Content-type: $type"); header("Content-Disposition: attachment;filename=$filename");
header("Content-Transfer-Encoding: binary");
header('Pragma: no-cache');
header('Expires: 0'); // Send the file contents.
set_time_limit(0);
readfile($file);
?>
</button>
我试图让它,当你点击按钮时,它会强制下载的.txt文件配置为:
$file = 'logs/$session->username.txt';
如果这让人感到困惑和混乱,我很抱歉,但我没有其他方式来表达这一点。
提前感谢!
为什么不把这些代码放在一个单独的文件中,比如download.php
:
<?php
$file = "logs/{$session->username}.txt";
if(!file_exists($file)) die("I'm sorry, the file doesn't seem to exist.");
$type = filetype($file);
// Get a date and timestamp
$today = date("F j, Y, g:i a");
$time = time();
// Send file headers
header("Content-type: $type");
//** If you think header("Content-type: $type"); is giving you some problems,
//** try header('Content-Type: application/octet-stream');
//** Note filename= --- if using $_GET to get the $file, it needs to be "sanitized".
//** I used the basename function to handle that... so it looks more like:
//** header('Content-Disposition: attachment; filename=' . basename($_GET['mygetvar']));
header("Content-Disposition: attachment;filename={$session->username}.txt");
header("Content-Transfer-Encoding: binary");
header('Pragma: no-cache');
header('Expires: 0');
// Send the file contents.
set_time_limit(0);
ob_clean();
flush();
readfile($file);
//** If you are going to try and force download a file by opening a new tab via javascipt
//** (In this code you would replace the onClick() event handler in the html
//** button with onclick="window.open('www.someurl.com', '_blank');"
//** - where 'www.someurl.com' is the url to the php page - I keep the file
//** creation and download handling in the same file, and $_GET the file name
// - bad practice? Probably, but I never claimed to be an expert),
//** be sure to include exit(); in this part of the php...
//** otherwise leave exit(); out of the code.
//** If you don't, it will likely break the code, based on my experience.
//exit();
?>
请注意,您必须将引号更改为双引号,因为您在'
s中使用了一个变量。因此,要展开该变量,请将第一行更改为:
$file = "logs/{$session->username}.txt";
在这里,我认为$session->username
是您试图引用的变量。
在HTML:中有这个
<button type="button" onclick="location.href='download.php'">Download All Your Keys On A .txt</button>
当你点击这个按钮时,它会重定向到download.php
,启动txt文件的下载。就这么简单。但这需要你有两个文件。我不明白这里需要一个按钮。为什么不使用这样一个简单的链接呢?
<a href="download.php">Download All Your Keys On A .txt</a>
如果你需要的话,你可以用CSS来设计它的样式。