include thumbnail upload in php sql code - php

I have an upload to mysql script in php that works perfectly for a property website - inserting all relevant fields and the main image.
The problem is however, this image is used in a slideshow which identifies the thumbnail as xxxxxt.png where the main image is xxxxx.png for example.
My php code is:
<?php include 'dbc.php'; page_protect();
if(!checkAdmin()) {header("Location: login.php");
exit();
}
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$login_path = #ereg_replace('admin','',dirname($_SERVER['PHP_SELF']));
$path = rtrim($login_path, '/\\');
foreach($_GET as $key => $value) {
$get[$key] = filter($value);
}
foreach($_POST as $key => $value) {
$post[$key] = filter($value);
}
$uniqid = md5(uniqid(mt_rand()));
?>
<?php
if($_FILES['photo']) //check if we uploading a file
{
$target = "images/properties/";
$target = $target . basename( $_FILES['photo']['name']);
$title = mysql_real_escape_string($_POST['title']);
$desc = mysql_real_escape_string($_POST['desc']);
$extra = mysql_real_escape_string($_POST['extra']);
$postcode = mysql_real_escape_string($_POST['postcode']);
$price = mysql_real_escape_string($_POST['price']);
$pandp = mysql_real_escape_string($_POST['pandp']);
$pic = "images/properties/" .(mysql_real_escape_string($_FILES['photo']['name']));
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
mysql_query("INSERT INTO `furnishings` (`title`, `postcode`, `desc`, `extra`, `productcode`, `price`, `status`, `pandp`, `photo`) VALUES ('$title', '$postcode', '$desc', '$extra', '" . $uniqid . "', '$price', 'tolet.png', '$pandp', '$pic' )") ;
echo "The property has been added to the lettings portfolio";
}
else
{
echo "Error uploading new property - please ensure all the fields are correctly entered and the file is an image";
}
}
?>
The html code for the upload form is:
<form enctype="multipart/form-data" action="addlet.php" method="POST">
<table width="600px" border="2" cellpadding="5"class="myaccount">
<tr>
<td width="135">Title: </td>
<td width="427"><input name="title" type="text" size="40"/></td>
</tr>
<tr>
<td>Description: </td>
<td><textarea name = "desc" rows="3" cols="40"></textarea></td>
</tr>
<tr>
<td>Property Features: </td>
<td><textarea name = "extra" rows="3" cols="40"></textarea></td>
</tr>
<tr>
<td>Postcode: </td>
<td><input name = "postcode" type="text" size="40" /></td>
</tr>
<tr>
<td>Price per week (£): </td>
<td><input name = "price" type="text" size="40" /></td>
</tr>
<tr>
<td>Furnished/Unfurnished: </td>
<td><input name = "pandp" type="text" size="40" /></td>
</tr>
<tr>
<td>Main Image: </td>
<td><input type="file" name="photo" class="forms" /></td>
</tr> </table></p>
<p> <input type="submit" class="CMSbutton" value="Add" /></p>
</form>
Is there a simple way to add an extra line of code which will insert two images into the desired target on the server, (images/properties/) - one the original name of the image, and one the thumbnail version (with a "t" on the end of the image name).
As they are both reasonably small I am not fussed about resizing the thumbnail as the code is pretty much done I dont want to have to rebuild everything!
Any help much appreciated
Thanks
JD

If your image file is being moved into place successfully, I would take this strategy: create columns is_uploaded, is_thumb_created and is_image_created in your database table. Upon successful upload and move, set the first one.
Then run a cron or other background system that generates a 'main' and a 'thumb' view from the uploaded image (bearing in mind that the uploaded image may be way too large for an ordinary screen-size picture). Upon the successful generation of these images, the relevant columns can be set as 'done', and the row remains non-live until this happens.
This approach is a great deal more scalable, incidentally, since it is not clogging up your web request with expensive image processing.

Related

image not uploading/moving into folder

