cropping and ajax uploading of image - php

I want to upload and crop an image via ajax.
Please suggest how I can do this.

To upload an image you will need javascript process handling the upload , there are plenty plugins to do it if you are using jquery library.
To handle uploading process you will need php script. You are sending request to php script from ajax and it does the upload .
To crop image you need a crop tool or crop script here is a cool one http://www.webresourcesdepot.com/jquery-image-crop-plugin-jcrop/
After you handled cropped image you need to execute uploading process (php) by jquery uploader plugin , or another jquery or javascript ajax code.

Here is the code Jquery + PHP [Cake PHP]
View file upload.ctp
<script type="text/javascript" src="http://demos.9lessons.info/ajaximageupload/scripts/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#photoimg').on('change', function(){
$("#preview").html('');
$("#preview").html('<img src="/images/ajax-loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm({target: '#preview',success: showResponse}).submit();
});
});
</script>
<form id="imageform" method="post" enctype="multipart/form-data" action='/media/upload'>
Upload image <input type="file" name="photoimg" id="photoimg" />
</form>
<div id='preview'></div>
create a function with name upload in Media controller
function upload(){
$this->layout = '';
$session_id='1'; // User session id
$path = "images/media/images/original/";
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
//pr($_FILES);die;
//if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name)) {
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats)){
if($size<(1024*1024)) { // Image size max 1 MB
$txt=str_replace(" ","_",$txt);
$actual_image_name = $txt."_".time().".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
App::import('Vendor', 'resize');
if(move_uploaded_file($tmp, $path.$actual_image_name)) { //Code for image resize
//mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
// save this to DB into Temp Selection table set USer wise and Capsule or individual Board wise
echo "<img src='/images/media/images/".$actual_image_name."' class='preview'><br/><a href='javascript:void(0);' id='upload_submit'>Submit</a>";
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file fo`enter code here`rmat..";
}
else
echo "Please select image..!";
exit;
}
}

Related

Copy() function getting error in upload image with php code

