I have a script to give a unique download link. Below:
The problem is when i refresh the page it generates another link.
i tried header but i want to:
Show the unique download link
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>download.php?key=<?=$strKey;?></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)
<?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.
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.
Related
On my website, I allow users to view a users information by simply clicking their name. Once they click the persons name, they can schedule the person to come to an event. When the user clicks "schedule me" I take the them full name from the "user_id" and send it as a "$_SESSION['speaker']" to the next file that pretty much checks if the user came from the last file and takes the name and uses it as the input value for the calendar. The problem I am having is that when the user didn't "click schedule" from the other file and goes to the calendar website alone, the name from the previous person they clicked stays there and I want it to be blank in case they want to put a different name. So pretty much i would access the calendar website just by typing the URL and the name would still be in the session. I want to clear the session without logging the user out so they don't see the name of the previous person they clicked. Here is some of my code
First file
$_GET['speaker'] = $_SESSION['speaker_id'];
$speaker_id = $_GET['speaker'];
$stmtSpeaker = $handler->prepare("SELECT * FROM formdata WHERE user_id= :speaker_id");
$stmtSpeaker->bindParam(':speaker_id', $speaker_id, PDO::PARAM_INT);
$stmtSpeaker->execute();
$formData = $stmtSpeaker->fetch();
if(isset($_POST['schedule_me'])){
$_SESSION['admin'] = $adminBoolean;
$_SESSION['speaker'] = $formData['fullname'];
$_SESSION['speaker_came'] = true;
header("Location: admincalendar.php");
exit;
}
Second file
$adminBoolean = $resultChecker['admin'];
if($_SESSION['speaker_came'] = true){
$speaker = $_SESSION['speaker'];
}else{
$speaker = "";
}
Unset will destroy a particular session variable whereas session_destroy() will destroy all the session data for that user.
It really depends on your application as to which one you should use. Just keep the above in mind.
unset($_SESSION['name']); // will delete just the name data
session_destroy(); // will delete ALL data associated with that user.
You can unset session variable
$adminBoolean = $resultChecker['admin'];
if($_SESSION['speaker_came'] = true){
$speaker = $_SESSION['speaker'];
}else{
unset($_SESSION['speaker']);
unset($_SESSION['speaker_came']);
$speaker = '';
}
You need to first get the tempkey of the element and then unset it. Try this:
if(($tempkey = array_search($speaker_id, $_SESSION['speaker'])) !== FALSE)
unset($_SESSION['speaker'][$tempkey]);
I have a problem and I don't know if anyone has a solution...
I have an online.php script that gets user ip and data and write it on mysql:
$browser = $_SERVER['HTTP_USER_AGENT'];
$root = $_SERVER['DOCUMENT_ROOT'];
include_once ("$root/config.php");
$ip = $_SERVER['REMOTE_ADDR'];
...
$sb4154 = $on124->num_rows;
if ($sb4154 == 0) {
$url=#$_SERVER['HTTP_REFERER'];
$ihghg = $mysqli_link->prepare("INSERT INTO online (ip, hora, browser) VALUES (?,now(),?)");
$ihghg->bind_param('ss', $ip, $browser);
$ihghg->execute();
$ihghg->close();
}
else {
$ihghg = $mysqli_link->prepare("UPDATE online SET `hora` = now() WHERE `ip` = ? LIMIT 1");
$ihghg->bind_param('s', $ip);
$ihghg->execute();
$ihghg->close();
}
it is basically that. (I use ... to sum up).
My php, when you click in a link it opens the image:
<a href="image.jpg">
So the user needs to click back in the browser to see more pictures. The problem is here, when user click back, this include online.php script not work, the UPDATE time not set the hour.
Why it is not working when user click back in browser?
I have am creating a Website that showes Visitors Info. Users are able to visit the page and use Textarea to pick a name for their URL, and the name will be saved as a table in mysql database..
I am using the $name variable in my first php file which is a replacement for the text "visitor_tracking". But today I noticed that there is also another php file and more sql codes, and once again I can see that this file also has the "visitor_tracking" text used in the sql code.
But I think I failed big time, because I simply dont know how to replace the "visitor_tracking" text with my the variable name called $name.
<?php
//define our "maximum idle period" to be 30 minutes
$mins = 30;
//set the time limit before a session expires
ini_set ("session.gc_maxlifetime", $mins * 60);
session_start();
$ip_address = $_SERVER["REMOTE_ADDR"];
$page_name = $_SERVER["SCRIPT_NAME"];
$query_string = $_SERVER["QUERY_STRING"];
$current_page = $page_name."?".$query_string;
//connect to the database using your database settings
include("db_connect.php");
if(isset($_SESSION["tracking"])){
//update the visitor log in the database, based on the current visitor
//id held in $_SESSION["visitor_id"]
$visitor_id = isset($_SESSION["visitor_id"])?$_SESSION["visitor_id"]:0;
if($_SESSION["current_page"] != $current_page)
{
$sql = "INSERT INTO visitor_tracking
(ip_address, page_name, query_string, visitor_id)
VALUES ('$ip_address', '$page_name', '$query_string', '$visitor_id')";
if(!mysql_query($sql)){
echo "Failed to update visitor log";
}
$_SESSION["current_page"] = $current_page;
}
} else {
//set a session variable so we know that this visitor is being tracked
//insert a new row into the database for this person
$sql = "INSERT INTO visitor_tracking
(ip_address, page_name, query_string)
VALUES ('$ip_address', '$page_name', '$query_string')";
if(!mysql_query($sql)){
echo "Failed to add new visitor into tracking log";
$_SESSION["tracking"] = false;
} else {
//find the next available visitor_id for the database
//to assign to this person
$_SESSION["tracking"] = true;
$entry_id = mysql_insert_id();
$lowest_sql = mysql_query("SELECT MAX(visitor_id) as next FROM visitor_tracking");
$lowest_row = mysql_fetch_array($lowest_sql);
$lowest = $lowest_row["next"];
if(!isset($lowest))
$lowest = 1;
else
$lowest++;
//update the visitor entry with the new visitor id
//Note, that we do it in this way to prevent a "race condition"
mysql_query("UPDATE visitor_tracking SET visitor_id = '$lowest' WHERE entry_id = '$entry_id'");
//place the current visitor_id into the session so we can use it on
//subsequent visits to track this person
$_SESSION["visitor_id"] = $lowest;
//save the current page to session so we don't track if someone just refreshes the page
$_SESSION["current_page"] = $current_page;
}
}
Here is a very short part of the script:
I really hope I can get some help to replace the "visitor_tracking" text with the Variable $name...I tried to replace the text with '$name' and used also different qoutes, but didnt work for me...
And this is the call that I used in my 2nd php file that reads from my first php file:
include 'myfile1.php';
echo $var;
But dont know if thats correct too. I cant wait to hear what I am doing wrong.
Thank you very much in advance
PS Many thanks to Prix for helping me with the first php file!
first you need to start session in both pages. it should be the first thing you do in page before writing anything to page output buffer.
In first page you need to assign the value to a session variable. if you don't start session with session_start you don't have a session and value in $_SESSION will not be available.
<?php
session_start(); // first thing in page
?>
<form action="" method="post" >
...
<td><input type="text" name="gname" id="text" value=""></td>
...
</form>
<?PHP
if (isset($_POST['submit'])) {
$name = $_POST['gname'];
//...
//Connect to database and create table
//...
$_SESSION['gname'] = $name;
...
// REMOVE THIS Duplicate -> mysql_query($sql,$conn);
}
?>
in second page again you need to start session first. Before reading a $_SESSION variable you need to check if it has a value (avoid errors or warnings). next read the value and do whatever you want to do with it.
<?php
session_start(); // first thing in page
...
if(isset($_SESSION['gname'])){
// Read the variable from session
$SomeVar = $_SESSION['gname'];
// Do whatever you want with this value
}
?>
By the way,
In your second page, I couldn't find the variable $name.
The way you are creating your table has serious security issue and least of your problems will be a bad table name which cannot be created. read about SQL injection if you are interested to know why.
in your first page you are running $SQL command twice and it will try to create table again which will fail.
Your if statement is finishing before creating table. What if the form wasn't submitted or it $_POST['gname'] was emptY?
there are so many errors in your second page too.
Here is the first question and I need your help.
I transfer form data from first page using header location method in php to second page.
On the second page I accept the data using get.
Now here the url of 2nd page, after the data is sent (i.e. form is submitted)
http://mydomain.com/site1/form1_conf.php?id=123
When user is on second page, the data on second page is being displayed according the id number from the mysql database.
Now the problem is that when the user is on second page and he changes the number (for ex. 123 to say 78) the data of id=78, from the database is displayed, which is no good.
How can I stop that?
Please Note: I can't use post, nor can I use sessions.
EDITE:
php code on first page, to transfer to second page:
// after all validations are okay
$insert = //insert into database
$result = mysql_query($insert);
if($result)
{
echo("<br>Input data is succeed");
$lastInsertedId = mysql_insert_id();
header('Location:form1_conf.php?id='.$lastInsertedId); //THIS IS THE IMPORTANT LINE
}
else
{
$message = "The data cannot be inserted.";
$message .= "<br />" . mysql_error();
}
Your problem is not with the URLs: to a power user changing cookies or POST-variables is as trivial as editing GET-variables for a regular user. You'll need some way to 'sign' the requests as being valid.
Easiest to do this is with a "pre-shared key", which you use with one-way hashes to validate requests.
Redirector:
$newURL = '/newpage?id='.$id.'&hash='.sha1('mypresharedkey'.$id);
header('HTTP/1.1 303 See other');
header('Location: '.$newURL);
die;
The other page:
$idToShow = $_GET['id'];
$hash = sha1('mypresharedkey'.$id);
if($hash != $_GET['hash'])
die("Tssss, don't play with the address bar!");
else
RenderThePage();
This ensures end users can only access pages they've been allowed to by the submit.
For your specific code:
...all prior code
$lastInsertedId = mysql_insert_id();
$timestamp = time();
header('Location:form1_conf.php?'.http_build_query([
'id' => $lastInsertedId,
'time' => $timestamp,
'hash' => sha1('some-generated-key'.$timestamp.$lastInsertedId)
]);
In the other page, including a timebomb if you want (otherwise just comment it out):
$id = $_GET['id'];
$time = $_GET['time'];
if($_GET['hash'] != sha1('some-generated-key'.$time.$id))
die('URL was tampered with');
if(time() - $time > 300)
die('URL was only valid for 5 minutes');
You need to track the user and the id that they have in your database to make sure that they haven't changed the number. So when you get the information via the GET you make sure that it is legit.
Users can change the id or even attempt to go directly to that page via the url. So you need some sort of server-side check to verify that it is ok.
You could complicate this "cheating" a bit, if you didn't pass the ID number directly, but somehow encrypted it.
Let's say, you define a salt:
define(SALT, 'long weird salt with special characters etc.');
Here comes the first part you want:
$lastInsertedId = mysql_insert_id();
$querytag = base64_encode($lastInsertedId); // just to make it less readable
$checksum = md5($querytag . SALT); // and make a hash
header('Location:form1_conf.php?id=' . $querytag . '&checksum=' . $checksum);
At the beginning of form1_conf.php, you put this:
$encodedId = $_GET['id'];
$oldChecksum = $_GET['checksum'];
$newChecksum = md5($encodedId . SALT);
$id = base64_decode($encodedId);
if($newChecksum != $oldChecksum) {
die('You Are Cheating!');
}
... do something with the $id ...
The point is that since you add SALT to the hash, some user can't simply use md5 on a changed ID, because he's missing the SALT you used.
It'd be even better if the salt wasn't the same every time.
You should never trust the url because there is always a way to manipulate the data.
So you should do validation after retreiving the data. If the result does not fit you: for example the loggedin user with the ID = 1 requests the settings page from the userid = 3 you do not show the result.
<?php
$userID = $_GET['id'];
if($userID != $expectedResult)
{
//show errormessage, redirect or show the page with the users data
}
?>
Ok so im at a loss. I can not figure out how to redirect someone once the headers are sent. The purpose of this script is if the date is valid they get redirected to the edit page. If the date is not valid it stops them and tells them why they are not able to edit.
<?php
$id = $_GET['id'];
// Define MySQL Information.
$mysqlhost="************************"; // Host name of MySQL server.
$mysqlusername="**************"; // Username of MySQL database.
$mysqlpassword="**************"; // Password of the above MySQL username.
$mysqldatabase="**************"; // Name of database where the table resides.
// Connect to MySQL.
mysql_connect("$mysqlhost", "$mysqlusername", "$mysqlpassword")or die("Could not connect to MySQL.");
mysql_select_db("$mysqldatabase")or die("Could not connect to selected MySQL database.");
$infosql = "SELECT * FROM premiersounds_users WHERE customer_id = $id";
$inforesult = mysql_query($infosql) or die(mysql_error());
$info = mysql_fetch_array($inforesult);
$l_date=$info['lockout_date'];
//Get current date from server
$format="%m/%d/%y";
$c_date=strftime($format);
//set sessions
$_SESSION['current_date'] = $c_date;
$_SESSION['lockout_date'] = $l_date;
//Check is Current date = lockout date
if ($c_date >= $l_date)
{ header("location:/planner_scripts/documnet_editors/edit_weddingplanner.php?id=$id"); } else {echo 'Whoops! Were sorry your account has been locked to edits because your event is less than 48 hours from now or your event has passed. To make changes to your event please contact your DJ.'; echo'<br/>'; echo ' Todays Date: ';echo $c_date; echo ','; echo ' Last Date for edits: '; echo $l_date;}
?>
I would make sure this is the first code run so that no headers have been sent yet, but if you cannot put it there, you have 2 choices:
Use javascript: window.location.url = ...
Put a meta refresh tag in the <head> section of your page: <meta http-equiv="refresh" content="0;url=...">
2 choices assuming you cannot change the code before your section is run...
You could use output buffering to stop anything being rendered. Alternatively just make sure the redirect is done in logic before echoing anything to the user.
Correct syntax is Location: http://....
Note:
Capital L
A space between : and the URL
An absolute URL (relative URLs aren't RFC compliant though might work in most browsers)