i am uploading an image , image title is getting added to database but the file(image is not uploading/moving to the folder), i am getting 404 error for that image , i have set that folder permissions to 0777 and also max upload is 1024MB
$article_image = $_FILES['image']['name'];
$image_tmp = $_FILES['image']['tmp_name'];
define ('SITE_ROOT', realpath(dirname('_FILE_')));
move_uploaded_file($image_tmp,SITE_ROOT.'/images/$article_image');
$add="insert into articles(article_title,article_date,article_author,category,article_image,article_keywords,article_content) values ('$article_title','$article_date','$article_author','$article_category','$article_image','$article_keywords','$article_content')" ;
if(mysqli_query($conn,$add)== 1 ){
echo "<script> alert('article added')</script>";
}
else{
echo "failed".mysqli_error($conn) ;
}
}
what mistake am i doing ?
EDIT here is my html code
<form method="post" action="addarticle.php" enctype="multipart/form-data">
<table align="center">
<tr>
<td align="center"><h1> ADD ARTICLE</h1></td>
</tr>
<tr>
<td>Article Title</td>
<td><input type="text" name="title"></td>
<tr>
<td>Article Keyword</td>
<td><input type="text" name="keywords"></td>
<tr>
<td>Article Image</td>
<td><input type="file" name="image"></td>
</tr>
<td>Article Content</td>
<td><textarea name="content" cols="90" rows="30"></textarea></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="submit"></td>
</tr>
</table>
</form>
Check your line with:
realpath(dirname('__FILE__'));
__FILE__
is a magic constant, and should not be wrapped in single or double quotes.
If you were to echo out the result of that function call you would probably see a different path than what you're expecting.
You're also trying to use string interpolation with single quotes around the variable instead of double:
SITE_ROOT.'/images/$article_image';
Should be:
SITE_ROOT."/images/$article_image";
Example:
if (!empty($_FILES['image'])) {
$tmp_file_to_upload = $_FILES['image'];
if ($_FILES['image']['error'] == UPLOAD_ERR_OK) {
$uploaded_name = $tmp_file_to_upload['name'];
$tmp_name = $tmp_file_to_upload['tmp_name'];
$destination = realpath(dirname(__FILE__))."images/$uploaded_name";
if (!move_uploaded_file($tmp_name, $destination)) {
die('Error uploading file.');
}
} else {
die('Error uploading file.');
}
}
Try this, Variable concatenation issue '/images/'.$article_image
move_uploaded_file($image_tmp,SITE_ROOT.'/images/'.$article_image);
instead of
move_uploaded_file($image_tmp,SITE_ROOT.'/images/$article_image');

How To Upload Multiple Images With Links To Them In mysql