I'm having an unsolvable problem with uploading images to the server using php code. The code below is the file that uploads my images to the folder in the hosting, and saves the path to the database. I am using apache2 and php 7.4 with mysql. When I select the image to upload to the hosting directory, the
copy($_FILES['cons_image']['tmp_name'], $consname);
do not copy the file to the directory on the hosting, and will lead to an error in this function.
if (!$copied) {
echo '<h1>Copy unsuccessful!</h1>';
$errors = 1;
}
I tried everything to solve the problem, and people said that I installed the missing php_gd library, but when I checked the php.ini file I already installed GD, used the phpinfo.php file to check the library. GD, everything is on. But when I check the php.ini file in the paragraph
[gd]
; Tell the jpeg decode to ignore warnings and try to create
; a gd image. The warning will then be displayed as notices ; disabled by
default ; http://php.net/gd.jpeg-ignore-warning
;gd.jpeg_ignore_warning = 1
I don't see it having extension=gd line like in xampp on local machine. Can you help me check why the copy() function doesn't copy the images to the folder on my hosting. It still writes the path to the database but cannot copy the images to the hosting folder. I have included my code below hope anyone can help!
<?php
set_time_limit(0);
include './controllers/config.php';
//define a maxim size for the uploaded images
define("MAX_SIZE", "500");
// define the width and height for the thumbnail
// note that these dimensions are considered the maximum dimension and are not fixed,
// because we have to keep the image ratio intact or it will be deformed
define("WIDTH", "187"); //set here the width you want your thumbnail to be
define("HEIGHT", "105"); //set here the height you want your thumbnail to be.
// 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 dimensions of the image
$old_x = imageSX($src_img);
$old_y = imageSY($src_img);
// next we will calculate the new dimensions for the thumbnail image
// the next steps will be taken:
// 1. calculate the ratio by dividing the old dimensions 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 dimensions 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 dimensions
$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);
if (!strcmp("gif", $ext))
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 error occurs. If the error occurs the file will not be uploaded.
$errors = 0;
// checks if the form has been submitted
$error_message = "";
$sucess_message = "";
if (isset($_POST['Submit'])) {
//reads the name of the file the user submitted for uploading
$image = $_FILES['cons_image']['name'];
$code_img = $_POST['code'];
//// check code input
if (empty($code_img)) {
$error_message = "Hãy điền mã cho hình ảnh, không được trùng mã của nhau!";
} else {
$checkDup = "SELECT count(*) FROM uploads WHERE codes = :codes";
$dupStmt = $sqlCon->prepare($checkDup);
$dupStmt->bindValue(':codes', $code_img);
$dupStmt->execute();
$counts = $dupStmt->fetchColumn();
if ($counts > 0) {
$error_message = "Mã đã tồn tại, hãy chọn mã khác!";
} else {
// if it is not empty
if ($image) {
// get the original name of the file from the clients machine
$filename = stripslashes($_FILES['cons_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")) {
$error_message = "Tệp không rõ! chỉ tải lên duy nhất tệp .gif, .jpg hoặc .png !";
$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['cons_image']['tmp_name']);
$sizekb = filesize($_FILES['cons_image']['tmp_name']);
//compare the size with the maxim size we defined and print error if bigger
if ($sizekb > MAX_SIZE * 56024) {
$error_message = "Dung lượng giới hạn 5MB cho mỗi tệp!";
$errors = 1;
}
$rand = rand(0, 1000);
//we will give an unique name, for example a random number
$image_name = $rand . '.' . $extension;
//the new name will be containing the full path where will be stored (images folder)
$consname = "thumb/" . $image_name; //change the image/ section to where you would like the original image to be stored
$consname2 = "thumb/thumbs/" . $image_name; //change the image/thumb to where you would like to store the new created thumb nail of the image
$copied = copy($_FILES['cons_image']['tmp_name'], $consname);
$copied = copy($_FILES['cons_image']['tmp_name'], $consname2);
$sql = "INSERT INTO uploads(thumb, small_thumb, codes) VALUE(:thumb, :images, :codes) ";
$statement = $sqlCon->prepare($sql);
$statement->bindValue(':thumb', $consname2);
$statement->bindValue(':images', $consname);
$statement->bindValue(':codes', $code_img);
$count = $statement->rowCount();
$statement->execute();
$statement->closeCursor();
$sucess_message = "Tải lên hình ảnh thành công!";
//we verify if the image has been uploaded, and print error instead
if (!$copied) {
echo '<h1>Copy unsuccessful!</h1>';
$errors = 1;
} else {
// the new thumbnail image will be placed in images/thumbs/ folder
$ori_image = $consname;
$thumb_name = $consname2;
// 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($consname, $thumb_name, WIDTH, HEIGHT);
}
}
}
}
}
}
//If no errors registered, print the success message and how the thumbnail image created
//if (isset($_POST['Submit']) && !$errors) {
// $error_message = "Tải lên hình ảnh thành công!";
//}
//echo "<form name=\"newad\" method=\"post\" enctype=\"multipart/form-data\" action=\"\">";
//echo "<input type=\"file\" name=\"cons_image\" >";
//echo "<input name=\"Submit\" type=\"submit\" id=\"image1\" value=\"Upload image\" />";
//echo "</form>";
// lay tat ca hinh anh len trang
$selectImg = "SELECT * FROM uploads ORDER BY id DESC";
$stmtImg = $sqlCon->prepare($selectImg);
$stmtImg->execute();
$imgList = $stmtImg->fetchAll();
?>
<html>
<head>
<meta charset="UTF-8">
<title>Thiên Long Huyết Tử</title>
<link rel="icon" type="image/png" href="imgs/favicon.ico"/>
<link rel="stylesheet" href="ht-admin/css/main.min.css">
<link href="http://tl-huyettu.us/css/aos.css" rel="stylesheet">
<script src="http://tl-huyettu.us/js/aos.js"></script>
<link href="http://tl-huyettu.us/ht-admin/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="http://tl-huyettu.us/ht-admin/js/bootstrap.min.js"></script>
<script src="http://tl-huyettu.us/ht-admin/js/jquery-1.11.1.min.js"></script>
</head>
<body style="background-color: #2b3035;">
<?php include './ht-admin/pages/NarvigationBar.php'; ?>
<!-- nav bar -->
<!-- end nav bar --->
<?php include './ht-admin/pages/verticleBar.php'; ?>
<div class="form-upload">
<form name="newad" method="post" enctype="multipart/form-data" action="">
<span><?php echo $error_message; ?></span>
<h5><?php echo $sucess_message; ?></h5>
<br><br>
<lable>Code</lable>
<input class="code" name="code" type="text" placeholder="Hãy tạo mã cho hình ảnh, không được trùng nhau..."><br>
<div class="file-image">
<lable>Hình ảnh</lable>
<input type="file" name="cons_image">
</div>
<input class="button-s" type="submit" name="Submit" id="image1" value="Upload">
<div class="thumbnails">
<label>Thumbnails</label>
<img src="<?php echo $thumb_name; ?>" width="150" height="70" /><br>
<label>Original Image</label>
<img src="<?php echo $ori_image; ?>" width="350" height="175" />
</div>
</form>
<div class="image-panel-list">
<table>
<tbody class="body-image-list" >
<?php foreach ($imgList as $lits): ?>
<tr>
<td><img src="<?php echo $lits['thumb'] ?>" width="150" height="70" /></td>
<td class="td-code-list" ><?php echo $lits['codes'] ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
<!-- tabs image script -->
</body>
</html>

