I wonder whether someone can help me please.
I've created this form which allows users to record details about a specific location they've visited and as each location is saved a unique incrementing 'locationid' is saved as part of the mySQL record.
I've extended this further and when they click on the add 'Add Image' Button they will be able to save image files connected to the 'location' record created. This is done via the code below which saved the original image file and thumbnail version into a folder on my server.
<?php
//define a maxim size for the uploaded images
//define ("MAX_SIZE","100");
// define the width and height for the thumbnail
// note that theese dimmensions are considered the maximum dimmension and are not fixed,
// because we have to keep the image ratio intact or it will be deformed
define ("WIDTH","150");
define ("HEIGHT","100");
// this is the function that will create the thumbnail image from the uploaded image
// the resize will be done considering the width and height defined, but without deforming the image
function make_thumb($img_name,$filename,$new_w,$new_h)
{
//get image extension.
$ext=getExtension($img_name);
//creates the new image using the appropriate function from gd library
if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))
$src_img=imagecreatefromjpeg($img_name);
if(!strcmp("png",$ext))
$src_img=imagecreatefrompng($img_name);
//gets the dimmensions of the image
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);
// next we will calculate the new dimmensions for the thumbnail image
// the next steps will be taken:
// 1. calculate the ratio by dividing the old dimmensions with the new ones
// 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
// and the height will be calculated so the image ratio will not change
// 3. otherwise we will use the height ratio for the image
// as a result, only one of the dimmensions will be from the fixed ones
$ratio1=$old_x/$new_w;
$ratio2=$old_y/$new_h;
if($ratio1>$ratio2) {
$thumb_w=$new_w;
$thumb_h=$old_y/$ratio1;
}
else {
$thumb_h=$new_h;
$thumb_w=$old_x/$ratio2;
}
// we create a new image with the new dimmensions
$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
// resize the big image to the new created one
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
// output the created image to the file. Now we will have the thumbnail into the file named by $filename
if(!strcmp("png",$ext))
imagepng($dst_img,$filename);
else
imagejpeg($dst_img,$filename);
//destroys source and destination images.
imagedestroy($dst_img);
imagedestroy($src_img);
}
// This function reads the extension of the file.
// It is used to determine if the file is an image by checking the extension.
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
// This variable is used as a flag. The value is initialized with 0 (meaning no error found)
//and it will be changed to 1 if an error occurs. If the error occures the file will not be uploaded.
$errors=0;
// checks if the form has been submitted
if(isset($_POST['Submit']))
{
$title = ($_POST['title']);
if ($title == '') // if title is not set
$title = '(No Title Provided)';// use (empty title) string
//reads the name of the file the user submitted for uploading
$image=$_FILES['image']['name'];
// if it is not empty
if ($image == '')
{
echo '<b> Error! </b> - You <b> must </b> select a file to upload before selecting the <b> "Upload image" </b> button. Please try again.';
$errors=1;
}
else
if ($image)
{
// get the original name of the file from the clients machine
$filename = stripslashes($_FILES['image']['name']);
// get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
// if it is not a known extension, we will suppose it is an error, print an error message
//and will not upload the file, otherwise we continue
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png"))
{
echo '<b> Error! </b> - The image that you attempted to upload is not in the correct format. The file format <b> must </b> be one of the following: <b> "jpg", "jpeg" </b> or <b> "png" </b>. Please try again.';
$errors=1;
}
else
{
// get the size of the image in bytes
// $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which the uploaded file was stored on the server
$size=getimagesize($_FILES['image']['tmp_name']);
$sizekb=filesize($_FILES['image']['tmp_name']);
//compare the size with the maxim size we defined and print error if bigger
if ($sizekb > 1150000)
{
echo '<b> Error! </b> - The file that you are attempting to upload is greater than the prescribed <b> 1MB </b> limit. Please try again.';
$errors=1;
}
//we will give an unique name, for example the time in unix time format
$image_name=$title.'.'.$extension;
//the new name will be containing the full path where will be stored (images folder)
$newname="images/".$image_name;
$copied = copy($_FILES['image']['tmp_name'], $newname);
//we verify if the image has been uploaded, and print error instead
if (!$copied)
{
echo '<b> Error! </b> Your file has not been loaded';
$errors=1;
}
else
{
// the new thumbnail image will be placed in images/thumbs/ folder
$thumb_name='images/thumbs/'.$image_name;
// call the function that will create the thumbnail. The function will get as parameters
//the image name, the thumbnail name and the width and height desired for the thumbnail
$thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT);
}} }}
//If no errors registred, print the success message and show the thumbnail image created
if(isset($_POST['Submit']) && !$errors)
{
echo '<br><b> Success! </b> - Your image has been uploaded</br>';
echo '<img src="'.$thumb_name.'">';
}
?>
<!-- next comes the form, you must set the enctype to "multipart/form-data" and use an input type "file" -->
<form name="newad" method="post" enctype="multipart/form-data" action="">
<table>
<tr><td><input type="text" name="title" ></td></tr>
<tr><td><input type="file" name="image" ></td></tr>
<tr><td><input name="Submit" type="submit" value="Upload image"></td></tr>
</table>
</form>
The problem I'm having is that I can't find a way of linking the 'location (parent)' record and the 'image (child)' record. Because the image upload is part of the parent record creation, the unique 'locationid' field hasn't been created.
I just wondered whether someone, perhaps with a lot more experience that I could suggest a way of overcoming this problem?
Many thanks and kind regards
Then uploading an image, save it's path on server to some storage (PHP session for example)
When saving your location, link images from session with created location and remove them from session (but not from server storage)
If action is cancelled - remove saved images from session and from server storage.
Also you need some garbage colection for the case if user just closing his browser without pressing any "cancel" buttons in yout UI.
Related
Bear with me, im new to PHP. I got this very nice tutorial from here:
Add watermark image PHP - developphp.com
The problem is, the cropping ratio is not proportionate. If I have wider image, it crop 500px width and the height is not proportion to the width the same as the height (tall image crop to 500px and width is lesser px.)
I want to make it proportional as 500px both width and height no matter how wide or tall the image is and should crop center.
Been searching and trying other method but failed. Hope someone can help. Thanks!
Here is the code:
<?php
// Access the $_FILES global variable for this specific file being uploaded
// and create local PHP variables from the $_FILES array of information
$fileName = $_FILES["uploaded_file"]["name"]; // The file name
$fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["uploaded_file"]["type"]; // The type of file it is
$fileSize = $_FILES["uploaded_file"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["uploaded_file"]["error"]; // 0 for false... and 1 for true
$fileName = preg_replace('#[^a-z.0-9]#i', '', $fileName); // filter
$kaboom = explode(".", $fileName); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
// START PHP Image Upload Error Handling -------------------------------
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
} else if($fileSize > 5242880) { // if file size is larger than 5 Megabytes
echo "ERROR: Your file was larger than 5 Megabytes in size.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
} else if (!preg_match("/.(gif|jpg|png)$/i", $fileName) ) {
// This condition is only if you wish to allow uploading of specific file types
echo "ERROR: Your image was not .gif, .jpg, or .png.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
} else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
echo "ERROR: An error occured while processing the file. Try again.";
exit();
}
// END PHP Image Upload Error Handling ---------------------------------
// Place it into your "uploads" folder mow using the move_uploaded_file() function
$moveResult = move_uploaded_file($fileTmpLoc, "uploads/$fileName");
// Check to make sure the move result is true before continuing
if ($moveResult != true) {
echo "ERROR: File not uploaded. Try again.";
exit();
}
// Include the file that houses all of our custom image functions
include_once("ak_php_img_lib_1.0.php");
// ---------- Start Universal Image Resizing Function --------
$target_file = "uploads/$fileName";
$resized_file = "uploads/resized_$fileName";
$wmax = 500;
$hmax = 500;
ak_img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
// ----------- End Universal Image Resizing Function ----------
// ---------- Start Convert to JPG Function --------
if (strtolower($fileExt) != "jpg") {
$target_file = "uploads/resized_$fileName";
$new_jpg = "uploads/resized_".$kaboom[0].".jpg";
ak_img_convert_to_jpg($target_file, $new_jpg, $fileExt);
}
// ----------- End Convert to JPG Function -----------
// ---------- Start Image Watermark Function --------
$target_file = "uploads/resized_".$kaboom[0].".jpg";
$wtrmrk_file = "watermark.png";
$new_file = "uploads/protected_".$kaboom[0].".jpg";
ak_img_watermark($target_file, $wtrmrk_file, $new_file);
// ----------- End Image Watermark Function -----------
// Display things to the page so you can see what is happening for testing purposes
echo "The file named <strong>$fileName</strong> uploaded successfuly.<br /><br />";
echo "It is <strong>$fileSize</strong> bytes in size.<br /><br />";
echo "It is an <strong>$fileType</strong> type of file.<br /><br />";
echo "The file extension is <strong>$fileExt</strong><br /><br />";
echo "The Error Message output for this upload is: $fileErrorMsg<br />";
?>
i'm currently making a website for my final year university project, which requires a photo upload function. Currently when a user uploads a photo, the photo is stored in a folder in the remote server. I need the images to go into a database and so I was wondering if anyone had any advice as to how to do this and where to place the code to send the uploaded content to the database within the following code, also I need for it to work where when each individual user uploads an image, they are all displayed for all to see, and not as it is currently, where only one image is displayed at a time and when the page is refreshed, the image disappears. Hope that all made sense, any help would be greatly appreciated. Thank you.
<?php include_once("home_start.php"); ?>
<h1>Upload your images here:</h1>
<div id="fileselect" style="border-bottom:thin #000000 solid; border- collapse:collapse">
<form id="frmSimple" action="home.php" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" id="filename" name="filename" size="10" /><br />
<input type="submit" id="submit" name="submit" value=" Upload " />
</form>
</div>
<div id="feedback">
<?php
// Determine whether a file was uploaded
if ($_FILES) {
// Put file properties into variables
$name = $_FILES['filename']['name'];
$size = $_FILES['filename']['size'];
$tmp_name = $_FILES['filename']['tmp_name'];
// Determine whether file is png, jpg or other
switch($_FILES['filename']['type']) {
case 'image/jpeg': $ext = "jpg"; break;
case 'image/png': $ext = "png"; break;
//default: ext = ''; break;
}
//validate against file type
// if $ext is empty string (therefore null or false) image is not a jpg or png
if($ext){
// validate against file size
if($size < 1000000){
// Create a safe name for the file and store in a safe location
$n = "$name"; // Could add .$ext to enforce file type
$n = ereg_replace("[^A-Za-z0-9.]","",$n); // Remove all except alphanumeric characters and
$n = strtolower($n); // Convert to lower case (platform independence)
$n = "uploaded_images/$n"; // Add folder to force safe location
move_uploaded_file($tmp_name, $n); // Move to the safe location and give it the safe
echo "<p>Uploaded image '$name' as '$n': </p>";
echo "<img src='$n' />";
}
else echo "<p>'$name' is too big - 50KB max (50000 bytes).</p>";
}
else echo "<p>'$name' is an invalid file - only jpg and png accepted.</p>";
}
else echo "<p>No image has been uploaded.</p>";
?>
</div>
<?php include_once("home_end.php"); ?>
I would highly recommend against it. Instead, stored the photos in a folder and reference their location from the database (i.e. a string pointing to their location on the filesystem).
However, if you're so inclined to store it in the database, you need to:
Get the file contents after upload
Ensure that the contents don't have any characters that would conflict with your SQL (easy solution is to encode it somehow; base64 perhaps?)
Perform your SQL insert
Again - this is a bad idea. Don't do it - save it to the filesystem.
Also, the following line:
move_uploaded_file($tmp_name, $n);
without any checks of file type, or file integrity, makes it trivial to upload a shell to your box.
Once after the file uploaded successfully get the uploaded image path.
$file_type='jpg'; //if you are using more than one type write a switch case
$file_size = filesize($file);
$fp = fopen($file,'r');
$content = fread($fp,$file_size);
$content = addslashes($content); //content is a binary data of the image
fclose($fp);
To save the image in database. Write a insert query with whatever fields you want $file_name, $file_type, $file_size and content. I am assuming you are able to connect to database successfully.
mysql_query("INSERT INTO Images (id,file_name,file_type,file_size,content)
VALUES ('bird', 'jpg',340kb,'binarydata')");
I use this code to upload images to my server. But for some reason my thumbnails get a black background instead of being transparent as they originally was.
I've tried using this "guide": http://www.akemapa.com/2008/07/10/php-gd-resize-transparent-image-png-gif/
But without success. I have no idea how I implement that piece of code into the one I use.
If anyone can help, please do so :)
<?php
//define a maxim size for the uploaded images
define ("MAX_SIZE","10240");
// define the width and height for the thumbnail
// note that theese dimmensions are considered the maximum dimmension and are not fixed,
// because we have to keep the image ratio intact or it will be deformed
define ("WIDTH","200");
define ("HEIGHT","200");
// this is the function that will create the thumbnail image from the uploaded image
// the resize will be done considering the width and height defined, but without deforming the image
function make_thumb($img_name,$filename,$new_w,$new_h)
{
//get image extension.
$ext=getExtension($img_name);
//creates the new image using the appropriate function from gd library
if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))
$src_img=imagecreatefromjpeg($img_name);
if(!strcmp("png",$ext))
$src_img=imagecreatefrompng($img_name);
if(!strcmp("gif",$ext))
$src_img=imagecreatefromgif($img_name);
//gets the dimmensions of the image
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);
// next we will calculate the new dimmensions for the thumbnail image
// the next steps will be taken:
// 1. calculate the ratio by dividing the old dimmensions with the new ones
// 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
// and the height will be calculated so the image ratio will not change
// 3. otherwise we will use the height ratio for the image
// as a result, only one of the dimmensions will be from the fixed ones
$ratio1=$old_x/$new_w;
$ratio2=$old_y/$new_h;
if($ratio1>$ratio2) {
$thumb_w=$new_w;
$thumb_h=$old_y/$ratio1;
}
else {
$thumb_h=$new_h;
$thumb_w=$old_x/$ratio2;
}
// we create a new image with the new dimmensions
$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
// resize the big image to the new created one
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
// output the created image to the file. Now we will have the thumbnail into the file named by $filename
if(!strcmp("png",$ext))
imagepng($dst_img,$filename);
else
imagejpeg($dst_img,$filename);
imagegif($dst_img,$filename);
//destroys source and destination images.
imagedestroy($dst_img);
imagedestroy($src_img);
}
// This function reads the extension of the file.
// It is used to determine if the file is an image by checking the extension.
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
// This variable is used as a flag. The value is initialized with 0 (meaning no error found) and it will be changed to 1 if an errro occures. If the error occures the file will not be uploaded.
$errors=0;
// checks if the form has been submitted
if(isset($_POST['Submit']))
{
//reads the name of the file the user submitted for uploading
$image=$_FILES['image']['name'];
// if it is not empty
if ($image)
{
// get the original name of the file from the clients machine
$filename = stripslashes($_FILES['image']['name']);
// get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
// if it is not a known extension, we will suppose it is an error, print an error message and will not upload the file, otherwise we continue
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
echo '<h1>Unknown extension!</h1>';
$errors=1;
}
else
{
// get the size of the image in bytes
// $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which
//the uploaded file was stored on the server
$size=getimagesize($_FILES['image']['tmp_name']);
$sizekb=filesize($_FILES['image']['tmp_name']);
//compare the size with the maxim size we defined and print error if bigger
if ($sizekb > MAX_SIZE*10240)
{
echo '<h1>You have exceeded the size limit!</h1>';
$errors=1;
}
//we will give an unique name, for example the time in unix time format
$image_name=time().'.'.$extension;
//the new name will be containing the full path where will be stored (images folder)
$newname="../images/uploads/".$image_name;
$copied = copy($_FILES['image']['tmp_name'], $newname);
//we verify if the image has been uploaded, and print error instead
if (!$copied)
{
echo '<h1>Copy unsuccessfull!</h1>';
$errors=1;
}
else
{
// the new thumbnail image will be placed in images/thumbs/ folder
$thumb_name='../images/uploads/thumbs/thumb_'.$image_name;
// call the function that will create the thumbnail. The function will get as parameters the image name, the thumbnail name and the width and height desired for the thumbnail
$thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT);
}} }}
Try including imagesavealpha() for PNG's
if(!strcmp("png",$ext))
{
$src_img=imagecreatefrompng($img_name);
imagesavealpha($src_img, true);
}
And read into imagecolortransparent() for GIF files to see if you can find a solution here, messy though.
I wonder whether someone may be able to help me please.
Using some excellent online tutorials I've put together the code below which allows a user to upload image files to a server folder and the filename and other details to a mySQL database.
PHP Script
<?php
//define a maxim size for the uploaded images
//define ("MAX_SIZE","100");
// define the width and height for the thumbnail
// note that theese dimmensions are considered the maximum dimmension and are not fixed,
// because we have to keep the image ratio intact or it will be deformed
define ("WIDTH","150");
define ("HEIGHT","100");
// this is the function that will create the thumbnail image from the uploaded image
// the resize will be done considering the width and height defined, but without deforming the image
function make_thumb($img_name,$filename,$new_w,$new_h)
{
//get image extension.
$ext=getExtension($img_name);
//creates the new image using the appropriate function from gd library
if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))
$src_img=imagecreatefromjpeg($img_name);
if(!strcmp("png",$ext))
$src_img=imagecreatefrompng($img_name);
//gets the dimmensions of the image
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);
// next we will calculate the new dimmensions for the thumbnail image
// the next steps will be taken:
// 1. calculate the ratio by dividing the old dimmensions with the new ones
// 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
// and the height will be calculated so the image ratio will not change
// 3. otherwise we will use the height ratio for the image
// as a result, only one of the dimmensions will be from the fixed ones
$ratio1=$old_x/$new_w;
$ratio2=$old_y/$new_h;
if($ratio1>$ratio2) {
$thumb_w=$new_w;
$thumb_h=$old_y/$ratio1;
}
else {
$thumb_h=$new_h;
$thumb_w=$old_x/$ratio2;
}
// we create a new image with the new dimmensions
$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
// resize the big image to the new created one
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
// output the created image to the file. Now we will have the thumbnail into the file named by $filename
if(!strcmp("png",$ext))
imagepng($dst_img,$filename);
else
imagejpeg($dst_img,$filename);
//destroys source and destination images.
imagedestroy($dst_img);
imagedestroy($src_img);
}
// This function reads the extension of the file.
// It is used to determine if the file is an image by checking the extension.
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$title = ($_POST['title']);
if ($title == '') // if title is not set
$title = '(No Title Provided)';// use (empty title) string
//reads the name of the file the user submitted for uploading
$image=$_FILES['image']['name'];
if ($image)
{
// get the original name of the file from the clients machine
$filename = stripslashes($_FILES['image']['name']);
// get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
// if it is not a known extension, we will suppose it is an error, print an error message
//and will not upload the file, otherwise we continue
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png"))
{
echo '<b> Error! </b> - The image that you attempted to upload is not in the correct format. The file format <b> must </b> be one of the following: <b> "jpg", "jpeg" </b> or <b> "png" </b>. Please try again.';
$errors=1;
}
else
{
// get the size of the image in bytes
// $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which the uploaded file was stored on the server
$size=getimagesize($_FILES['image']['tmp_name']);
$sizekb=filesize($_FILES['image']['tmp_name']);
//compare the size with the maxim size we defined and print error if bigger
if ($sizekb > 1150000)
{
echo '<b> Error! </b> - The file that you are attempting to upload is greater than the prescribed <b> 1MB </b> limit. Please try again.';
$errors=1;
}
//we will give an unique name, for example the time in unix time format
$image_name=time().'.'.$title.'.'.$extension;
//the new name will be containing the full path where will be stored (images folder)
$newname="images/".$image_name;
$copied = copy($_FILES['image']['tmp_name'], $newname);
if (!$copied)
{
//echo '<b> Error! </b> Your file has not been loaded';
//$errors=1;
}
else
{
// the new thumbnail image will be placed in images/thumbs/ folder
$thumb_name='images/thumbs/'.$image_name;
// call the function that will create the thumbnail. The function will get as parameters
//the image name, the thumbnail name and the width and height desired for the thumbnail
$thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT);
} }}
//If no errors registred, print the success message and show the thumbnail image created
if(isset($_POST['Submit']) && !$errors)
{
//echo '<br><b> Success! </b> - Your image has been uploaded</br>';
//echo '<img src="'.$thumb_name.'">';
}
require("mapmyfindsdbinfo.php");
// Gets data from form
$userid = $_POST["userid"];
$locationid = $_POST["locationid"];
$findosgb36lat = $_POST["findosgb36lat"];
$findosgb36lon = $_POST["findosgb36lon"];
$dateoftrip = $_POST["dateoftrip"];
$findcategory = $_POST["findcategory"];
$findname = $_POST["findname"];
$finddescription = $_POST["finddescription"];
$detectorid= $_POST["detectorname"];
$searchheadid = $_POST["searchheadname"];
if( empty($_POST["detectorsettings"]) ) {
$detectorsettings = 'No details provided.'; } else {
$detectorsettings = $_POST["detectorsettings"]; }
if( empty($_POST["pasref"]) ) {
$pasref = 'No PAS Ref. number provided.'; } else {
$pasref = $_POST["pasref"]; }
if( empty($_POST["additionalcomments"]) ) {
$additionalcomments = 'No additional comments made.'; } else {
$additionalcomments = $_POST["additionalcomments"]; }
$makepublic = $_POST["makepublic"];
// Opens a connection to a MySQL server
$conn = mysql_connect ("hostname", $username, $password);
if (!$conn) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $conn);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
$sql = "INSERT INTO finds (userid, locationid, findosgb36lat, findosgb36lon, dateoftrip, findcategory, findname, finddescription, detectorid, searchheadid, detectorsettings, pasref, additionalcomments, makepublic) VALUES ('$userid', '$locationid', '$findosgb36lat', '$findosgb36lon', '$dateoftrip', '$findcategory', '$findname', '$finddescription', '$detectorid', '$searchheadid', '$detectorsettings', '$pasref', '$additionalcomments', '$makepublic')";
$result = mysql_query($sql, $conn);
$findid = mysql_insert_id($conn);
$sql = "INSERT INTO testimages (title, imagename, findid) VALUES ('$title', '$image_name', '$findid')";
$result = mysql_query($sql, $conn);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
HTML Form
<form name="savemyfindstolocation" method="post" enctype="multipart/form-data" action="savemyfindstolocation.php">
<p align="left">Do You Wish To Add Find Images<label></label>
<label></label>
</p>
<div align="left">
<table id="addfiletable" border="1" style="table-layout:auto">
<tr>
<td> </td>
<td><div align="center">Title</div></td>
<td><div align="center">File Location </div></td>
</tr>
<tr>
<td width="20"><input name="select" type="radio" id="select" title=""/></td>
<td width="144"><input name="title" type="text" id="title"/></td>
<td width="314"><input name="image" type="file" id="image" onchange="addRow();" size="40"/></td>
</tr>
</table>
<div align="justify">
<input type="submit" name="deleterow" value="Delete Row" />
</div>
</div>
<input name="submit" type="submit" value="Submit" />
</form>
It all works well, but I'd now like to extend the functionality of allowing a user to upload more than 1 file at a time. I've done a fair bit of research to look at how to upload multiple files, but I'm fairly new to PHP and a little unsure as to which is the best way to progress this.
I just wondered whether someone could perhaps have a look at what I've put together and offer some guidance on how I can change this to upload mutiple files upon the form submit.
Many thanks
PHP
foreach($_FILES['image']['name'] as $i => $name)
{
// now $name holds the original file name
$tmp_name = $_FILES['image']['tmp_name'][$i];
$error = $_FILES['image']['error'][$i];
$size = $_FILES['image']['size'][$i];
$type = $_FILES['image']['type'][$i];
if($error === UPLOAD_ERR_OK)
{
$extension = getExtension($name);
if( ! in_array(strtolower($extension, array('jpg', 'jpeg', 'png') )
{
// Error, invalid extension detected
}
else if ($size > $maxAllowedFileSize /* needs to be defined elsewhere */)
{
// Error, file too large
}
else
{
// No errors
$newFileName = 'foo'; // You'll probably want something unique for each file.
if(move_uploaded_file($tmp_file, $newFileName))
{
// Uploaded file successfully moved to new location
$thumbName = 'thumb_image_name';
$thumb = make_thumb($newFileName, $thumbName, WIDTH, HEIGHT);
}
}
}
}
HTML
<form method="post" enctype="multipart/form-data">
<input name="image[]" type="file" class="image-upload" />
<input name="image[]" type="file" class="image-upload" />
<input name="image[]" type="file" class="image-upload" />
<input name="image[]" type="file" class="image-upload" />
<input name="image[]" type="file" class="image-upload" />
<!-- You need to add more, including a submit button -->
</form>
Note the name of the input elements. The [] at the end cause PHP to create an array and add the items to the array.
If you don't bother paying for it, you may have a look at PHP File Uploader, it's a very nifty and useful tool, that I already used for a couple of sites.
Not that cheap, but definitely worth the cost.
I wonder whether someone could help me please.
Through the use of some online tutorials and 'trial and error' I've put together the script below which allows a user to upload image files.
<?php
//define a maxim size for the uploaded images
//define ("MAX_SIZE","100");
// define the width and height for the thumbnail
// note that theese dimmensions are considered the maximum dimmension and are not fixed,
// because we have to keep the image ratio intact or it will be deformed
define ("WIDTH","150");
define ("HEIGHT","100");
// this is the function that will create the thumbnail image from the uploaded image
// the resize will be done considering the width and height defined, but without deforming the image
function make_thumb($img_name,$filename,$new_w,$new_h)
{
//get image extension.
$ext=getExtension($img_name);
//creates the new image using the appropriate function from gd library
if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))
$src_img=imagecreatefromjpeg($img_name);
if(!strcmp("png",$ext))
$src_img=imagecreatefrompng($img_name);
//gets the dimmensions of the image
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);
// next we will calculate the new dimmensions for the thumbnail image
// the next steps will be taken:
// 1. calculate the ratio by dividing the old dimmensions with the new ones
// 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
// and the height will be calculated so the image ratio will not change
// 3. otherwise we will use the height ratio for the image
// as a result, only one of the dimmensions will be from the fixed ones
$ratio1=$old_x/$new_w;
$ratio2=$old_y/$new_h;
if($ratio1>$ratio2) {
$thumb_w=$new_w;
$thumb_h=$old_y/$ratio1;
}
else {
$thumb_h=$new_h;
$thumb_w=$old_x/$ratio2;
}
// we create a new image with the new dimmensions
$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
// resize the big image to the new created one
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
// output the created image to the file. Now we will have the thumbnail into the file named by $filename
if(!strcmp("png",$ext))
imagepng($dst_img,$filename);
else
imagejpeg($dst_img,$filename);
//destroys source and destination images.
imagedestroy($dst_img);
imagedestroy($src_img);
}
// This function reads the extension of the file.
// It is used to determine if the file is an image by checking the extension.
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
// This variable is used as a flag. The value is initialized with 0 (meaning no error found)
//and it will be changed to 1 if an error occurs. If the error occures the file will not be uploaded.
$errors=0;
// checks if the form has been submitted
if(isset($_POST['Submit']))
{
// cleaning title field
$title = 'title';
if ($title == '') // if title is not set
$title = '(No Title Provided)';// use (empty title) string
//reads the name of the file the user submitted for uploading
$image=$_FILES['image']['name'];
// if it is not empty
if ($image)
{
// get the original name of the file from the clients machine
$filename = stripslashes($_FILES['image']['name']);
// get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
// if it is not a known extension, we will suppose it is an error, print an error message
//and will not upload the file, otherwise we continue
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png"))
{
echo '<b> Error! </b> - The image that you attempted to upload is not in the correct format. The file format <b> must </b> be one of the following: <b> "jpg", "jpeg" </b> or <b> "png" </b>. Please try again.';
$errors=1;
}
else
{
// get the size of the image in bytes
// $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which the uploaded file was stored on the server
$size=getimagesize($_FILES['image']['tmp_name']);
$sizekb=filesize($_FILES['image']['tmp_name']);
//compare the size with the maxim size we defined and print error if bigger
if ($sizekb > 1150000)
{
echo '<b> Error! </b> - The file that you are attempting to upload is greater than the prescribed <b> 1MB </b> limit. Please try again.';
$errors=1;
}
//we will give an unique name, for example the time in unix time format
$image_name=$title.'.'.$extension;
//the new name will be containing the full path where will be stored (images folder)
$newname="images/".$image_name;
$copied = copy($_FILES['image']['tmp_name'], $newname);
//we verify if the image has been uploaded, and print error instead
if (!$copied)
{
echo '<b> Error! </b> Your file has not been loaded';
$errors=1;
}
else
{
// the new thumbnail image will be placed in images/thumbs/ folder
$thumb_name='images/thumbs/'.$image_name;
// call the function that will create the thumbnail. The function will get as parameters
//the image name, the thumbnail name and the width and height desired for the thumbnail
$thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT);
}} }}
//If no errors registred, print the success message and show the thumbnail image created
if(isset($_POST['Submit']) && !$errors)
{
echo '<br><b> Success! </b> - Your image has been uploaded</br>';
echo '<img src="'.$thumb_name.'">';
}
?>
<!-- next comes the form, you must set the enctype to "multipart/form-data" and use an input type "file" -->
<form name="newad" method="post" enctype="multipart/form-data" action="">
<table>
<tr><td><input type="text" name="title" ></td></tr>
<tr><td><input type="file" name="image" ></td></tr>
<tr><td><input name="Submit" type="submit" value="Upload image"></td></tr>
</table>
</form>
I appreciate that this may be a real beginners question, but I'm having problems in saving the 'Title' provided by the user as a form of identifying the image file. If the user doesn't provide a 'Title', the words '(No Title Provided)' are saved as the filename, and I can get this to work correctly, but if I complete the 'Title' text field, the value isn't pulled and inserted as the filename.
I know that the answer lies within this piece of code:
$title = 'title';
if ($title == '') // if title is not set
$title = '(No Title Provided)';// use (empty title) string
But I've tried all manner of ways to try and overcome this without any luck. I just wondered whether someone could perhaps take a look at this please and let me know where I've gone wrong.
Many thanks and kind regards.
You need to grab the information from the text field:
$title = $_POST['title'];
It may be better that you use empty() for checking if the field has been left empty:
if (empty($title))
$title = "(No Title Provided)";
Thanks to #ThatOtherPerson, I realised that I was not capturing the 'Title' value. The solution is
$title = ($_POST['title']);
if ($title == '') // if title is not set
$title = '(No Title Provided)';// use (empty title) string