Currently I have a code which is working perfectly for one image upload. But i want to upload multiple images at a time with same Image Title, Image Description for image group being uploaded as these images will be used in photo slideshow(See Images below please)
My Current Code is as follows -
PHP Code -
$bsq->connect_db();
$fileName = $_FILES["image"]["name"];
$fileNameNew = preg_replace('/\s+/', '_', $fileName);
$fileTmpLoc = $_FILES["image"]["tmp_name"];
// Path and file name
$pathAndName = "uploads_admin/".$fileNameNew;
// Run the move_uploaded_file() function here
$moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);
// Evaluate the value returned from the function if needed
if($_POST['action']=="add"){
$all_columns[]="image_subject";
$all_columns[]="image_name";
$all_columns[]="clinic";
$all_columns[]="image_link";
//Get All values to insert in to table
$all_values[]=addslashes($_POST["image_subject"]);
$all_values[]=addslashes($_POST["image_name"]);
$all_values[]=addslashes($_POST["clinic"]);
$all_values[]=addslashes($pathAndName );
//=====================
$qry=$bsq->webdreaminsert("sa_galleryuploads_by_admin",$all_columns,$all_values,'');
echo mysql_error();
header("location:upload_file_for_downloading_list.php");
///////////////////////////////////////////////////
}
And HTML Form For upload Image Is As follows -
<form action="" method="post" enctype="multipart/form-data" name="addtwebinar1" id="addtwebinar1" onsubmit="javascript:return validateimage1();" >
<input type="hidden" value="add" name="action" />
<table width="90%" align="center" border="0" cellpadding="0" cellspacing="0" class="ListTable1">
<tr class="HeadBr">
<td colspan="4"><div align="center"><strong>Add Images For Photo Gallery</strong></div></td>
</tr>
<tr >
<td>Image Title*</td>
<td><input name="image_name" id="image_name" type="text" size="40" value="" /></td>
</tr>
<tr>
<td>Image Description In Short*</td>
<td><input name="image_subject" id="image_subject" type="text" size="40" value="" /></td>
</tr>
<tr >
<td>Clinic Name*</td>
<td>
<select name="clinic" id="message" >
<option value="">Select Clinic</option>
<option value="arogya">1. Arogyawardhini Ayurved Clinic</option>
<option value="smruti">2. Smruti Ayurved Clinic</option>
<option value="tarpan">3. Tarpan Ayurved Clinic</option>
<option value="vishwa">4. Vishwawardhini Ayurved Clinic</option>
</select>
</td>
</tr>
<tr >
<td>Your Image For Upload* </td>
<td><label for="image">File To Upload: </label><br>
<input type="file" size="40" name="image" id="image" /><br />
</td>
</tr>
<tr>
<td></td>
<td><button >Upload</button></td>
</tr>
</table>
</form>
Current Look of My Active Image upload Form -
And I Want Like Below (Created Graphically)
You can use a for loop.
For the form, do something like this:
for($i = 1; $i <= 4; $i++) {
echo "<input type=\"file\" size=\"40\" name=\"image{$i}\" id=\"image{$i}\" /><br />";
}
And for the processing, just put all of that in a for loop as well.
for($i = 1; $i <= 4; $i++) {
$fileName = $_FILES["image".$i]["name"];
$fileNameNew = preg_replace('/\s+/', '_', $fileName);
$fileTmpLoc = $_FILES["image".$i]["tmp_name"];
// Path and file name
$pathAndName = "uploads_admin/".$fileNameNew;
// Run the move_uploaded_file() function here
$moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);
// Evaluate the value returned from the function if needed
if($_POST['action']=="add"){
$image_name = mysql_real_escape_string($_POST['image_name']);
$image_subject = mysql_real_escape_string($_POST['image_subject']);
$clinic = mysql_real_escape_string($_POST['clinic']);
$image_link = "http://".$_SERVER['HTTP_HOST'].rtrim(dirname($_SERVER['REQUEST_URI']), "\\/")."/".$pathAndName;
//=====================
mysql_query("INSERT INTO `sa_galleryuploads_by_admin` VALUES ('', '{$image_name}', '{$image_subject}', '{$clinic}', '{$image_link}' )") or die(mysql_error());
if(!mysql_error()) {
echo "success";
}
}
You can edit the number that the loop goes up to, to match the number of fields/images you want to show. Good luck!
edit: You also need to sanitize validate your inputs. At the very least, use mysql_real_escape_string().
Also, mysql_* functions are deprecated. You should switch to using either mysqli or pdo. I'd suggest mysqli to start off, because it also offers a procedural approach, whereas pdo is completely object oriented.

Image upload via php and adding details to mysql

