问题描述
|
我正在一个内容管理系统上工作,我必须使用php代码下载一个php文件而不执行。任何人都可以帮助我
这有点像ftp。我已经添加了上传,编辑和下载文件的选项。它工作正常。但是在下载php文件时,它是执行而不是下载...
我试过的是:
<?php
$file = $_REQUEST[\'file_name\'];
if (file_exists($file)) {
header(\'Content-Description: File Transfer\');
header(\'Content-Type: application/octet-stream\');
header(\'Content-Disposition: attachment; filename=\'.basename($file));
header(\'Content-Transfer-Encoding: binary\');
header(\'Expires: 0\');
header(\'Cache-Control: must-revalidate,post-check=0,pre-check=0\');
header(\'Pragma: public\');
header(\'Content-Length: \' . filesize($file));
include_once($file);
exit;
}
?>
解决方法
您必须加载文件内容,将内容写入请求并设置标头,以便将其解析为强制下载或八位位组流。
例如:
http://server.com/download.php?name=test.php
download.php的内容:
<?php
$filename = $_GET[\"name\"]; //Obviously needs validation
ob_end_clean();
header(\"Content-Type: application/octet-stream; \");
header(\"Content-Transfer-Encoding: binary\");
header(\"Content-Length: \". filesize($filename).\";\");
header(\"Content-disposition: attachment; filename=\" . $filename);
readfile($filename);
die();
?>
此代码无需任何修改即可工作。尽管需要验证和一些安全功能。
, 服务器以某种方式标识应执行而不是下载的文件。您必须从该处理中排除要下载的.php文件。最简单的方法可能是将文件重命名为.php.txt。
否则,您应该能够将服务器配置为不处理该特定文件或该文件所在的路径。如何执行取决于您正在运行的服务器。
, 如果此类php文件位于同一服务器/网站上,则只需将其作为普通文件打开即可,例如$fileContents = file_get_contents($filename);
如果文件在另一台服务器上,则几乎没有选择:
1)通过FTP进行访问(如果您具有登录名和访问权限)
2)在该服务器上有特殊的URL重写规则,该规则将指示Web服务器以纯文本形式发送文件而不是执行该文件(例如somefile.php.txt
)
3)在该服务器上有特殊脚本,并通过传递文件名作为参数,它将返回该文件的内容(例如http://example.com/showfile.php?file=somefile.php
)
, 这是下载php文件而不是执行它的方法。
相信我,它有效! ..download文件php,后果自负:)
<?php
function downloadThatPhp($nameOfTheFile)
{
header(\"Pragma: public\");
header(\"Expires: 0\"); // set expiration time
header(\"Cache-Control: must-revalidate,post-check=0,pre-check=0\");
header(\"Content-Type: application/text/x-vCard\");
header(\"Content-Disposition: attachment; filename=\".basename($nameOfTheFile).\";\");
header(\"Content-Transfer-Encoding: binary\");
header(\"Content-Length: \".filesize($nameOfTheFile));
@readfile($nameOfTheFile);
exit(0);
}
// and this how to use:
// download that php file with your own risk :)
$file = $_REQUEST[\'file_name\'];
$downloadThis = \"http://domain-name.com/\".$file;
if (file_exists($file)) {
downloadThatPhp($downloadThis);
}
?>
希望这可以帮助您兄弟:)
, 您可以在php.net/header上阅读很多相关内容,但是要强制下载,可以使用强制下载标头。此评论很棒,请查看! :-)
, 如果有人希望在其.htaccess文件中执行此操作:
Header set Content-Disposition attachment
AddType application/octet-stream .php
要么
<FilesMatch \"\\.(?i:php)$\">
ForceType application/octet-stream
Header set Content-Disposition attachment
</FilesMatch>