How download if variable is set, and not download if unset - php

I'm trying to make an iCalendar file via querying the database, so I don't have to make new iCalendar files with every event created.
<?php
header("Content-type: text/calendar");
$connection = mysqli_connect("localhost", "root", "");
$sql = "SELECT * FROM events WHERE eventID = '{$eventID}'";
$result = mysqli_query($connection, $sql);
$numrows = mysqli_num_rows($result);
// Render iCal file
?>
How to forbid file download if $_GET["eventID"] is not set?
In that case, I want instead of downloading, the visitor to get a blank page for an example.

Stick this at the top:
if (!isset($_GET["eventID"])) {
exit;
}
You should also do something after the SQL query, checking that it has actually returned a result. e.g.
if ($numrows == 0) {
exit;
}

if (!isset($_GET["eventID"])){
echo 'bad';
}else{
// your code here
}

The proper thing to do is the send a 404 Not Found HTTP status code if the URL/entity doesn't exist:
$result = mysqli_query($connection, $sql);
$event = $result->fetch_assoc();
if (!$event) {
header('HTTP/1.0 404 Not Found');
exit;
}
header("Content-type: text/calendar");
echo $event['title'];
..
Here I'm checking whether the event exists in the database. To handle a missing $_GET parameter you could send a 400 Bad Request separately.

Related

PHP Mysql view PDF file error

I was trying to view a PDF from my a MySQL database but it gets stuck on loading.
Here's my code:
<?php
header("Content-type: application/pdf");
$con = mysqli_connect("localhost","root","username","password");
//check if errors occur in connection to database
if (mysqli_connect_errno())
{
//return the error
echo mysqli_connect_error();
}
$filename = $row['name'];
$query = "SELECT content from images WHERE id = 7";
$result = mysqli_query($query,$con)or die(mysqli_error());
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
echo $row['content'];
?>
You can use dompdf or TCP pdf library for better and extended functionality.
or try to use ob_clean() method in starting of the line.
or remove first header("Content-type: application/pdf"); and check whether query is working or not.

Redirect Issue for referral system when fetching URL data

