file download using mysql and PHP - php

I am creating PHP page that allows users to download files when they click in this button:
<td><a href='download.php?id={$row['file_name']}'>Download</a></td>
then the page redirect to download.php, code:
<?php
// Make sure an ID was passed
if(isset($_GET['file_name'])) {
// Get the ID$id
$file_name= ($_GET['file_name']);
// Make sure the ID is in fact a valid ID
if($file_name == NULL) {
die('The name is invalid!');
}
else {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', "", 'db_name');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ".mysqli_connect_error());
}
// Fetch the file information
$query = "
SELECT `type`, `file_name`, `size`, `data`
FROM `pdfs`
WHERE `file_name` = {$file_name}";
$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);
header("Content-Type: ".$row['type']);
header("Content-Length: ".$row['size']);
header("Content-Disposition: attachment");
// disopsition = attachment to force download request
// Print data
echo $row['data'];
}
else {
echo 'Error! No file exists with that ID.';
}
// Free the mysqli resources
#mysqli_free_result($result);
}
else {
// if there is an error excuting the query
echo "Error! Query failed: <pre>{$dbLink->error}</pre>";
}
// close database connection
#mysqli_close($dbLink);
}
}
else {
// if no ID passed
echo 'Error! No ID was passed.';
}
?>
however, wehn i click in download i always get the massage of the last else statement "error no id was passed", but i can't find the problem, is the problem that i made the primary key of the file is the name??

If your link looks like this:
<a href='download.php?id={$row['file_name']}'>
Then the GET variable will be 'id' as in $_GET['id'] and not $_GET['file_name']

$_GET['file_name'] should be $_GET['id']
since <a href='download.php?id={$row['file_name']}'> you sending "id" not "file_name"

Typo
<td><a href='download.php?id=<?php echo $row['file_name']; ?>'>Download</a></td>

<a href='download.php?id={$row['file_name']}'>
u should use <a href="download.php?id=<?= $row['file_name'];?>">
then use $_GET['id'] since id is the variable u pass in url not $_GET['file_name']

Related

How do I change state value on MySQL with an a href?

I can't change the state of a value with a href.
I have tried in all ways. Here is my code
Giallo
giallo.php=
<?php
// Create connection
$conn = new mysqli('localhost','root','','agenda');
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$id = $_GET['id'];
$qry = mysqli_query($db,"select * from note where id='$id'"); // select query
// when click on Update button
if(isset($_POST['update'])) {
$colore=1;
$edit = mysqli_query($db,"update note set colore='$colore' where id='$id'");
if($edit) {
mysqli_close($db); // Close connection
header("location:udienze.php"); // redirects to all records page
exit;
} else {
echo mysqli_error();
}
}
if (mysqli_query($conn, $sql)) {
echo "<script>
alert('Nota inserita correttamente');
window.location.href='add-udienze.php';
</script>";
} else {
echo "<script>
alert('Errore');
window.location.href='add-udienze.php';
</script>";
}
mysqli_close($conn);
?>
What is wrong with my code? There are probably cleaner ways to do it. I have tried all ways that I know.
I think the problem is that you are calling the giallo.php script with multiple kind of params (POST and GET).
So when you click on the link, the "href" attribute redirects to giallo.php, but nothing happen because it miss the $_POST['update'] action.
Probably the solution fit your case can be edit the href attribute, adding a GET parameter for "update", like:
Giallo
And then edit the giallo.php file and consider the new $_GET["update"] and not the POST one.

Error query failed , check manual line 3

My upload.php and view.php are working fine but I am not able to create a download links to download files. db name = dbtuts.
and the link for download option is:
<td><a href='download.php?id=<?php echo $row['file_name']; ?>'>Download</a></td>
Here is the code for download.php
<?php
// Make sure an ID was passed
if(isset($_GET['id'])) {
// Get the ID$id
$file_name= ($_GET['id']);
// Make sure the ID is in fact a valid ID
if($file_name == NULL) {
die('The name is invalid!');
}
else {`enter code here`
// Connect to the database
$dbLink = new mysqli('localhost', 'root', "", 'dbtuts');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ".mysqli_connect_error());
}
// Fetch the file information
$query = "
SELECT file, type, size
FROM tbl_uploads
WHERE `file` = {$file_name}";
$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);
header("Content-Type: ".$row['type']);
header("Content-Length: ".$row['size']);
header("Content-Disposition: attachment");
// disopsition = attachment to force download request
// Print data
echo $row['data'];
}
else {
echo 'Error! No file exists with that ID.';
}
// Free the mysqli resources
#mysqli_free_result($result);
}
else {
// if there is an error excuting the query
echo "Error! Query failed: <pre>{$dbLink->error}</pre>";
}
// close database connection
#mysqli_close($dbLink);
}
}
else {
// if no ID passed
echo 'Error! No ID was passed.';
}
?>