So I have searched everywhere and i cannot figure this out at all. I am trying to upload POST info and the image name to SQL and also upload the image to the uploads directory. SQL will update all info except the image line nor will it actually upload the image. Ill post code below
EDIT: I got it to add the file name into the SQL table but still it wont upload file.
FORM info
<table width="100%" border="0">
<tr><form action="specialadd.php" method="post">
<td>Name of Special</td>
<td>Special Price</td>
</tr>
<tr>
<td valign="top">
<input type="text" name="name"></td>
<td><input type="text" name="price"></td>
</tr>
<tr>
<td>Description #1</td>
<td>Description #2</td>
</tr>
<tr>
<td><textarea name="desc1" rows="6" cols="50"></textarea></td>
<td><textarea name="desc2" rows="6" cols="50"></textarea></td>
</tr>
<tr>
<td>Upload Photo</td>
<td> </td>
</tr>
<tr>
<td><input type="file" name="image"></td>
<td><input type="submit" value="Save Your Special"></form></td>
</tr>
</table>
PHP Info
<?php
//This is the directory where images will be saved
$target = "/public_html/uploads";
$target = $target . basename( $_FILES['image']['name']);
//This gets all the other information from the form
$name=$_POST['name'];
$desc1=$_POST['desc1'];
$desc2=$_POST['desc2'];
$price=$_POST['price'];
$image=($_FILES['image']['name']);
// Connects to your Database
include "process/connect.php";
//Writes the information to the database
mysql_query("UPDATE specials
SET name='$name', desc1='$desc1', desc2='$desc2', price='$price', image='$image'") ;
//Writes the photo to the server
if(move_uploaded_file($_FILES['image']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
I figured it out also thanks on the enctype i completely forgot about that. It works perfectly.
You need to add
enctype="multipart/form-data"
in the form so your form should be
<form action="specialadd.php" method="post" enctype="multipart/form-data">

Adding uploading to edit page

I have been trying the whole week to get this too work but haven't had any luck thus far. I am building an employee system, being my first project I could really use your help.
I have a database with a table called ref_employees with x amount of fields.
I managed to get my hands on some source to edit the record and thought that my problem was solved. Although the source helped me to edit the records, the client needs more functionality by means of upload and storing functionality. I have edited the code accordingly but have 2 issues now.
1) I had to add the upload form separate to the editing form because when the edits' update is clicked it clears the upload fields within the db even after adding echoing out the current values within the upload fields in the db.
2) The uploads shows that it is uploading but is doesn't get saved in the specified directory. The permissions are set to 777, and the file names are not captured in the database in the relevant fields. I think it is because the upload function is in a separate page and not on the same page as the upload form.
I need it to upload the file, store it in a directory and finally place the file name in the db where the warning fields are, but it needs to be captured under the record (employee) being edited.
I am new to this and all help is appreciated.
The edit page:
<?php
include 'core/init.php';
protect_page();
include 'includes/overall/header.php';
error_reporting(1);
?>
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($idnumber, $firstname, $lastname, $department, $manager, $startdate, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit Record</title>
</head>
<body>
<div class="article">
<h1>Employee Details</h1>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="hidden" name="idnumber" value="<?php echo $idnumber; ?>"/>
<div>
<p>* Required</p>
<p><strong>ID:</strong> <?php echo $idnumber; ?></p>
<table cellpadding="5" cellspacing="5">
<tr>
<td><strong>First Name: *</strong></td>
<td><input type="text" name="firstname" value="<?php echo $firstname; ?>"/></td>
</tr>
<tr>
<td><strong>Last Name: *</strong></td>
<td> <input type="text" name="lastname" value="<?php echo $lastname; ?>"/></td>
</tr>
<tr>
<td><strong>Department: *</strong> </td>
<td> <input type="text" name="department" value="<?php echo $department; ?>"/></td>
</tr>
<tr>
<td><strong>Manager/Superviser: *</strong></td>
<td><input type="text" name="manager" value="<?php echo $manager; ?>"/></td>
</tr>
<tr>
<td><strong>Start Date: *</strong></td>
<td><input type="text" name="startdate" value="<?php echo $startdate; ?>"/></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Submit" class="btn"></td>
</tr>
</table>
</form>
<tr>
<td>
<table cellpadding="5" cellspacing="0">
<form action="includes/add.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="idnumber" value="<?php echo $idnumber; ?>"/>
<th>Ad Warnings Documents</th>
<tr>
<td>Warning File 1</td>
<td><input type="file" name="warning1" value="<?php echo $warning1;?>" /></td>
</tr>
<tr>
<td>Warning File 2</td>
<td><input type="file" name="warning2" value="<?php echo $warning2;?>" /></td>
</tr>
<tr>
<td>Warning File 3</td>
<td><input type="file" name="warning3" value="<?php echo $warning3;?>" /></td>
</tr>
<tr><td><input type="submit" name="submit" value="upload"></td></tr>
</table>
</td>
<td></td>
</tr>
</table>
</div>
</body>
</html>
<?php
}
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['idnumber']))
{
// get form data, making sure it is valid
$idnumber = $_POST['idnumber'];
$firstname = mysql_real_escape_string(htmlspecialchars($_POST['firstname']));
$lastname = mysql_real_escape_string(htmlspecialchars($_POST['lastname']));
$department = mysql_real_escape_string(htmlspecialchars($_POST['department']));
$manager = mysql_real_escape_string(htmlspecialchars($_POST['manager']));
$startdate = mysql_real_escape_string(htmlspecialchars($_POST['startdate']));
// check that firstname/lastname fields are both filled in
if ($firstname == '' || $lastname == '')
{
// generate error message
$error = 'ERROR: Please fill in all fields!';
//error, display form
renderForm($idnumber, $firstname, $lastname, $department, $manager, $startdate, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE ref_employees SET firstname='$firstname', lastname='$lastname', department='$department', manager='$manager', startdate='$startdate' WHERE idnumber='$idnumber'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: employeelist.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
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 (checing that it is numeric/larger than 0)
if (isset($_GET['idnumber']) && is_numeric($_GET['idnumber']) && $_GET['idnumber'] > 0)
{
// query db
$idnumber = $_GET['idnumber'];
$result = mysql_query("SELECT * FROM ref_employees WHERE idnumber=$idnumber")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$department = $row['department'];
$manager = $row['manager'];
$startdate = $row['startdate'];
$warning1 = $row['warning1'];
$warning2 = $row['warning2'];
$warning3 = $row['warning3'];
// show form
renderForm($idnumber, $firstname, $lastname, $department, $manager, $startdate, '');
}
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!';
}
}
?>
<h1>Additional options</h1>
</div>
The file upload source file add.php
<?php
include 'core/init.php';
protect_page();
include 'includes/overall/header.php';
error_reporting(1);
?>
<?php
//This is the directory where images will be saved
$target = "files/empdocs";
$target1 = $target . basename( $_FILES['warning1']['name']);
$target2 = $target . basename( $_FILES['warning2']['name']);
$target3 = $target . basename( $_FILES['warning3']['name']);
//This gets all the other information from the form
$warning1=($_FILES['warning1']['name']);
$warning2=($_FILES['warning2']['name']);
$warning3=($_FILES['warning3']['name']);
//Writes the information to the database
mysql_query("INSERT INTO ref_employees VALUES ('$warning1', '$warning2', '$warning3')") ;
//Writes the file to the server
if (move_uploaded_file($_FILES['warning1']['tmp_name'], $target1)
&& move_uploaded_file($_FILES['warning2']['tmp_name'], $target2)
&& move_uploaded_file($_FILES['warning3']['tmp_name'], $target3)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>

add unique id to php mysql upload

Is there a quick method to add a unique id to a php mysql upload- I have scrolled through these forums but was hoping there is a much simpler method to achieve my aim.
Essentially, I have an upload that works perfectly - and I am hoping to add a product code to each item that will be generated using the auto-incremented unique id field in mysql.
So far I have the following php:
<?php include 'dbc.php'; page_protect();
if(!checkAdmin()) {header("Location: login.php");
exit();
}
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$login_path = #ereg_replace('admin','',dirname($_SERVER['PHP_SELF']));
$path = rtrim($login_path, '/\\');
foreach($_GET as $key => $value) {
$get[$key] = filter($value);
}
foreach($_POST as $key => $value) {
$post[$key] = filter($value);
}
?>
<?php
if($_FILES['photo']) //check if we uploading a file
{
$target = "images/furnishings/";
$target = $target . basename( $_FILES['photo']['name']);
$title = mysql_real_escape_string($_POST['title']);
$desc = mysql_real_escape_string($_POST['desc']);
$price = mysql_real_escape_string($_POST['price']);
$pandp = mysql_real_escape_string($_POST['pandp']);
$pic = "images/furnishings/" .(mysql_real_escape_string($_FILES['photo']['name']));
$productcode = "FUR000" .(mysql_real_escape_string($_POST['id']));
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
mysql_query("INSERT INTO `furnishings` (`title`, `desc`, `price`, `pandp`, `photo`,`productcode`) VALUES ('$title', '$desc', '$price', '$pandp', '$pic', '$productcode')") ;
echo "The product has been added to the furnishings category";
}
else
{
echo "Please fill out the specifications and select the respective file to upload for the main image";
}
}
?>
And the following HTML:
<form enctype="multipart/form-data" action="addfurn.php" method="POST">
<table width="100%" border="2" cellpadding="5"class="myaccount">
<tr>
<td>Title: </td>
<td><input type="text" name="title" /></td>
</tr>
<tr>
<td>Description: </td>
<td><input type="text" name = "desc" /></td>
</tr>
<tr>
<td>Price: </td>
<td><input type="text" name = "price" /></td>
</tr>
<tr>
<td>P&P: </td>
<td><input type="text" name = "pandp" /></td>
</tr>
<tr>
<td>Main Image: </td>
<td><input type="file" name="photo" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" class="CMSbutton" value="Add" /></td>
</tr>
</table>
</form>
Now given everything works - the only "problem line" in the code is:
$productcode = "FUR000" .(mysql_real_escape_string($_POST['id']));
assuming that as the id hasnt yet been generated it cannot add it to the insert query - therefore the table in mysql simply returns FUR000 for each new item added.
Is there a way to amend this line to auto-increment in mysql in a similar fashion to the addition of new lines - or do I have to include a unique code for each item in my HTML table?
Any help much appreciated!
Thanks
JD
you need 2 queries for this.
first, insert your data without productcode.
next, get id using mysql_insert_id()
finally, create your productcode and update your table using this newly generated id
however, I see no point in such a field. Why not to create it on the fly?
You want to use uniqid, which generates unique ids. I'd recommend using it with more entropy to be on the safe side.

Categories