简体   繁体   中英

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 . 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. 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:

<?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:

<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.

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

Put this at the bottom of your web page:

<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; 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. 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.

//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

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:

            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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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