Viewing Image from database - php

I have a file in which a user can view its stored files. I want that only the logged in user and it can only be viewed by that member who has stored that file. It works fine when I view other files like .html, .txt etc. But when I view any image, it doesn't work.
This is my script :
require ('config.php');
$id = intval($_GET['id']);
$dn2 = mysql_query('select authorid from files where uploadid="'.$id.'"');
while($dnn2 = mysql_fetch_array($dn2))
{
if(isset($_SESSION['username']) and ($_SESSION['userid']==$dnn2['authorid'] or $_SESSION['username']==$admin)){
$query = "SELECT data, filetype FROM files where uploadid=$id"; //Find the file, pull the filecontents and the filetype
$result = MYSQL_QUERY($query); // run the query
if($row=mysql_fetch_row($result)) // pull the first row of the result into an array(there will only be one)
{
$data = $row[0]; // First bit is the data
$type = $row[1]; // second is the filename
Header( "Content-type: $type"); // Send the header of the approptiate file type, if it's' a image you want it to show as one :)
print $data; // Send the data.
}
else // the id was invalid
{
echo "invalid id";
}
}
}
How can I view the image?

Related

Cant delete files from folder using unlink function in php

Unable to delete file from folder otherwise code work perfectly.
same code i used for replacing or updating image where it works fine but here dosent able to delete data from folder by their id or name
if(isset($_POST['8maths_delete'])) //post method button name
{
$id = $_POST['delete_id']; //data fetch by id
$files_query = "DELETE FROM 8maths WHERE id='$id'"; //deleting data from sever
$files_query_run = mysqli_query($connection, $files_query); //query run
if($files_query_run) // query run
{
unlink("upload/".$row['files']); //unlink where upload folder where all the files held. but dosent able to delete file from folder
$_SESSION['success'] = "Your Data is Deleted"; //session for echo
header('Location: 8thmaths.php');
}
else
{
$_SESSION['status'] = "Your Data is not Deleted";
header('Location: 8thmaths.php'); //redirecting location
}
}
There are two issues I can see:
1 - You reference $row['files'] but I don't see $row defined anywhere in your code.
2 - Using the word 'files' I assume there could be multiple, if that's the case you need to loop over all the files and unlink them either with something like:
A foreach loop:
$result = mysqli_fetch_all($files_query_run, MYSQLI_ASSOC);
foreach($result as $row) {
unlink("upload/".$row['files']);
}
Or using a while loop.
while ($row = mysqli_fetch_assoc($files_query_run)){
unlink("upload/".$row['files']);
}
I hope this helps get you off to the right start.

HTML function to download JSON stored in MySQL database

I would like to be able to save a JSON file that is in a database to the user's PC. In summary, I'm storing setup files from a sim racing game, that use a JSON format, in a database, and I'd like the user to be able to upload/download these JSON files (to share with others, etc).
I've got the upload working, using PDO, so there is a column called setup that is a text data type. I'm using a form, with a $FILES() to fetch the uploaded json file, with some checks to ensure it's a valid setup json.
$setup = file_get_contents($_FILES['setupjson']['tmp_name']); //get json from file uploaded
$setupJSON = json_decode($setup); //decode into object
$car = $setupJSON->carName; //carName from object
if ($obj->searchCarName($car) > 0) // if search matches (car exists)
{
if($obj->insertSingleSetup($_POST["name"], $_POST["description"], $_POST["type"], $car, $_POST["track"], $setup) !== false)
{
header('Location: add.php?success');
exit();
}
else
{
header('Location: add.php?error=Error+adding+the+setup');
exit();
}
}
else
{
header('Location: add.php?error=Please+submit+a+valid+setup');
exit();
}
}
The issue i'm having is downloading the file again. I've been able to view the JSON directly
<?php
include('../db.php');
$setup_id = $_POST['setup'];
try {
$connectionString = sprintf("mysql:host=%s;dbname=%s;charset=utf8mb4",
DB::DB_HOST,
DB::DB_NAME);
$pdo = new PDO($connectionString, DB::DB_USER, DB::DB_PASSWORD);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = 'SELECT * FROM setups WHERE setup_id= :setupID';
$query = $pdo->prepare($sql);
$query->bindValue(':setupID', $setup_id);
$result = $query->execute();
$setup = $query->fetch(PDO::FETCH_ASSOC);
processSetup($setup);
} catch (PDOException $e) {
die("Could not connect to the database $dbname :" . $e->getMessage());
}
function processSetup($setupRow)
{
$setup = $setupRow['setup'];
$setupJSON = json_decode($setup);
echo '<pre>';
echo $setup;
echo '</pre>';
}
?>
but I can't work out how to download it. I've researched that it's related to headers, but everytime I try something, it never works. I just want the save file dialog to appear with the json, and preferably, the option to set the filename outputted to a chosen variable.
Just figured it out, on the processSetup function, I changed the code to this
function processSetup($setupRow)
{
$setup = $setupRow['setup'];
header('Content-type: application/json');
header('Content-disposition: attachment; filename=setup.json');
echo $setup;
}
If I add some code to give the JSON it's proper filename, it'll be perfect :D

PHP - getting image from database

I want to save user's image to a database.
p9_member (member_no ,member_name , .... , member_photo)
Now, I am using a BLOB to save the image for "member_photo" column
What I want to do now is that:
1. I have an application that need to connect the database and get the image from the database.
2. I have also a website doing the same things.
I am implementing the application now. As I need to send the image with some information of the member like name or id. So I create an object to save all the things. This is my PHP code:
<?PHP
Class Friends{
var $no;
var $name;
var $photo;
var $status;
var $admin;
public function __construct($no,$name,$photo,$admin,$status){
$this->name = $name;
$this->photo = $photo;
$this->no = $no;
$this->status=$status;
$this->admin=$admin;
}
};
include ("../../server_config.php");
$friends = array();
$SQL = "SELECT p9_member.member_no,p9_member.photo AS PHOTO,p9_member.name,p9_member.photo FROM p9_member, p9_friends WHERE p9_member.member_no = p9_friends.member_no2 AND p9_friends.member_no1 =".$_POST['memberno'];
$result = mysqli_query($con,$SQL);
if (mysqli_num_rows($result)>0) {
while($row = mysqli_fetch_array($result)){
$friends[] = new Friends($row['member_no'],$row['name'],$row['photo'],null,null);
}
}else
$friends[] = 0;
echo json_encode($friends);
?>
The SQL CODE:
SELECT p9_member.member_no,p9_member.photo AS PHOTO
FROM p9_member, p9_friends
WHERE p9_member.member_no = p9_friends.member_no2
AND p9_friends.member_no1 =".$_POST['memberno']
I cannot get the data back from the application after json decode.
What is the best solution for me?
TRY the below code it will work..
$image_qry=mysql_query("SELECT * FROM tabel_name WHERE your condition");
$image=mysql_fetch_assoc($image_qry);
$get_image=$image['image_column']; //BLOB DATA TYPE
header("Content-type: image/jpeg"); // need to add the header content type in your code
echo $get_image;

including file with if else condition

i am including payment.php but only in case of if image type is equal to "map" else rest of the html content without including payment.php.
for Example
<?php
include('aaa.php');
$url=$_GET['url'];
$sql = "SELECT * FROM maps WHERE url='$url'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$name=$row['name'];$metaTitle=$row['metaTitle'];$metaDesc=$row['metaDesc'];$metaKeyword=$row['metaKeyword'];$imageType=$row['imageType'];
?>
some content appears. i need to write php code for below line
if imageType(name of field in table)= map
then include external file "payment.php"
else
html content without indluding payment.php file.
if($imageType == "map") {
include('payment.php');
}
//html content here

download button - save file to disk instead of opening

I have a download button and when i click on it, instead of saving to disk it opens it in the browser. I tried a bunch of attempts to make it open in the browser but it doesnt seem to do anything
<?php
// make a connection to the database
require_once("connection/connection.php");
//retrieve the ID from the url to fetch the specific details
if ($_GET['id'] != ""){
$item_id = $_GET['id'];
$bad_id = FALSE;
}
else{
$item_id = "";
$bad_id = TRUE;
}
//select the specific item from the database
// run if statement to ensure valid id was passed
if (is_numeric ($_GET['id'])){
$query = "SELECT name FROM repository WHERE item_id = '$item_id'";
$result = mysql_query($query) or die(mysql_error());
// assign the values to an array
$row = mysql_fetch_assoc($result);
//assign the values from the array to variables
$name = $row['name'];
}
// define path to the xml file
$file = "xml/".$hud_name . "_cfg.xml";
// check to make sure the file exists
if(!file_exists($file)){
die('Error: File not found.');
} else{
// Set headers
header("Content-Type: application/xml");
header("Content-Disposition:attachment; filename=".basename($file)."");
readfile($file);
}
?>
That is download.php and it obviously finds the file because it doesnt give the error about it not existing. It also echos back the correct file path
Then on another page i have:
<img src="images/download.png" alt=""/>
Any ideas whats wrong?
Well the solution turned out to be simple in the end but i didnt see any documentation saying the header must be the very first line. If i placed:
header("Content-Type: application/xml");
as the first line and then the coding below it and the other header info at the end it works. Im not sure if that's the solution or a workaround but it fixed it for me

Categories