Upload image and preview on div without refresh - PHP / AJAX

I know how upload an image by a form in php. This is my php-code:
<?php
include('include/db.inc.php');
if(!isset($_SESSION))
{
session_start();
}
if(isset($_SESSION['username']))
{
$username = $_SESSION['username'];
$valid_exts = array('jpeg', 'jpg', 'png', 'gif');
$max_size = 200 * 1024;
$path = "../php/data/users/".$username."/";
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
if(!empty($_FILES['image']))
{
$ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
if(in_array($ext, $valid_exts) && $_FILES['image']['size'] < $max_size)
{
$path = $path . 'profile.jpg';
if (move_uploaded_file($_FILES['image']['tmp_name'], $path))
{
$sql = 'UPDATE users SET img_src = "profile.jpg" WHERE username_crypt = "'.$username.'"';
$result = mysql_query($sql) or die("Query error: ".mysql_error());
echo("Success");
}
}
else
{
echo ("InvalidFile");
}
}
else
{
echo ("FileNotUploaded");
}
}
else
{
echo ("BadRequest");
}
}
?>
After the upload, I take the uploaded image by php and the upload works.
But my question is: I have a div in HTML page where there's already an image selected by php. I would upload the new image and replace this without refresh of the page. I would upload the image and after the upload I would see the new image change the previous. I don't know how I could do that. I don't know how I can use AJAX in this context. I would obviously control the errors that php makes during the upload.
I would only click on a button that chooses the image, upload that image and then change the image div with the new uploaded picture without any refresh.
Thank you :D
You could take a look at jQuery File Upload: http://blueimp.github.io/jQuery-File-Upload/
Indeed, you need to use AJAX.
You can use this code below:
<script>
$.ajax({
type: "POST",
url: "YOUR-PHP-URL",
data: YOUR-DATA,
success: function(data){
$('YOUR-DIV').HTML(HERE-YOUR-NEW-IMAGE);
},
error: function(data){
Do-SOMETHING-IF-YOU-WANT
}
})
</script>
Your PHP looks oke, after succes you need to echo the path of the image. The 'data' var in success would be the path that you echo'd you now only need to replace the old image using jQuery. I'm not sure if you can do that only with .HTML() but i think this would work.

Resize and rename PNG, JPG or GIF file with PHP

