问:我有一个下载页面,单击链接时需要运行功能。该功能应该在mysql数据库表中输入一行并下载文件。我不知道是否对函数进行了错误编码或对onclick进行了错误编码。这是页面的开始:
<?php
$filename = NULL;
session_start();
// start of script every time.
// setup a path for all of your canned php scripts
$php_scripts = '/home/larry/web/test/php/'; // a folder above the web accessible tree
// load the pdo connection module
require $php_scripts . 'PDO_Connection_Select.php';
require $php_scripts . 'GetUserIpAddr.php';
require $php_scripts . 'mydloader.php';
//*******************************
// Begin the script here
$ip = GetUserIpAddr();
if (!$pdo = PDOConnect("foxclone")):
{
echo "Failed to connect to database" ;
exit;
}
endif;
//exit;
?>
<DOCTYPE html>
<html lang="en">
<head>
<title>Download</title>
<script type="text/javascript">
function myFunc($arg) {
var filename
filename = $arg
ip = GetUserIpAddr();
$stmt = $pdo->prepare("INSERT INTO download (IP_ADDRESS, FILENAME) VALUES (?, ?)");
$stmt->execute([ip,filename]) ;
header('Content-Type: octet-stream');
header('Content-Disposition: attachment; filename="'.$_GET['filename'].'"');
header('Pragma: no-cache');
header('Expires: 0');
readfile("download/{filename}");
}
</script>
这是调用函数的部分:
<!-- DOWNLOAD -->
<div id="download" class="stylized">
<div "myform">
<div class="container">
<div class="row">
<div class="download">
<br /><br>
<h1><center>FoxClone Download Page</center></h1>
<?php
$isos = glob('download/*.iso');
$iso = $isos[count($isos) -1];
$isoname = basename($iso);
$md5file = md5_file($iso);
?>
<div class="container">
<div class="divL">
<h3>Get the "<?php echo "{$isoname}";?>" file (approx. 600MB)</h3>
<a href="#" onclick="myfunc("<?php echo "{$isoname}";?>)";><img src="images/button_get-the-app.png" alt=""> </a>
感谢您的任何提前帮助,
答:此函数是javascript函数,您无法在javascript中运行PHP代码。(PHP是服务器端,而javascript是客户端)
这是我用来打开网址的javascript中的一个简单函数:
function openPopup(url,name,h,w){
var newWindow = window.open(url,name,'height='+h+',width='+w);
if(window.focus){newWindow.focus();}
}
所以你会做:
<a href="#" onclick="openPopup('https://www.example.com/fileDownload.php?file=<?php echo "{$isoname}";?>', 'window name',250,250);";><img src="images/button_get-the-app.png" alt=""> </a>
然后,您需要在URL的末尾有一个php页面,该页面将打开并发送带有适当标题的文件。
答:您实际上无法做到这一点,PHP在Web服务器上运行并将HTML页面输出到浏览器。
因此,整个脚本已经运行并将HTML代码发送到用户浏览器,并且他具有下载页面,这时您无法运行PHP函数,因为PHP在Web服务器上。
您必须在网页内发送javascript代码,该代码将向网络服务器发送另一个请求以获取要下载的文件。我之前包含的openPopup函数将执行此操作。
就像在Microsoft网站下载页面上一样-您无法从自己的计算机上下载文件-该文件不存在。您必须与Web服务器建立另一个连接才能向您发送文件。它所连接的PHP文件不必太复杂,只需验证允许连接的人下载该文件并让PHP从磁盘读取文件并输出即可。
这是我发现的在PHP中输出图像的简单示例:
<?php
$file = '../image.jpg';
$type = 'image/jpeg';
header('Content-Type:'.$type);
header('Content-Length: ' . filesize($file));
readfile($file);
?>
将其保存为自己的PHP文件,就像download.php在浏览器中访问该文件一样,浏览器将获取图像。您正在尝试对ISO映像执行相同的概念。快速浏览一下,我认为您会使用iso映像,header('Content-Type: application/octet-stream');因此,当您单击下载链接时,javascript将请求发送到PHP页,该页从磁盘读取ISO映像并将其提供给用户。