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>
Related
How can i resize proportionaly image in php without "squishing" ? I need some solution, i was searching here, but i could't find anything what i need.
What i have:
<?php
if (isset($_SESSION['username'])) {
if (isset($_POST['upload'])) {
$allowed_filetypes = array('.jpg', '.jpeg', '.png', '.gif');
$max_filesize = 10485760;
$upload_path = 'gallery/';
$filename = $_FILES['userfile']['name'];
$ext = substr($filename, strpos($filename, '.'), strlen($filename) - 1);
if (!in_array($ext, $allowed_filetypes)) {
die('The file you attempted to upload is not allowed.');
}
if (filesize($_FILES['userfile']['tmp_name']) > $max_filesize) {
die('The file you attempted to upload is too large.');
}
if (!is_writable($upload_path)) {
die('You cannot upload to the specified directory, please CHMOD it to 777.');
}
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_path.$filename)) {
$q = mysqli_query($connection, "UPDATE users SET avatar='".$_FILES['userfile']['name']."' WHERE username ='".$_SESSION['username']."'");
echo "<font color='#5cb85c'>Браво, успешно си качил/а профилна снимка!</font>";
} else {
echo 'There was an error during the file upload. Please try again.';
}
}
echo ' <form action="images.php" method="post" enctype="multipart/form-data"> ';
echo ' <input type="file" name="userfile"/>';
echo ' <input type="submit" name="upload" value="Качи">';
echo ' </form>';
} else {
echo "<font color='#ec3f8c'>Съжелявам! За да качиш снимка във профила си, <a href='login.php'><font color='#ec3f8c'><b> трябва да се логнеш</b> </font></a></font>";
}
?>
I want to add something like this:Click here
how i call images?
echo '<a href="profiles.php?id='.$rowtwo['id'].'">';
echo"<img src='gallery/".$rowtwo['avatar']."' width='170px' height='217px'/>";
echo'</a>';
I save my image of avatar in DB in users as avatar.
It's much easier to use JS. It also works better because you're letting the client do the slow work of manipulation vs using your finite server resources for that task.
Here's a sample:
//This is the URL to your original image
var linkUrl = "http://www.mywebsite.com/myimage.png";
//This is a div that is necessary to trick JS into letting you manipulate sizing
//Just make sure it exists and is hidden
var img = $('#HiddenDivForImg');
//This is a call to the function
image_GetResizedImage(img, linkUrl);
//This function does the magic
function image_GetResizedImage(img, linkUrl) {
//Set your max height or width dimension (either, not both)
var maxDim = 330;
//Define the equalizer to 1 to avoid errors if incorrect URL is given
var dimEq = 1;
//This determines if the larger dimension is the images height or width.
//Then, it divides that dimension by the maxDim to get a decimal number for size reduction
if (img.height() > maxDim || img.width() > maxDim) {
if (img.height() > img.width()) {
dimEq = maxDim / img.height();
} else {
dimEq = maxDim / img.width();
}
}
var imageOutput = "<a href='" + linkUrl + "' target='_blank'>View Larger</a><br /><a href='" + result +
"' target='_blank'><img src='" + linkUrl + "' style='width: " + img.width() * dimEq
+ "px; height: " + img.height() * dimEq + "px' /></a>";
//This returns a URL for the image with height and width tags of the resized (non-squished) image.
return imageOutput;
}
For image manipulation in PHP you can use Imagemagick.
http://www.imagemagick.org/
It's the scale command you are looking for.
Here I have created a function with your reference link, you can use it like this
Call it
//Resize uploaded image
resize_image($_FILES['userfile'], 100, 200);
//Or if you want to save image with diffrent name
$filename = $upload_path.$_SESSION['username'].'-avatar.jpg';
resize_image($_FILES['userfile'], 100, 200, $newfilename);
//if (move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_path.$filename)) {
$q = mysqli_query($connection, "UPDATE users SET avatar='".$filename."' WHERE username ='".$_SESSION['username']."'");
echo "<font color='#5cb85c'>Браво, успешно си качил/а профилна снимка!</font>";
} else {
echo 'There was an error during the file upload. Please try again.';
}
Function
function resize_image($image_src, $w = 100, $h = 100, $save_as = null) {
// Create image from file
switch(strtolower($image_src['type']))
{
case 'image/jpeg':
$image = imagecreatefromjpeg($image_src['tmp_name']);
break;
case 'image/png':
$image = imagecreatefrompng($image_src['tmp_name']);
break;
case 'image/gif':
$image = imagecreatefromgif($image_src['tmp_name']);
break;
default:
exit('Unsupported type: '.$image_src['type']);
}
// Target dimensions
$max_width = $w;
$max_height = $h;
// Get current dimensions
$old_width = imagesx($image);
$old_height = imagesy($image);
// Calculate the scaling we need to do to fit the image inside our frame
$scale = min($max_width/$old_width, $max_height/$old_height);
// Get the new dimensions
$new_width = ceil($scale*$old_width);
$new_height = ceil($scale*$old_height);
// Create new empty image
$new = imagecreatetruecolor($new_width, $new_height);
// Resize old image into new
imagecopyresampled($new, $image,
0, 0, 0, 0,
$new_width, $new_height, $old_width, $old_height);
if($save_as) {
//Save as new file
imagejpeg($new, $save_as, 90);
}else{
//Overwrite image
imagejpeg($new, $image_src['tmp_name'], 90);
}
// Destroy resources
imagedestroy($image);
imagedestroy($new);
}
I use http://image.intervention.io/. You can scale, cache, store, convert and do various image manipulation tasks.
Very easy to use.
// load the image
$img = Image::make('public/foo.jpg');
// resize the width of the image to 300 pixels and constrain proportions.
$img->resize(300, null, true);
// save file as png with 60% quality
$img->save('public/bar.png', 60);
I have a php upload script which have 2 files to process uploaded image.
the first file contain html form and ajax script. this script work fine for uploading one image and save the image name and image patch to mysql table.
look at the codes:
Upload.php:
<?php
if($loggedin) {
$contents = "
<frame>
<html>
<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
<title>Ajax Upload and Resize with jQuery and PHP - Demo</title>
<script type=\"text/javascript\" src=\"Images/js/jquery-1.10.2.min.js\"></script>
<script type=\"text/javascript\" src=\"Images/js/jquery.form.min.js\"></script>
<script type=\"text/javascript\">
$(document).ready(function() {
var progressbox = $('#progressbox');
var progressbar = $('#progressbar');
var statustxt = $('#statustxt');
var completed = '0%';
var options = {
target: '#output', // target element(s) to be updated with server response
beforeSubmit: beforeSubmit, // pre-submit callback
uploadProgress: OnProgress,
success: afterSuccess, // post-submit callback
resetForm: true // reset the form after successful submit
};
$('#MyUploadForm').submit(function() {
$(this).ajaxSubmit(options);
// return false to prevent standard browser submit and page navigation
return false;
});
//when upload progresses
function OnProgress(event, position, total, percentComplete)
{
//Progress bar
progressbar.width(percentComplete + '%') //update progressbar percent complete
statustxt.html(percentComplete + '%'); //update status text
if(percentComplete>50)
{
statustxt.css('color','#fff'); //change status text to white after 50%
}
}
//after succesful upload
function afterSuccess()
{
$('#submit-btn').show(); //hide submit button
$('#loading-img').hide(); //hide submit button
}
//function to check file size before uploading.
function beforeSubmit(){
//check whether browser fully supports all File API
if (window.File && window.FileReader && window.FileList && window.Blob)
{
if( !$('#imageInput').val()) //check empty input filed
{
$(\"#output\").html(\"Are you kidding me?\");
return false
}
var fsize = $('#imageInput')[0].files[0].size; //get file size
var ftype = $('#imageInput')[0].files[0].type; // get file type
//allow only valid image file types
switch(ftype)
{
case 'image/png': case 'image/gif': case 'image/jpeg': case 'image/pjpeg':
break;
default:
$(\"#output\").html(\"<b>\"+ftype+\"</b> Unsupported file type!\");
return false
}
//Allowed file size is less than 1 MB (1048576)
if(fsize>8388608)
{
$(\"#output\").html(\"<b>\"+bytesToSize(fsize) +\"</b> Too big Image file! <br />Please reduce the size of your photo using an image editor.\");
return false
}
//Progress bar
progressbox.show(); //show progressbar
progressbar.width(completed); //initial value 0% of progressbar
statustxt.html(completed); //set status text
statustxt.css('color','#000'); //initial color of status text
$('#submit-btn').hide(); //hide submit button
$('#loading-img').show(); //hide submit button
$(\"#output\").html(\"\");
}
else
{
//Output error to older unsupported browsers that doesn't support HTML5 File API
$(\"#output\").html(\"Please upgrade your browser, because your current browser lacks some new features we need!\");
return false;
}
}
//function to format bites bit.ly/19yoIPO
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Bytes';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
});
</script>
<link href=\"Images/style/style.css\" rel=\"stylesheet\" type=\"text/css\">
</head>
<body>
<div id=\"upload-wrapper\">
<div align=\"center\">
<h3>Upload your Image</h3>
<span class=\"\">Image Type allowed: Jpeg, Jpg, Png and Gif. | Maximum Size 8 MB</span>
<form action=\"Process.php\" onSubmit=\"return false\" method=\"post\" enctype=\"multipart/form-data\" id=\"MyUploadForm\">
<input name=\"ImageFile\" id=\"imageInput\" type=\"file\" />
<input type=\"submit\" id=\"submit-btn\" value=\"Upload\" />
<img src=\"Images/images/ajax-loader.gif\" id=\"loading-img\" style=\"display:none;\" alt=\"Please Wait\"/>
</form>
<div id=\"progressbox\" style=\"display:none;\"><div id=\"progressbar\"></div ><div id=\"statustxt\">0%</div></div>
<div id=\"output\"></div>
</div>
</div>
</body>
</html>
</frame>
";
}else header("Location: login.php?return=upload.php");
?>
And, this file is for processing the submitted form:
Process.php:
<?php
if(isset($_POST))
{
############ Edit settings ##############
$ThumbSquareSize = 100; //Thumbnail will be 200x200
$BigImageMaxSize = 300; //Image Maximum height or width
$ThumbPrefix = "thumb_"; //Normal thumb Prefix
$DestinationDirectory = '/www/site/Images/uploads/'; //specify upload directory ends with / (slash)
$Quality = 90; //jpeg quality
##########################################
//check if this is an ajax request
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
die();
}
// check $_FILES['ImageFile'] not empty
if(!isset($_FILES['ImageFile']) || !is_uploaded_file($_FILES['ImageFile']['tmp_name']))
{
die('Something wrong with uploaded file, something missing!'); // output error when above checks fail.
}
// Random number will be added after image name
$RandomNumber = rand(0, 9999999999999);
$ImageName = str_replace(' ','-',strtolower($_FILES['ImageFile']['name'])); //get image name
$ImageSize = $_FILES['ImageFile']['size']; // get original image size
$TempSrc = $_FILES['ImageFile']['tmp_name']; // Temp name of image file stored in PHP tmp folder
$ImageType = $_FILES['ImageFile']['type']; //get file type, returns "image/png", image/jpeg, text/plain etc.
//Let's check allowed $ImageType, we use PHP SWITCH statement here
switch(strtolower($ImageType))
{
case 'image/png':
//Create a new image from file
$CreatedImage = imagecreatefrompng($_FILES['ImageFile']['tmp_name']);
break;
case 'image/gif':
$CreatedImage = imagecreatefromgif($_FILES['ImageFile']['tmp_name']);
break;
case 'image/jpeg':
case 'image/pjpeg':
$CreatedImage = imagecreatefromjpeg($_FILES['ImageFile']['tmp_name']);
break;
default:
die('Unsupported File!'); //output error and exit
}
//PHP getimagesize() function returns height/width from image file stored in PHP tmp folder.
//Get first two values from image, width and height.
//list assign svalues to $CurWidth,$CurHeight
list($CurWidth,$CurHeight)=getimagesize($TempSrc);
//Get file extension from Image name, this will be added after random name
$ImageExt = substr($ImageName, strrpos($ImageName, '.'));
$ImageExt = str_replace('.','',$ImageExt);
//remove extension from filename
$ImageName = preg_replace("/\\.[^.\\s]{3,4}$/", "", $ImageName);
//Construct a new name with random number and extension.
$NewImageName = $ImageName.'-'.$RandomNumber.'.'.$ImageExt;
$NewThumbImageName = $ThumbPrefix.$NewImageName;
//set the Destination Image
$thumb_DestRandImageName = $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumbnail name with destination directory
$DestRandImageName = $DestinationDirectory.$NewImageName; // Image with destination directory
//Resize image to Specified Size by calling resizeImage function.
if(resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType))
{
//Create a square Thumbnail right after, this time we are using cropImage() function
if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType))
{
echo 'Error Creating thumbnail';
}
/*
We have succesfully resized and created thumbnail image
We can now output image to user's browser or store information in the database
*/
// Insert info into database table!
$chkquery = mysql_query("SELECT * FROM `ID_Card` WHERE `UserName`='{$ir['username']}'")or die(mysql_error());
if(mysql_num_rows($chkquery) > 0){
while($chkquerys = #mysql_fetch_array($chkquery)){
$answer=$chkquerys['Approved'];
if($answer == 1) {
echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">';
echo '<tr>';
echo '<td align="center"> some text:<br><br> <img src="'.$chkquerys['ImageName'].'" alt="Image"></td>';
echo '</tr>';
echo '</table>';
die();
}if($answer == 0) {
echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">';
echo '<tr>';
echo '<td align="center"> some text:<br><br> <img src="'.$chkquerys['ImagePath'].''.$chkquerys['ImageName'].'" alt="Image"></td>';
echo '</tr>';
echo '</table>';
die();
}
}
} else{
/* DB Connect code goes here... */
mysql_query("INSERT INTO `Images`(Id,`UserName`,`ImageName`,`ThumbName`,`ImagePath`,`Approved`,`Ip`,`Date`)
VALUES (Null,'Null','$NewImageName','$NewThumbImageName','Images/uploads/','0','IP',unix_timestamp())")or die(mysql_error());}
echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">';
echo '<tr>';
echo '<td align="center">Dear '.$ir['username'].', your Image was uploaded successfully. please waiting for review and verify.</td>';
echo '</tr><tr>';
echo '<td align="center"><img src="Images/uploads/'.$NewImageName.'" alt="Resized Image"></td>';
echo '</tr>';
echo '</table>';
}else{
die('Resize Error'); //output error
}
}
// This function will proportionally resize image
function resizeImage($CurWidth,$CurHeight,$MaxSize,$DestFolder,$SrcImage,$Quality,$ImageType)
{
//Check Image size is not 0
if($CurWidth <= 0 || $CurHeight <= 0)
{
return false;
}
//Construct a proportional size of new image
$ImageScale = min($MaxSize/$CurWidth, $MaxSize/$CurHeight);
$NewWidth = ceil($ImageScale*$CurWidth);
$NewHeight = ceil($ImageScale*$CurHeight);
$NewCanves = imagecreatetruecolor($NewWidth, $NewHeight);
// Resize Image
if(imagecopyresampled($NewCanves, $SrcImage,0, 0, 0, 0, $NewWidth, $NewHeight, $CurWidth, $CurHeight))
{
switch(strtolower($ImageType))
{
case 'image/png':
imagepng($NewCanves,$DestFolder);
break;
case 'image/gif':
imagegif($NewCanves,$DestFolder);
break;
case 'image/jpeg':
case 'image/pjpeg':
imagejpeg($NewCanves,$DestFolder,$Quality);
break;
default:
return false;
}
//Destroy image, frees memory
if(is_resource($NewCanves)) {imagedestroy($NewCanves);}
return true;
}
}
//This function corps image to create exact square images, no matter what its original size!
function cropImage($CurWidth,$CurHeight,$iSize,$DestFolder,$SrcImage,$Quality,$ImageType)
{
//Check Image size is not 0
if($CurWidth <= 0 || $CurHeight <= 0)
{
return false;
}
//abeautifulsite.net has excellent article about "Cropping an Image to Make Square bit.ly/1gTwXW9
if($CurWidth>$CurHeight)
{
$y_offset = 0;
$x_offset = ($CurWidth - $CurHeight) / 2;
$square_size = $CurWidth - ($x_offset * 2);
}else{
$x_offset = 0;
$y_offset = ($CurHeight - $CurWidth) / 2;
$square_size = $CurHeight - ($y_offset * 2);
}
$NewCanves = imagecreatetruecolor($iSize, $iSize);
if(imagecopyresampled($NewCanves, $SrcImage,0, 0, $x_offset, $y_offset, $iSize, $iSize, $square_size, $square_size))
{
switch(strtolower($ImageType))
{
case 'image/png':
imagepng($NewCanves,$DestFolder);
break;
case 'image/gif':
imagegif($NewCanves,$DestFolder);
break;
case 'image/jpeg':
case 'image/pjpeg':
imagejpeg($NewCanves,$DestFolder,$Quality);
break;
default:
return false;
}
//Destroy image, frees memory
if(is_resource($NewCanves)) {imagedestroy($NewCanves);}
return true;
}
}
As I said this Script works prefect for one file...
But, how can I change it to work with 3 differents image field? (all fields are required.)
I want to upload 3 images and save all the uploaded image to one row of a table in database.
for example, I want to have these 3 fields in my form:
<label>Image #1:</label><input name="ImageFile1" type="file" >
<label>Image #2:</label><input name="ImageFile2" type="file" >
<label>Image #3:</label><input name="ImageFile3" type="file" >
after submitting the form, proccess.php upload files and save the name of images in one same row.
for example:
mysql_query("INSERT INTO `Images`(Id,`UserName`,`ImageName1`,`ImageName2`,`ImageName3`,`ImagePath`,`Approved`,`Ip`,`Date`)
VALUES (Null,'Null','$ImageName1','$ImageName2','$ImageName3','Images/uploads/','0','IP',unix_timestamp())")or die(mysql_error());}
Is that possible to do?
Thank you :)
Try setting the same name as an array such as:
<label>Image #1:</label><input name="ImageFile[]" type="file" >
<label>Image #2:</label><input name="ImageFile[]" type="file" >
<label>Image #3:</label><input name="ImageFile[]" type="file" >
Then you can loop the images like this (or pretty much like this):
$array = array();
foreach($_FILES['ImageFile'] as $img) {
// $img['name']
// $img['tmp']
// ...
// upload
// $array[] = {{the uploaded image}}
}
So now you can have as much images as you want. Put the result in an array ($array in that case) and just explode (or implode) like this: `explode(',',$array);
If you want a multiple image uploader, add the multiple in the input:
<label>Image #1:</label><input name="ImageFile[]" type="file" multiple="multiple">
This all works in my own codes, I just don't remember explode or implode, multiple="multiple" or multiple or multiple="true". You can Google that, though.
I'm trying to get this image uploading and converting script working correctly.
I had the script uploading any of the valid images and renaming them fine but then I added the conversion code and I can't get it working correctly. I commented out the // imagepng($image); because that caused the success div to fill with �PNG IHDR��G,�} IDATx���i���u'�s�]�%....... I've worked on this for two days looking at a lot of posts on Stack and thought I understood what was needed. If somebody could please look at this and maybe shed some light on my issue I would greatly appreciate it. In the current configuration I receive no errors on the server. Thanks!
PHP
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/include/session.php';
// Detect the file params according to need
$filename = $_FILES["myfile"]["name"];
$filesize = $_FILES["myfile"]["size"];
$tmp_name = $_FILES["myfile"]["tmp_name"];
$custnum = $session->custnum; //Users account number from session
// Valid extensions for Upload
$validExtensions = array('.jpeg', '.jpg', '.gif', '.png');
// Valid size in KB
$max_size = 6000;
// Detect file extension
$extension = strtolower(strrchr($filename, "."));
// Convert filesize in KB
$getFileSize = round($filesize / 1024, 1);
//Make the storage directory
if (!file_exists("maps/accounts/".$custnum)) {
mkdir("maps/accounts/".$custnum, 0777, true);
}
// Location to store the file
$path = str_replace('\/\\', '/', dirname(__FILE__)) . "/maps/accounts/".$custnum;
if( in_array($extension, $validExtensions) ){
if( $getFileSize < $max_size ){
if(is_dir($path)){
//***********Start of image conversion***********
$srcFile = $tmp_name;
list($width_orig, $height_orig, $type) = getimagesize($srcFile);
// Get the aspect ratio
$ratio_orig = $width_orig / $height_orig;
//Set max size
$width = 900;
$height = 600;
// resize to height (orig is portrait)
if ($ratio_orig < 1) {
$width = $height * $ratio_orig;
}
// resize to width (orig is landscape)
else {
$height = $width / $ratio_orig;
}
// Temporarily increase the memory limit to allow for larger images
ini_set('memory_limit', '32M');
switch ($type)
{
case IMAGETYPE_GIF:
$image = imagecreatefromgif($srcFile);
break;
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg($srcFile);
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng($srcFile);
break;
default:
throw new Exception('Unrecognized image type ' . $type);
}
// create a new blank image
$newImage = imagecreatetruecolor($width, $height);
// Copy the old image to the new image
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
imagepng($newImage, $path . '/' . $custnum.'.png');
imagedestroy($image);
imagedestroy($newImage);
//******End of image conversion****************
// Success Message
echo "<div id='success' class='alert alert-success'><strong>Your map image was uploaded!</strong>
<button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button>
</div>";
} else {
trigger_errors("Directory not Found!<br /> $path");
}
} else {
$error_msg = "<strong>Filesize should be less then $max_size KB!</strong><br />Your file is about $getFileSize KB";
trigger_errors($error_msg);
}
} else {
$error_msg = "<strong>File not Supproted for Upload!</strong><br />
Please try with the files that has following extensions: .jpg, .jpeg, .gif, .png";
trigger_errors($error_msg);
}
// Make function that
// generate the Error
function trigger_errors( $error_msg ){
echo "<div class='alert alert-error'>
<button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button>
$error_msg
</div>";
}
?>
Here's my JQuery Ajax script that is iside the fabric.js kitchensink.js that's calling the above php script.
JQuery Ajax
$('#loading').hide();
$(function(){
var $form = $('#myform'),
$result = $('#result');
$('form').on('change','#myfile', function(){
$('#loading').show();
$result.ajaxStart(function(){
});
$form.ajaxForm({
target: $result
}).submit();
$( document ).ajaxComplete(function() {
$('#loading').delay(1500).hide('slow');
if ($('#success').hasClass('alert-success')){
canvas.setBackgroundImage(fullurl , function() {
canvas.renderAll();
});};
});
});
})
Here's my current html that calls the Ajax and php image processor. This html receives the feed back from the php and ajax success or failure to give feedback to the user.
HTML
<div>
<form id="myform" action="image_uploader.php" method="post" enctype="multipart/form-data">
<table align="center">
<tr>
<td width="100"><label>Select File: </label></td>
<td>
<input class="btn shape" type="file" id="myfile" name="myfile">
</td>
</tr>
</table>
</form>
<div id="loading"><img src="fabric/img/loadingbar.gif" width="200" height="15" alt="" border="0"><img src="fabric/img/uploading-text.GIF" width="128" height="19" alt="" border="0"></div>
</div>
<div id="result"></div>
You don't need to call move_uploaded_file actually. In fact, you'll not get the results you want if you do.
// create a new blank image
$newImage = imagecreatetruecolor($width, $height);
// Copy the old image to the new image
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
imagepng($newImage, $path . '/' . $custnum);
imagedestroy($image);
imagedestroy($newImage);
The reason you'll want to do this is that the second argument of imagepng can be a path to save the file. Since you've gone to all the trouble of converting the file, calling move_uploaded_file will move the original file into a png filename. So if I upload a JPEG with your script it would move that JPEG into example.png. In other words, it wouldn't be a PNG, it would still be a JPEG.
The reason it's dumping the way you're written is that, without that path, the function returns the raw image so your browser is trying to interpret that binary data as text and, thus, you get gibberish and random characters.
You are just moving the uploaded file..
So.. Remove this line..
header('Content-Type: image/png');
I've written a code to upload and unzip a zip file of images to a folder. This file is upload2.php, there is also an upload1.php which I use to input the folder name.
I'm trying to add a function wherein the script will also, after unzipping the files and saving them into the target folder, convert them into thumbnails and then ALSO save those thumbnails into another folder.
The script is also INSERTing various data about all the separate files into a mysql database.
Here's the code:
<?php // actual code for upload
$dirname = trim($_POST['dirname']);
$taken = trim($_POST['taken']);
$location = trim($_POST['location']);
$subject = trim($_POST['subject']);
$rooturl = "http://example.com/test";
$dateurl = $dirname.'/';
$mainurl = $rooturl.$dateurl;
require_once 'connect.php';
$sqlselect = "SELECT * from learning2 WHERE location='test2';";
$result = mysql_query($sqlselect) or die(mysql_error());
$thumbwidth = 100;
$thumbheight = 100;
function makeThumbnail($sourcefile, $endfile, $thumbwidth, $thumbheight, $quality) {
ini_set( "memory_limit","192M");
// Takes the sourcefile (path/to/image.jpg) and makes a thumbnail from it
// and places it at endfile (path/to/thumb.jpg).
// Load image and get image size.
if (file_exists($sourcefile)) {
$img = imagecreatefromjpeg($sourcefile);
$width = imagesx( $img );
$height = imagesy( $img );
if ($width > $height) {
$newwidth = $thumbwidth;
$divisor = $width / $thumbwidth;
$newheight = floor( $height / $divisor);
} else {
$newheight = $thumbheight;
$divisor = $height / $thumbheight;
$newwidth = floor( $width / $divisor );
}
// Create a new temporary image.
$tmpimg = imagecreatetruecolor( $newwidth, $newheight );
// Copy and resize old image into new image.
imagecopyresampled( $tmpimg, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height );
// Save thumbnail into a file.
imagejpeg( $tmpimg, $endfile, $quality);
// release the memory
imagedestroy($tmpimg);
imagedestroy($img);
} else {
echo "The file " . $sourcefile . " does not exist";
}
}
function makeDirectory($dirname) { //This function makes both the directory the photos will be unzipped into, and a directory nested within that for the thumbnails of those photos.
mkdir($dirname, 0777);
mkdir($dirname.'/thumbs', 0777);
}
if(isset($_POST['submit'])) {
if (file_exists($dirname) && is_dir($dirname)) { // determines whether or not this particular directory exists
echo "the directory exists and it is called: " . $mainurl;
echo "<br />";
} else {
makeDirectory($dirname);
}
if($_FILES["zip_file"]["name"]) { // pull the name of the zip file from the upload
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$type = $_FILES["zip_file"]["type"];
$name = explode(".", $filename); //format the filename for a variable
$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false; // let user know if the zip file has not been uploaded
if(!$continue) {
$message = "The file you are trying to upload is not a .zip file. Please try again.";
}
$target_path = $dirname."/".$name; // get the $target_path variable to for the move_uploaded_file() function.
if(move_uploaded_file($source, $target_path)) { // this block extracts the zip files and moves them to the $dirname directory
$zip = new ZipArchive();
$x = $zip->open($target_path);
if ($x === true) {
$zip->extractTo($dirname."/");
$images = array();
for ($i=0; $i<$zip->numFiles; $i++) {
$images[] = $zip->getNameIndex($i);
}
$zip->close();
unlink($target_path);
}
$message = "Your .zip file was uploaded and unpacked.";
}
} else {
$message = "There was a problem with the upload. Please try again.";
}
$newdir = scandir($dirname);
foreach ($newdir as $key => $value) {
if ($value!='.' && $value!='..') {
$thumburl = $rooturl.$dateurl.'thumbs/'.$value;
echo 'Key: ' . "$key;" . ' Value: ' . "$value" ."<br />\n";
$sourcefile = $value;
$endfile = 'http://example.com/test/'.$dirname.'/thumbs/'.'$value';
makeThumbnail($sourcefile, $endfile, $thumbwidth, $thumbheight, $quality);
mysql_query("INSERT INTO learning3 (taken, location, subject, rooturl, dateurl, imagename, thumburl) VALUES ('$taken', '$location', '$subject', '$rooturl', '$dateurl', '$value', '$thumburl')");
echo "<br />";
echo '<img src="'.$thumburl.'>< /img>';
echo "$value"." inserted successfully!";
} else {
echo $value." not inserted, thumbnail not created.";
echo $insert_sql . '<BR>' . mysql_error();
}
}
} else { echo 'Please input your data and select a zip file.';
}
echo '<html>';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR...nsitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
if($message) echo "<p>$message</p>";
if($taken) echo "<p>pictures taken on: " . $taken . "</br>";
if($subject) echo "<p>subject: " . $subject . "</br>";
if($location) echo "<p>location: " . $location . "</br>";
if(($rooturl) && ($dateurl)) echo "<p>directory is called: " . $rooturl.$dateurl. "</br>";
?>
<form enctype="multipart/form-data" method="post" action="upload2.php">
<label for="dirname">Directory to use?: </label> <input name="dirname" size="20" type="text" value="<?php echo $dirname; ?>" /><br />
<label for="taken">When was this taken?:</label> <input name="taken" size="20" type="text" value="<?php echo $dirname; ?>" /><br />
<label for="location">Where was this taken?</label> <input name="location" size="20" type="text" /><br />
<label for="subject">subject?</label> <input name="subject" size="20" type="text" /><br />
<!--< />-->
<input type=hidden name="mainurl" value="<?php echo "http://example.com/test/".'$dirname;' ?>" />
<label>Choose a zip file to upload: <input type="file" name="zip_file" /></label>
<br />
<input type=submit name='submit' value="Upload" />
</form>
</body>
</html>
The thing I can't figure out about the script is this: it does not create the thumbnails and put them into the new thumbnail folder, although it does create the correct folders, and the mysql inserts are successful. Rather than the thumbnails being saved, I get the simple error messsage "the file does not exist." The thing is, I know the file does exist, because the earlier part of the script creates it. Can anyone tell me what I'm doing wrong here, or even give me a hint as to where I should be looking?
So, I tested the makeThumbnail() function directly (both with files in the current directory and then with files outside of it) and in both cases, it worked fine. It's kinda hard to know exactly what's going on without being able to fully execute the code, but my guess is that it lies in the call to makeThumbnail(). Is it possible that you're forgetting to prepend the path to $sourcefile before making the call? Is it possible there are white spaces at the beginning or end of $sourcefile? The function works, so it has to be the calling code that's responsible.
Just skimming that code, shouldn't the call be: makeThumbnail($dirname.$sourcefile[...]) instead of makeThumbnail($sourcefile[...]) (or "$dirname/$sourcefile", but you get the point)?
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.