繁体   English   中英

当用户单击链接而不重定向到特定的 php 页面时,如何运行 php 脚本并同时下载 mp3 文件?

[英]How can I run a php script when a user clicks a link without redirecting to that particular php page, and download an mp3 file at the same time?

I have an mp3 file whose downloads value am counting and updating well in a MySQL database when I run my php script by going to the scripts address in the address bar like this https://groupkse.net/music_files/countDownloads.php?id =3 我的问题是,当单击链接下载该 mp3 时,我想运行此 php 脚本而不将我的浏览器重定向到该位置。 NB: The mp3 is in the same directory with the countDownloads.php and the page containing the link is in a different directory, but on the same server, ie https://groupkse.net/songReleaseHtml/megaMuQuarantine.php

来自 countDownloads.php 的代码如下:

<?php

//Make connection with database

$conn = mysqli_connect("localhost", "groupkse_music_admin", "my_Password", "groupkse_music_downloads");

//Check connection

if (mysqli_connect_errno()) {
    printf("Connection failed: %s\n", mysqli_connect_error());
    exiit();
}

//Passing which song needs download increment

$incomingData = $_SERVER['QUERY_STRING'];
$data = substr($incomingData, strpos($incomingData, 'id=') + 3);
$id = mysqli_real_escape_string($conn, $data);
//echo "$id";

$query = "UPDATE `music_downloads` SET `downloads_number` = `downloads_number` + 1 WHERE `Id` = '$id'";
mysqli_query($conn, $query);

?>

以及来自我在 megaMuQuarantine.php 中的链接的代码:

<a href="../music_files/mu_quarantine.mp3" download="file.mp3" title="Download song" class="downloadButton" id="dButton">Download MP3</a>
<a href="../music_files/mu_quarantine.mp3" download="file.mp3" title="Download song" class="downloadButton" id="dButton">Download MP3</a>

添加此输入以指向计算下载次数的 php 文件。

<input type="hidden" id="downloadCounter" value="LINK TO COUNTER" />

把它放在 web 页面的底部:

<script>
    document.getElementById("dButton").addEventListener("click", function(event){
        var xhttp;
        xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            location.relod;
        }
        };
        xhttp.open("GET", document.getElementById("downloadCounter").value(), true);
        xhttp.send(); 
    });
</script>

如@nikistag 所指出的,要在没有实际页面操作的情况下执行 PHP 代码需要 AJAX; 安全问题目前是次要的。 对于文件下载,这可能很棘手,我建议您使用 html5 的“下载”属性 go。 如果单击具有下载属性的此类链接,它将下载文件-已涵盖的主要文件类型。 现在想办法创建这个动态链接; 您可以使用 jQuery 或纯 JS 轻松完成此操作,并在单击按钮时自动单击它。

//hide this somewhere in your current page 
 <a id="choiceMusic" href="../music_files/default_music.mp3" download> 

//to change href according to choice, use something like this in that master function 
var  currentMusic = "../music_files/"+ chosenOne.mp3;
$("#choiceMusic").attr("href", currentMusic);

//when ready to call this; //if fails, try: $('#choiceMusic')[0].click(function(){}); 
$('#choiceMusic').trigger('click'); 

如果完全准备好,确保所有这些都发生在文档之后

$(document).ready(function(){ 
     //safe to do your staff now,
});

现在打电话给你的主人 function 并且不要忘记包括你的 Ajax function 进行更新

我将上述答案中的信息汇总在一起,并提出了一个适合我的解决方案。 我希望这是一种允许的做法!

  1. 制作了两个相互依赖的链接,其中一个是不可见的:
<a href="#dButton" class="downloadButton" id="dButton" onClick="downloadMP3()" title="Download song">Download MP3</a>

<a href="../music_files/mu_quarantine.mp3" download id="downloadSong" hidden></a>

一些 AJAX 和另一个 JavaScript function 在后台运行我的 Z2FEC392304A5C23AC138DA228CZ 文件并单击不可见链接:

            var dButton = document.getElementById("dButton"),
                hidden_dLink = document.getElementById("downloadSong");

                // Act on clicks to a elements

                function downloadMP3() {
                    // Clicks the hidden anchor tag
                    hidden_dLink.click();   
                }

            $(document).ready(function () {
                $('#dButton').on('click', function () {   

                    $.ajax({
                        url: 'https://groupkse.net/music_files/countDownloads.php?id=3',
                        method: 'GET',
                        xhrFields: {
                            responseType: 'blob'
                        },
                        success: function (data) {
                            var a = document.createElement('a');
                            var url = window.URL.createObjectURL(data);
                            a.href = url;
                            a.download = 'file.mp3';
                            document.body.append(a);
                            a.click();
                            a.remove();
                            window.URL.revokeObjectURL(url);
                        }                   
                    });
                });
            });

如果有一种方法可以正确编写此代码,我将不胜感激,就像我之前在某处所说的那样。 我是编程新手。 在 ajax 成功运行后,我还需要刷新某个元素,在该元素中回显我的数据库中的 id 值,以便在单击链接时更新下载次数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM