Images not displaying from database and file - php

i Have set up a site that lets user upload images then those images get displayed back on the home screen. but i hit a wall just now so i got past to letting the user upload an image then that images gets saved to a folder and a database but how can i do it so the image gets displayed on the home screen.
<?php
// Connect to database
$errmsg = "";
if (! #mysql_connect("localhost","alfred1000351","*******")) {
$errmsg = "Cannot connect to database";
}
#mysql_select_db("drp_2cgih5o233");
$q = <<<CREATE
create table pix (
pid int primary key not null auto_increment,
title text,
imgdata longblob)
CREATE;
#mysql_query($q);
// Insert any new image into database
if ($_REQUEST[completed] == 1) {
// Need to add - check for large upload. Otherwise the code
// will just duplicate old file ;-)
// ALSO - note that latest.img must be public write and in a
// live appliaction should be in another (safe!) directory.
move_uploaded_file($_FILES['imagefile']['tmp_name'],"latest.img");
$instr = fopen("latest.img","rb");
$image = addslashes(fread($instr,filesize("latest.img")));
if (strlen($instr) < 149000) {
mysql_query ("insert into pix (title, imgdata) values (\"".
$_REQUEST[whatsit].
"\", \"".
$image.
"\")");
} else {
$errmsg = "Too large!";
}
}
// Find out about latest image
$gotten = #mysql_query("select * from pix order by pid desc limit 1");
if ($row = #mysql_fetch_assoc($gotten)) {
$title = htmlspecialchars($row[title]);
$bytes = $row[imgdata];
} else {
$errmsg = "There is no image in the database yet";
$title = "no database image available";
// Put up a picture of our training centre
$instr = fopen("../wellimg/ctco.jpg","rb");
$bytes = fread($instr,filesize("../wellimg/ctco.jpg"));
}
// If this is the image request, send out the image
if ($_REQUEST[gim] == 1) {
header("Content-type: image/jpeg");
print $bytes;
exit ();
}
?>
<html><head>
<title>Upload an image to a database</title>
<body bgcolor=white><h2>Here's the latest picture</h2>
<font color=red><?= $errmsg ?></font>
<center><img src=?gim=1 width=144><br>
<b><?= $title ?></center>
<hr>
<h2>Please upload a new picture and title</h2>
<form enctype=multipart/form-data method=post>
<input type=hidden name=MAX_FILE_SIZE value=150000>
<input type=hidden name=completed value=1>
Please choose an image to upload: <input type=file name=imagefile><br>
Please enter the title of that picture: <input name=whatsit><br>
then: <input type=submit></form><br>
<hr>
</body>
</html>

Here is my toughts:
Do not suppress warnings what you get from DB. They are real, and needed. Remove all #-characters from the front of DB-calls. If you get any notices, warnings, errors do not suppress them, correct them.
If you are making new code, consider using PDO as DB API, not the old, deprecating PHP MySQL API. It's as easy as MySQL API to use.
You only want try to create table only once, remove it from code which is executed many times.
You should check if $_REQUEST parameters exists, and not compare them if they do not. Also you need to put the parameter names in quotes, otherwise PHP thinks you are using constants, which you are not. So line if ($_REQUEST[completed] == 1) { must be fixed to if(isset($_REQUEST['completed']) && $_REQUEST['completed'] == 1) {. Same appies to whatisit and gim -params.
The code if (strlen($instr) < 149000) { does not work as intented, you cannot get length of resource. You are probably looking for this functionality: if (strlen($_FILES['imagefile']['size']) < 149000) {.
Same (as in step 4) with $row s you need to put the literas in quotes, so fix those lines as: $title = htmlspecialchars($row['title']); $bytes = $row['imgdata'];
Othewise than that it should work. However, it contains DB-security hole, which can lead to compromize your website, so I recommend you NOT to put this to any real site. Just for your own/friends fun.

Related

Appear A Picture Which User Input In Web PHP Using Database

Can anyone help me out? So, now I'm making a website, and one of the feature there is profile feature. In there I want user can upload their own picture, but if the value is null, then I want the picture is from the default image from mine. But I got a problem when I get the value of the pictures in database. I use a loop to determine whether the value is null or not, but all the images just appear from all the users images, not as the login user.
Here's the php code :
<?php
$arrayPictures[] = array();
$row=0;
while ($result= mysqli_fetch_object($query)) {
$arrayPictures[] = $result->pictures;
$row++;
}
for($i=0;$i<=$row;$i++)
{
if($arrayPictures[$i] == null)
{
?>
<img src="mypath\default.jpg" class="pictures" alt="">
<?php
}
else {
?>
<img class="pictures" src="mypath\<?php echo "$arrayPictures[$i]";?>" >
<?php
}
}
?>
So, what I want is if I login as 'User A', I just want to get the pictures from user A. But If User A not yet upload the pictures, I want to use the default pictures from mine.
This is the query code :
$id_account = $_SESSION['id'];
$query = mysqli_query($con, "SELECT * FROM t_akun WHERE username=$id_account");

Run two completely different sqli queries inside one script

I'm new to php.
I have this page:
<?php
function renderForm($id, $StaffFullName, $StaffJobPosition, $error)
{
?>
<!doctype html>
<html>
<head><title></title></head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div>'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p>ID: <?php echo $id; ?></p>
Name: * <input type="text" name="StaffFullName" value="<?php echo $StaffFullName; ?>"/><br/>
Job Position: * <select name="JobPosition">
<?php
$query = "SELECT * FROM LUT_JOBPOS";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)){
if ($StaffJobPosition == $row['JobposID'])
{
echo "<option value='{$row['JobposID']}' selected='selected'>{$row['JobposTitle']}</option>";
}
else {
echo "<option value='{$row['JobposID']}'>{$row['JobposTitle']}</option>";
}
}
$result->close();
?>
</select><br/>
<input type="submit" name="submit" value="Update">
<input type="button" onClick="parent.location='view.php'" value="Back">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
require_once('../../authenticate.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// do some funky stuff
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checking that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$query = "SELECT * FROM STAFF WHERE StaffID=$id";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);
$result->close();
// check that the 'id' matches up with a row in the database
if($row)
{
// get data
$StaffFullName = $row['StaffFullName'];
$StaffJobPosition = $row['StaffJobPosition'];
// show form
renderForm($id, $StaffFullName, $StaffJobPosition, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
So, what happens here is this:
When you open the page like edit.php?id=1, it fetches the data of the associated record from STAFF table and shows them on page for the user to edit them.
This part of the code works fine.
I also want the user to be able to select "Job Position" possible values from a drop down box. The drop down box should get its data from another table in database, LUT_JOBPOS.
This is the part of the code that doesn't work.
I was using mysql_query commands before on this page and it worked perfectly. However I was told to switch on mysqli_query instead.
Since I did the conversion I can't find how to run these two queries on the same script.
I messed a little bit with the require_once command and depending on where I call it I can run one query or another, but never both of them.
Looking at the logs of my web host the only thing I can see that may be relevant to my issue is:
"mod_fcgid: stderr: PHP Notice: Undefined variable: connection in /var/www/vhosts/myhostdomain.com/httpdocs/prod15/admin/staff/edit.php on line 24"
The connection variable comes from authenticate.php and it holds the connection parameters to the database. I'm sure it's set otherwise the first query (that gets the user data) wouldn't work.
I read somewhere that you can't run two sqli queries on the same script.
Then how I'm supposed to use a LUT table (lookup table)?
PS: I know that for showing the data I can use a UNION and that's what I do.
But when I edit the data I want the user to be able to select only from the possible values that exist on the LUT table (drop down select box)
Any help?
You have a lot of issues in your code. You really need to review it before use it in some real application, but for your specific problem, here is my guess.
You are calling the line $result = mysqli_query($connection, $query); in the line 24 and only after taht you call require_once('../../authenticate.php');.
As you said, the $connection var is defined in the authenticate.php, so in the line 24 is undefined.
Try to use require in the first line of your php script.

PHP Gallery CMS - Cannot Update Row in PHPMyadmin (LONG)

Project: Create a simple CMS for a photography website. My first project in php. :)
Problem: I am 90% finished with the CMS, but have ran into an issue of not being able to UPDATE row data after being READ from database.
The Goal: What I am trying to achieve seems simple. I have an admin page that reads image data from a database (id, image) and I am using a while loop to display this. It works great, and so does the delete button.
<?php
$query = "SELECT * FROM photos";
$select_all_photos_query = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($select_all_photos_query)) {
$photos_id = $row['photos_id'];
$photos_image = $row['photos_image'];
$photos_title = $row['photos_title'];
$photos_alt = $row['photos_alt'];
echo "<tr>
<td><input type='checkbox' name='photo' value='photo'></td>
<td><img src='../images/$photos_image' width='70'></td>
<td><a class='edit' href='edit_photo.php?&p_id={$photos_id}'>Edit</a></td>
<td><a onClick=\"javascript: return confirm('Are you sure?') \"class='delete' href='admin.php?delete={$photos_id}'>Delete</a></td>
</tr>";
}
?>
The problem I am having is the Edit Button in my while loop. I am using a get method in my href to get the edit_photo.php page with a parameter named "p_id" that is = to $photos_id.
Once I click the Edit button it sends me to the edit_photo.php page and I see all of the CORRECT information which tells me it is reading it correctly. I do get a error at the bottom ( Notice: Undefined variable: photos_file) See code below.
<?php
if (isset($_GET['p_id'])) {
$photo_id = $_GET['p_id'];
// Send query to photos table in database. //
$query = "SELECT * FROM photos WHERE photos_id = $photo_id";
$result = mysqli_query($connection, $query);
// Grab unique row from photos table in database. //
while($row = mysqli_fetch_assoc($result)) {
$photo_file = $row['photos_image'];
$photos_title = $row['photos_title'];
$photos_desc = $row['photos_alt'];
}
}
?>
Now. Here comes the big problem. When I try to update this information, the program busts. I even checked to see if my sql is correct, and if the queries are connecting to database. See code below.
<?php
if (isset($_POST['image'])) {
// After "Save" is pressed, the values white space is trimmed and assigned to a variable. //
$photos_title = trim($_POST['photos-title']);
$photos_desc = trim($_POST['photos-description']);
$photos_file = $_FILES['image']['name'];
$photos_file_temp = $_FILES['image']['name_tmp'];
// The new variables are sanitized. //
$photos_title = mysqli_real_escape_string($connection, $photos_title);
$photos_desc = mysqli_real_escape_string($connection, $photos_desc);
}
// Send the Update query to the database. //
$update_query = " UPDATE photos SET
photos_image = '$photos_file', photos_title = '$photos_title', photos_alt = '$photos_desc'
WHERE photos_id = '$photo_id' ";
// Test the SQL syntax. //
if(!$update_query) {
echo "Wrong." . " " . mysqli_error($connection);
}
else { echo "The SQL appears right..." . "<br>";
}
// Test the Update query. //
$update_result = mysqli_query($connection, $update_query);
if(!$update_result) {
echo "Didnt Connect." . " " . mysqli_error($connection);
} else {
echo "Sent query to to database.";
}
?>
<form action="edit_photo.php" class="settings-form" method="post" enctype="multipart/form-data">
<div class="form-group edit-preview">
<label for="image">Photo</label>
<img src= <?php echo "../images/$photo_file"?> >
<input type="file" name="file_upload">
</div>
<div class="form-group">
<label for="photos-title">Title</label>
<input type="text" name="photos-title" value= <?php echo "$photos_title" ?> class="form-control">
</div>
<div class="form-group">
<label for="photos-description">Description</label>
<textarea type="text" rows="4" name="photos-description" class="form-control" ><?php echo "$photos_desc" ?> </textarea>
</div>
<div class="form-group">
<input type="submit" name="image" class="btn btn-primary" value="Save Photo">
</div>
</form>
I have spent four days trying to figure this out with no luck.
For one thing, it's failing because of this ['name_tmp'].
The syntax is ['tmp_name'] - you had those inversed
Ref: http://php.net/manual/en/features.file-upload.php so your temp file never gets processed.
Then as per your edit and seeing your HTML form:
You're using name="file_upload" and then using the $_FILES['image'] array; those names need to match.
Error reporting would have helped you here.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Additional note.
If you are attempting to set the given (file) column as binary data instead of the path to the given file(s) as text, then you MUST escape it.
Otherwise, MySQL will throw you an error.
If that is the case, you will need to do the same as the others:
$photos_file = $_FILES['file_upload']['name']; // notice I changed it to what it should be
$photos_file = mysqli_real_escape_string($connection, $photos_file);
as per <input type="file" name="file_upload">
Check for errors against all your queries; you're not doing that in your $query = "SELECT * FROM photos WHERE photos_id = $photo_id"; query.
Add or die(mysqli_error($connection)) to all mysqli_query() should there be an error somewhere.
HTML stickler.
<textarea type="text" - <textarea> does not have a "text" type; remove it.
Footnotes.
If you want to check if your UPDATE truly was successful, use mysqli_affected_rows().
http://php.net/manual/en/mysqli.affected-rows.php
Instead of else { echo "The SQL appears right..." . "<br>"; }
As outlined in comments, your code is open an SQL injection.
If $photo_id is an integer, change
$photo_id = $_GET['p_id'];
to
$photo_id = (int)$_GET['p_id'];
However, if that is a string, then you will need to quote it and escape it in your query.

adding image attachement to php messages?

I have a php message system on my site. With it users can send and receive messages to each other, but recently I have been trying to look for a way to include image attachments, so a user could send a photo with their message.
Messages are stored in ptb_messages, and the message part (subject and body) works fine but I've created a column in my table called 'image' which is a BLOB type and a 'name' column to store the image name. But I'm new to php and mysql and no matter what I try, I can't seem to get the image to store in the database.
Can anyone help me and let me know where I'm going wrong?
<?php ob_start(); ?>
<?php
// CONNECT TO THE DATABASE
require('includes/_config/connection.php');
// LOAD FUNCTIONS
require('includes/functions.php');
// GET IP ADDRESS
$ip_address = $_SERVER['REMOTE_ADDR'];
?>
<?php require_once("includes/sessionframe.php"); ?>
<?php
confirm_logged_in();
if (isset ($_GET['to'])) {
$user_to_id = $_GET['to'];
}
?>
<?php
//We check if the form has been sent
if(isset($_POST['subject'], $_POST['message_content']))
{
$subject = $_POST['subject'];
$content = $_POST['message_content'];
$image = $POST ['image'];
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$subject = stripslashes($subject);
$content = stripslashes($content);
$image = stripslashes($image);
}
//We check if all the fields are filled
if($_POST['subject']!='' and $_POST['message_content']!='')
{
$sql = "INSERT INTO ptb_messages (id, from_user_id, to_user_id, subject, content, image) VALUES (NULL, '".$_SESSION['user_id']."', '".$user_to_id."', '".$subject."', '".$content."', '".$image."');";
mysql_query($sql, $connection);
echo "<div class=\"infobox2\">The message has successfully been sent.</div>";
}
}
if(!isset($_POST['subject'], $_POST['message_content']))
if (empty($_POST['subject'])){
$errors[] = 'The subject cannot be empty.';
if (empty($_POST['body'])){
$errors[] = 'The body cannot be empty.';
}
}
{
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<div class="subject">
<input name="subject" type="text" id="subject" placeholder="Subject">
<input type="file" name="image" id="image">
<textarea name="message_content" id="message_content" cols="50" placeholder="Message" rows="8" style="resize:none; height: 100px;"></textarea>
<input type="image" src="assets/img/icons/loginarrow1.png" name="send_button" id="send_button" value="Send">
</form>
<?php } ?>
<?php ob_end_flush() ?>
My advice would be to store the URL of the image in the data base, not the image file itself. Store the images in the server file system. The reasoning goes to the notion of backup and performance, where moving a huge blob column is not a good thing to repeat many times. Plus if someone ever writes SELECT * without a LIMIT clause, you're going to get a table scan that transfers all of the images.
That said, if you insist on storing an image in a data base table, you might want to use base64_encode() to make the image file safe for binary transfer. There is a corresponding decode function that you would call before sending the image to the browser.
http://php.net/manual/en/function.base64-encode.php
HTH, ~Ray

image click counter

Is there a way to count how many times an image how been clicked. And once the image is clicked have it displayed?
I am currently pulling random images from a database and want to show which is has been clicked the most.
<html> <body>
<div style="float:left"> <?php // Connect to the database mysql_connect ('localhost', 'root') ; mysql_select_db ('links');
// Number of images $num_displayed = 1 ;
// Select random images from the database $result = mysql_query ("SELECT * FROM links ORDER BY RAND() LIMIT $num_displayed");
// For all the rows that are selected while ($row = mysql_fetch_array($result))
// Display images { echo "<img src=\"".$row["image"]."\" border=0 alt=\"".$row["text"]."\">"; } ?> </div>
<div style="float:left; margin-left:100px"> <?php include("image2.php"); ?>
</div> </body> </html>
thanks.
Create a trigger in image table to count selects
CREATE TRIGGER `database_name`.`trigger_name` BEFORE SELECT INSERT ON
`database_name`.`images_table_name` FOR EACH ROW
BEGIN
UPDATE
`database_name`.`images_table_name`
SET
`database_name`.`images_table_name`.`counter` = `database_name`.`images_table_name`.`counter` + 1
WHERE
`database_name`.`images_table_name`.`id` = NEW.`id`;
END$$
Perform your querys ordering by counter field.
To register clicks, implements a click tracker quering an update on second field, like 'clicks'
You can do this using javascript:
In head tag:
<script type="text/javascript">
var count = 0;
function changevar(){
count = count + 1;
if (count == 3) {
alert('Done');
}
}
</script>
In body tag:
<img src="image.png" onClick="changevar()"/>
How about counting each time the image is displayed? This is an option if and only if there are no other images which can be to it in the way an image album viewer works.
Use php to render the image, and run a small script in there which increments the number of times this image has been clicked (or displayed). Alternatively you could create an entry for each time the image is displayed saving lots more possibly interesting information such as image, last_view, ip, count and or referrer (if it works;untested). Recording the IP would allow you to keep track of unique views with count showing you how many times they reviewed the image; this depends on how you implement it.
$name = trim($_GET['img']);
if (!isset($_GET['img'] || empty($name)) {
// Check url var wasn't omitted or typed incorrectly.
die("Image not specified.");
}
// This is just an example path. It would be a good idea to specify a path
// like this to ensure that people don't try and use it to display files
// that you wouldn't want them too.
//eg. images you don't want to keep records of.
$image = "/images/$name";
$date = time();
$ip = $_SERVER['REMOTE_ADDR'];
$ref = $_SERVER['HTTP_REFERER'];
if (!file_exists($image)) {
// Ensure that something exists at $image
die("Invalid image.");
}
$f = fopen($image, 'r');
if (!$f) {
// Make sure that the contents of the file can be opened.
die("Unable to open image.");
}
$info = #imagegetsize($image);
if (!$info) {
// This is to make sure that the $image contains a path
// to an image not just a regular file.
die("Invalid image type.");
}
Header("Content-type: {$info['mime']}");
echo fread($f, filesize($image));
fclose($f);
/****************
* Script for saving image 'click' information.
***************/
exit;
Display the image like this
<img src="/image.php?img=example.png" />
If you are having troubles and images are displaying correctly, open the path in your browser to see the errors.

Categories