Create zip archive out of file from MySQL using PHP

I am trying to put a XML file from MySQL database to a zip archive before downloading. I am able to create zip file but Windows is giving error while opening it.
error msg: window cannot open the foler.
filename.zip is invalid
Here is my code:
<?php
if(isset($_GET['id']))
{
$id = intval($_GET['id']);
if($id <= 0) {
die('The id is invalid!');
}
else
{
// Connect to the database
$dbLink = new mysqli('localhost', 'root', 'root', 'db');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
$zip = new ZipArchive();
$filename = "export_".date('Y.m.d H.i').".zip";
if ($zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== true)
{
echo "Cannot Open for writing";
}
$zip->addEmptyDir('Section');
$query = "SELECT name,data FROM file_section WHERE id ='$id'";
$result = $dbLink->query($query);
if($result->num_rows == 1)
{
// Get the row
$row = mysqli_fetch_array($result);
}
while($row = mysql_fetch_array($result))
{
$zip->addFile($row['data'], "{$row['name']}.xml");
}
$zip->close();
header("Content-disposition: attachment; filename='.$filename'");
header('Content-type: application/zip');
readfile($fileName);
}
// Free the mysqli resources
mysqli_free_result($result);
}
else {
echo "Error! Query failed: <pre>{$dbLink->error}</pre>";
}
mysqli_close($dbLink);
?>
P.S.: I have limited PHP knowledge.
Test this : create a temp file before addFile your zip object
see http://php.net/manual/en/ziparchive.addfile.php
addFile method wait first parameter a filename (the path to the file to add)
Here is the working solution that I got later. Its valid for one single file id input.
<?php
// Make sure an id was passed
if (isset($_GET['ids'])) {
// Get the id into string (in case of an array)
$id_pass = implode(",",$_GET['ids']);
// Make sure the name is in fact a valid
if ($id_pass <= 0) {
die ('No ID Selected!');
} else
{
// Connect to the database
$dbLink = new mysqli('localhost', 'root', 'password', 'DB Name');
if (mysqli_connect_errno()) {
die("MySQL connection failed: " . mysqli_connect_error());
}
// Fetch the file information
$query = "select id, name, data from datatable where id = {$id_pass};";
$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);
//zip function
$zip = new ZipArchive();
$filename = "export_" . date('Y.m.d H.i.s') . ".zip";
if ($zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== true) {
echo "Cannot Open for writing";
}
$ext = $row['name'] . ".xml"; // taking file name from DB and adding extension separately
$zip->addFromString($ext, $row['data']); //adding blob data from DB
$zip->close();
header("Content-disposition: inline; filename='.$filename'");
header('Content-type: application/zip');
readfile($filename);
unlink($filename);
}
}
// Free the mysqli resources
mysqli_free_result($result);
mysqli_close($dbLink);
}
}

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!

Upload files from IPhone/IPad to mysql DB?

I've been searching a lot about managing data on IOS and finally i build an app that downloads PDF archives,when the user download a PDF the archive is displayed on a UITableView and the user can see the PDF.Now i need do to the most important thing to my project,upload those archives to my MYSQL DB!I've found an very busy tutorial on a website,but the app just upload images,so if anyone know,how can i upload PDF archives!Any tutorial or idea will be helpful!
Thanks in advanced!
PHP SCRIPT:
<?php
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', 'root', 'fileUP');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
$name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
$mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
$data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name']));
$size = intval($_FILES['uploaded_file']['size']);
// Create the SQL query
$query = "
INSERT INTO `file` (
`name`, `mime`, `size`, `data`, `created`
)
VALUES (
'{$name}', '{$mime}', {$size}, '{$data}', NOW()
)";
// Execute the query
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}
// Echo a link back to the main page
echo '<p>Click here to go back</p>';
?>
Try using the following library to upload your PDF documents: http://allseeing-i.com/ASIHTTPRequest/How-to-use

Categories