I have created a script for users to invite a friend using a email address, the email address and a randomly generated 10 character string 'inviteCode' is sent to a table called 'referrals'.
The invited person then receives an email with a URL link that contains their email and their unique inviteCode; http://website.com/register.php?email=email&inviteCode=1234567890
When the user clicks on the link the page register.php should then check the URL and if they data is valid in the 'referrals' table. If so then I have an include line to add the register form, if not then they are redirected. The point is nobody can access register.php unless they have been invited and sent a link.
At the moment the page keeps redirecting to index.php;
Register.php script:
<?php
include 'config.php';
if (isset($_GET['email'],$_GET['inviteCode'])) {
$mysqli = new Mysqli(/* your connection */);
$email = $mysqli->real_escape_string($_GET['email']);
$inviteCode = $mysqli->real_escape_string($_GET['inviteCode']);
$sql = "SELECT email,inviteCode FROM referrals WHERE email='".$email."' AND inviteCode='".$inviteCode."'";
$query = $mysqli->query($sql);
if ($query->num_rows > 0) { //check if values are correct and available in database
echo 'lol';
}
else
{
echo 'no';
exit;
}
}
else
{
echo 'problem'; //Page not accessible if neither email nor referral entered
}
?>
I replaced the first if statement with:
if(!isset($_GET['email']) || !isset($_GET['inviteCode'])) {
die(header('Location: index.php'));
} else
And I receive a blank page with no errors. I believe there may be something wrong with the email and invite code not being set.
Any help on this would be much appreciated (Y) thanks.
You should really be looking at handling the errors first. Try something like this:
if(!isset($_GET['email']) || !isset($_GET['inviteCode'])) {
die(header('Location: index.php'));
} else {
$mysqli = new Mysqli(/* your connection */);
$email = $mysqli->real_escape_string($_GET['email']);
$inviteCode = $mysqli->real_escape_string($_GET['inviteCode']);
$sql = "SELECT email,inviteCode FROM referrals WHERE email='$email' AND inviteCode='$inviteCode'";
$query = $mysqli->query($sql);
if ($query->num_rows > 0) { //check if values are correct and available in database
include'register-form.php';
} else {
die(header('Location: index.php'));
}
}
Breakdown
The if block checks to see if GET[email] or GET[inviteCode] are not set. if that is the case, kill the app with die() and redirect the user to index.php.
The second change is this line:
if ($query->num_rows > 0) {
That will check to ensure the rows returned are more than 0 (meaning there are actually rows returned.) Because you were just testing the presence of the $query->num_rows before.
Another Note:
Turn on error reporting, it will help you emensly during debugging:
ini_set('display_errors', 1);
error_reporting(E_ALL);
You could alternatively change your sql query to select the COUNT(id) and check if that is greater than 0, but that seems like overkill for what you're trying to do.
Do this to find out if anything is being returned by your query:
Start by making sure that the connection to your database is succeeding:
$mysqli = new Mysqli(/* your connection */);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$email = $mysqli->real_escape_string($_GET['email']);
Add that then let us know the results afterward, also provide specific error messages.
To debug your num_rows, replace this:
$query = $mysqli->query($sql);
if ($query->num_rows) //check if values are correct and available in database
{
include'register-form.php';
}
With this:
$query = $mysqli->query($sql);
$count = $query->num_rows;
print $count;
exit;
if ($query->num_rows) //check if values are correct and available in database
{
include'register-form.php';
}
If it shows 0, I have a suspicion it is because your sql statement needs to be concatenated.
"SELECT email,inviteCode FROM referrals WHERE email='".$email."' AND inviteCode='".$inviteCode."'";

How to COUNT the number of times a FILE from my database has been downloaded?

I am new to this and I am having problems trying to get my website to count the number of times a files has been downloaded. The website has download buttons linking to the files which are stored on my database, and I would like to be able to count the amount of downloads per file to display as a statistic, ideally once they click the link to download, the column in the files table should be incremented, but I cannot wrap my head around it. please help?
<?php
error_reporting(E_ALL ^ E_NOTICE);
session_start();
$userid = $_SESSION['userid'];
$username= $_SESSION['username'];
?>
<?php
// Make sure an ID was passed
if(isset($_GET['id'])) {
// Get the ID
$id = ($_GET['id']);
// Make sure the ID is in fact a valid ID
if($id <= 0) {
die('The ID is invalid!');
}
else {
// Connect to the database
$dbLink = new mysqli('dragon.kent.ac.uk', 'repo', '3tpyril', 'repo');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Fetch the file information
$query = "
SELECT `mime`, `name`, `size`, `data`
FROM `files`
WHERE `id` = {$id}";
$result = $dbLink->query($query);
if($result) {
// Make sure the result is valid
if($result->num_rows == 1) {
// Get the row
$row = mysqli_fetch_assoc($result);
// Print headers
header("Content-Type: ". $row['mime']);
header("Content-Length: ". $row['size']);
header("Content-Disposition: attachment; filename=". $row['name']);
// Print data
echo $row['data'];
}
else {
echo 'Error! No files exists with that ID.';
}
}
else {
echo "Error! Query failed: <pre>{$dbLink->error}</pre>";
}
#mysqli_close($dbLink);
}
}
else {
echo 'Error! No ID was passed.';
}
?>
The download link would point to a php file, such as download.php?id=123 -- this file would then take the ID and check the downloads database. If the ID exists, you run a query such as UPDATE files SET downloads = downloads + 1 WHERE id = 123.
Afterwards, you set the headers using header() to set content-type. Then use readfile().
See How to force file download with PHP on how to set headers and force a download.
Cheers!

Redirecting to another page, using variables from the first one

I have created the following scenario.
I have the index.php file which shows the mainpage. On this there are two fields - User Id and password enclosed in a form tag. The submit button calls the login.php file.
Login.php validates the user id, password etc
Once validation is successful, I want the login.php page to take me to MyDashboard.php page (passing the User Id and Password along).
I tried Header in PHP but does not work. I also tried to do a Javascript window.location.href and tried to call it on $(document).ready but nothing happens.
Please help.
--- Edit ----
here is the code after modification
<?php
include_once('./library/Common.php');
$_EmailId = trim($_POST['validemailid']);
$_Password = trim($_POST['password1']);
$_Rememberme = trim($_POST['rememberme']);
// Get the username from the Email Id by searching for #
$_UName= substr($_EmailId, 0, strpos($_EmailId, '#'));
$_Password = md5($_Password);
session_start();
$_SESSION['username'] = $_UName;
$query = "select username, firstname, password_hash,userstatus from users where username = ? and emailid = ?";
$dbconn = new mysqli('localhost', 'root', '','myDB');
if($dbconn->connect_errno)
{
print getHTML('ERROR', "Error in connecting to mysql".$dbconn->connect_error);
}
if(!($stmt=$dbconn->prepare($query)))
{
print getHTML('ERROR',"error in preparing sql statement".$dbconn->error);
}
if(!($stmt->bind_param('ss',$_UName,$_EmailId)))
{
print getHTML('ERROR',"error in binding params in sql statement".$stmt->error);
}
if(!$stmt->execute())
{
print getHTML('ERROR',"Execute failed: (" . $stmt->errno . ") " . $stmt->error);
}
$result=$stmt->get_result();
$row = $result->fetch_assoc();
$_dbpwd = $row['password_hash'];
$_userstatus = $row['userstatus'];
$errstatus = false;
if ($row['username'] != $_UName)
{
print getHTML('ERROR',"User does not exist with the given email id: ".$_EmailId);
$errstatus = true;
}
if(($row['password_hash'] != $_Password) && !$errstatus)
{
print getHTML('ERROR',"Password does not match");
$errstatus = true;
}
if(($row['userstatus'] != 'ACTIVE') && !$errstatus)
{
print getHTML('ERROR',"User is inactive. Please check your email for activation");
$errstatus = true;
}
if(!$errstatus)
{
$_SESSION['firstname'] = $row['firstname'];
$chksession = "SELECT sessionid FROM USERSESSIONS WHERE USERNAME = ? AND ENDDATE IS NULL";
if(!($sessionstmt=$dbconn->prepare($chksession)))
{
print "error in preparing sql statement".$dbconn->error;
exit();
}
$sessionstmt->bind_param('s',$_UName);
$sessionstmt->execute();
$sessionresult=$sessionstmt->get_result();
$sessionrow= $sessionresult->fetch_assoc();
$currdate = date('y-m-d H:i:s');
if($sessionrow['sessionid'] == 0)
{
$insertstmt = $dbconn->query("INSERT INTO USERSESSIONS(USERNAME,STARTDATE,ENDDATE) VALUES ('".$_UName."','".$currdate."',null)");
$insertstmt->close();
}
}
$sessionstmt->close();
$stmt->close();
$dbconn->close();
header("Location :MyDashboard.php");
exit;
?>
--- End of Edit -----
Amit
You should use session variables to store variables within a login session. Passing a password along to other pages is not recommended, nor necessary. Read up on Sessions, and take a look at already existing login scripts. Below is a very simple example, redirecting to the next page using the header() function.
<?php
// Validate user credentials and save to session
session_start();
$_SESSION['userId'] = $userId;
// Redirect to next page
header("Location: dashboard.php");
// Make sure that code below does not get executed when we redirect
exit;
?>
If user authenticated,
In PHP:
header('Location:MyDashboard.php');
Try include()
This function allows you to include code from other php scripts.
The header function is the correct way. As long as you don't have any output before calling the header function, it should work.
http://us3.php.net/manual/en/function.header.php
Post your code, and let's see what it is that isn't working!
Header should work in your condition.
Tou can use following code:
header("Location:filename");
exit();

PHP code included in HTML won't update

I currently have a PHP file which will search my MySQL database and see if a user is logged in. If they are logged in, it will echo "Welcome 'username'. Logout" and if they're not logged in it will echo "Login. Register."
If I view this PHP file directly, it will echo out the correct text, depending on whether or not I am logged in. However, if I put into my HTML file using include it will only echo out the logged out text, regardless of whether I'm logged in.
Is there some conflict between PHP and HTML which will stop it from printing out the correct text maybe? It seems strange that it will work opening the PHP file itself, but not when it's included in HTML.
HTML code:
<?php include "loginreg/check.php"; ?>
Would the fact it's in a subfolder make a difference? Haven't included the PHP code as that itself is working, but I have got it if you need to see it.
Cheers
PHP code:
// Gets IP address
$ip = visitorIP();
// Connect to database
mysql_connect(localhost, $username, $password);
#mysql_select_db($database) or die('Unable to select database');
$query = "SELECT * FROM loggedin WHERE userip='$ip'";
$result = mysql_num_rows(mysql_query($query));
if ($result == '0') {
mysql_close();
loggedOut();
return;
}
if (isset($_COOKIE['sid'])) {
$sessionid = $_COOKIE['sid'];
}
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
if ($row['sessionid'] == $sessionid) {
mysql_close();
loggedIn($row['id']);
} else {
mysql_close();
loggedOut();
}
}
function visitorIP() {
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$TheIp = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$TheIp = $_SERVER['REMOTE_ADDR'];
}
return trim($TheIp);
}
function loggedIn($id) {
global $username, $password, $database;
mysql_connect(localhost, $username, $password);
#mysql_select_db($database) or die('Unable to select database');
$query = "SELECT * FROM users WHERE id='$id'";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
$fname = $row['fname'];
$sname = $row['sname'];
}
echo "<div class=\"fltrt\">Welcome, " . $fname . ". Logout</div>";
}
function loggedOut() {
echo "<div class=\"fltrt\">Login Register</div>";
}
Without seeing the code of both scripts this is just a guess, but a likely problem would be that you are outputting html (anything...) before you include your loginreg/check.php script.
That would render any session_start() statements in your included file useless as the headers already have been sent. And not being able to get to the session would lead to the error that you describe.
Edit: For cookies the same principle applies, they need to be set before the headers are sent so before you output anything to the browser.
Your issue is that you are setting cookies while inside a subdirectory. Use the path parameter of setcookie to ensure you're setting the cookie in the root folder of your website:
// Sets the cookie for the root of the domain:
setcookie("username", "foo", time() + 60 * 60, "/");
Correct me if I'm wrong here, but are you trying to use a PHP include in an HTML file? If so, that will never work (unless you've got some custom server config that will parse PHP code in HTML files).
PHP code is for PHP files. HTML code can work in HTML and PHP files. You cannot do a PHP include, in an HTML file.

Categories