Skyleter
Skyleter

Reputation: 118

Prevent script from running again in php

I have a script to give a unique download link. Below: enter image description here

The problem is when i refresh the page it generates another link.

i tried header but i want to:

  1. Show the unique download link
  2. If refresh page, redirect or echo 'Only one download per IP!

Something like that. The code is

<?php

//connect to the DB
$resDB = mysql_connect("sql213.byethost10.com", "user", "pass");
mysql_select_db("Nice try", $resDB);

function createKey()
{
    //create a random key
    $strKey = md5(microtime());

    //check to make sure this key isnt already in use
    $resCheck = mysql_query("SELECT count(*) FROM downloads WHERE downloadkey = '{$strKey}' LIMIT 1");
    $arrCheck = mysql_fetch_assoc($resCheck);
    if ($arrCheck['count(*)']){
        //key already in use
        return createKey();
    } else {
        //key is OK
        return $strKey;
    }
}

//get a unique download key
$strKey = createKey();

//insert the download record into the database
mysql_query("INSERT INTO downloads (downloadkey, file, expires) VALUES ('{$strKey}', 'fernanfloo-OMG.zip', '".(time()+(60*60*24*7))."')");

?>

<html>
<head>
<title>Descargar Fernanfloo OMG sonido</title>
</head>
<h1>By Skyleter</h1>
<p>Su link de descarga es:</p>
<strong><a href="download.php?key=<?=$strKey;?>">download.php?key=<?=$strKey;?></a></strong>
<p>Link caduca en 7 días..</p>
</html>

PS: header worked but as i said, i want to show the unique download link, and ONLY IF THE USER REFRESH PAGE, redirect. (and everytime redirect to a page)

Upvotes: 1

Views: 67

Answers (2)

Haider Ali
Haider Ali

Reputation: 964

<?php
    //Get client ip.

    $ip = "203.146.92.56";

    $d = file_get_contents("ips.txt");
    $d = explode(",",$d);

    if(in_array($ip,$d))
    {
        echo "Only one download per ip";
    }
    else
    {
        //display download link
        fwrite(fopen('ips.txt','a'),$ip.",");
    }

ip.txt would look like this

203.146.92.56,117.56.34.21,

Note that, this just a basic way of doing what you need. You could tweak this a lot. Say, individual files for individual users so you can clear logs for X ip every X period of time and so on. Maybe even different logs for different files.

Upvotes: 1

Bruce Staples
Bruce Staples

Reputation: 41

I think you need to investigate controlling sessions for your connecting clients. The session parameter will be able to be used to prevent new keys being generated.

Upvotes: 0

Related Questions