is there any way, using PHP, that you can resize an image sent from a HTML form's WIDTH (Only PNG, JPG and GIF) to a max value of let's say 500px (so if the file is 350px wide there isn't any stretching), and rename it to a random 15 character name (e.g. "e19gy675jo5el7g.png") and save it to the image/ directory?
I have some code already but it doesn't resize the file and allows all file types to be uploaded (it only renames the file to a random name). I don't want to use the accept="image/*" HTML code in the form so if you could help me find a PHP solution that would be great.
Here's my PHP code...
<?php
function findexts ($filename)
{
$filename = strtolower($filename) ;
$exts = split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
$ext = findexts ($_FILES['uploaded']['name']) ;
$ran = rand () ;
$ran2 = $ran.".";
$target = "image/";
$target = $target . $ran2.$ext;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file has been uploaded as ".$ran2.$ext;
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
?>
And here's my HTML
<html>
<body>
<form enctype="multipart/form-data" action="upload.php" method="post">
<div>
<input name="uploaded" type="file" />
</div>
<br>
<button type="submit">Upload</button>
</form>
</body>
</html>
Sorry for the complicated question, I'm just quite new with PHP :-)
Thanks in advance :-)
I don't know the whole code but you can do it by GD library of PHP.Use
getimagesize($filename)
TO get the image details and check the width using it.If width is less than 500 then do not resize.
Link that may help you: http://forums.phpfreaks.com/topic/210603-uploaded-image-change-width-and-height/

PHP & JQUERY + how to let Jquery know when a file upload has completed

I have a script working to upload images without refreshing the page using jquery.form.js
Below is the PHP file that it kicks off the processes the file and when finished PHP creates an tag to show the image.
I now need a method to let JQUERY know the PHP file processing has completed. Is there a good way to connect these two?
I thought I could write something hidden to the page and have JQUERY look for this but I'm not sure if this is a B-Grade solution.
Any ideas? I can explain better if needed. thx
<?php
$type = $_POST['mimetype'];
$xhr = $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
foreach($_FILES as $file) {
$filename = $file['name'];
$filesize = $file['size'];
$filetmp = $file['tmp_name'];
}
// Script Variables
$errors=0;
$notAllowedFileType=0;
$exceededMaxFileSize=0;
$maxsize='10485760'; // 10MB Maximum Upload
$folder = 'images/';
$configWidth = 500;
$newFileName = 'success_story'.time().'.jpg';
// Process if No Errors
if(!$errors) {
// Variables
$uploadedFile = $filetmp;
$filename = basename( $filename);
$extension = strtolower(getExtension($filename));
// Convert the Specific Type of File into an Image
if($extension=='jpg' || $extension=='jpeg' ) {
$uploadedfile = $fullfilepath;
$src = imagecreatefromjpeg($uploadedFile);
}elseif($extension=='png') {
$uploadedfile = $fullfilepath;
$src = imagecreatefrompng($uploadedFile);
}else{
$uploadedfile = $fullfilepath;
$src = imagecreatefromgif($uploadedFile);
}
// Configure Width & Height
list($origWidth, $origHeight) = getimagesize($uploadedFile);
$configHeight = ($origHeight/$origWidth)* $configWidth;
// Create Empty File
$tmp = imagecreatetruecolor($configWidth, $configHeight);
imagecopyresampled($tmp, $src, 0,0,0,0,$configWidth,$configHeight,$origWidth,$origHeight);
imagejpeg($tmp, $_SERVER['DOCUMENT_ROOT'].$folder.$newFileName,90);
echo "<img src=".$folder.$newFileName." id=\"cropMeNowImage\">";
}
// Get Extension from Uploaded File
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) {return "";}
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script>
(function() {
$(document).on('change','img#cropMeNowImage', function() {
alert('Ready to Crop');
});
})();
</script>
You need to use a callback function. Something like:
$(document).on('change','img#cropMeNowImage', function() {
$.post(url, {
vars_to_server : vars
}, function(process_done){
if (process_done)
alert("ready");
})
});
php must echo something recognizable by jquery in the var process_done
Instead:
echo "<img src=".$folder.$newFileName." id=\"cropMeNowImage\">";
you can echo 1 for success
This is the idea. It's totally possible. Specially for the common task of upload files via AJAX...
I recommend you: 5 Ways to Make Ajax Calls with jQuery
Take a look to http://github.com/valums/file-uploader I always use it to upload files.

Upload Multiple Files In PHP

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.

Categories