简体   繁体   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 . 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 My issue is I want to run this php script without redirecting my browser to this location, when a link is clicked to download that mp3.我的问题是,当单击链接下载该 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 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

Code from countDownloads.php is below:来自 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);

?>

And code from my link in the megaMuQuarantine.php:以及来自我在 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>

Add this input to point to the php file that counts downloads.添加此输入以指向计算下载次数的 php 文件。

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

Put this at the bottom of your web page:把它放在 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>

To execute a PHP code without actual page action requires AJAX as pointed out by @nikistag;如@nikistag 所指出的,要在没有实际页面操作的情况下执行 PHP 代码需要 AJAX; security issues being secondary as per now.安全问题目前是次要的。 For file downloads, this can be tricky and I would advice that you go with the 'download' attribute for html5.对于文件下载,这可能很棘手,我建议您使用 html5 的“下载”属性 go。 If such links with download attribute is clicked, it will download the file - major file types already covered.如果单击具有下载属性的此类链接,它将下载文件-已涵盖的主要文件类型。 Now figure out a way to create this dynamic link;现在想办法创建这个动态链接; you can easily do this with jQuery or pure JS and perform auto-click on it when your button is clicked.您可以使用 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'); 

Ensure that all these happen after the document if fully ready如果完全准备好,确保所有这些都发生在文档之后

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

Now call your master function and don't forget to include your Ajax function for updates现在打电话给你的主人 function 并且不要忘记包括你的 Ajax function 进行更新

I put together the information from the above answers and came up with a solution that works for me.我将上述答案中的信息汇总在一起,并提出了一个适合我的解决方案。 I hope it's a practice that is allowed!我希望这是一种允许的做法!

  1. Made two interdependent links with one of them invisible:制作了两个相互依赖的链接,其中一个是不可见的:
<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>

Some AJAX and another JavaScript function to run my PHP file in the background and auto click the invisible link:一些 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);
                        }                   
                    });
                });
            });

If there is a way in which this code can be properly written, I would appreciate the guidance, Like I have earlier said somewhere.如果有一种方法可以正确编写此代码,我将不胜感激,就像我之前在某处所说的那样。 am new to programming.我是编程新手。 I further need to refresh a certain element where am echoing the id value from my database after the ajax has run successfully so that the number of downloads is updated on link click.在 ajax 成功运行后,我还需要刷新某个元素,在该元素中回显我的数据库中的 id 值,以便在单击链接时更新下载次数。

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

相关问题 当用户单击链接时如何运行 PHP 代码? - How do I run PHP code when a user clicks on a link? 只有一个简单的html和js文件,我怎么能强制链接到MP3下载而不是只是播放? - with just a plain html and js file, how can i force a link to an mp3 to download instead of just play? 当用户单击href链接时,如何使用Javascript和jQuery调用PHP页面? - How to call PHP page with Javascript & jQuery when user clicks on a href link? 如何将变量发布到php并在同一页面上运行该php? - How can I post a variable to php and run that php on the same page? 重定向到带有请求参数的php页面并对其进行处理后,如何在没有参数的情况下返回同一页面? - After redirecting to a php page with request parameters and processing them, how to I return to the same page without the parameters? 如何链接来自 <ul> 播放清单相同 <audio> 标签? - How can I link different MP3 files from an <ul> playlist to the same <audio> tag? 如何在没有cronjob的情况下运行php页面脚本 - How to run php page script without cronjob 在链接点击时运行PHP脚本而不刷新页面 - Run PHP script on link click without page refresh 用户单击链接时如何强制“另存为”选项 - How can I force a “save as” option when the user clicks a link 如何在用户单击时在新选项卡中打开链接 - How can I open a link in a new tab when the user clicks it
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM