Upload Multiple Files In PHP - 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.

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>

how to upload multiple image in php pdo [duplicate]

This question already has an answer here:
How to upload multiple image with rename in php mysql?
(1 answer)
Closed 1 year ago.
I wanted to upload multiple pictures at once using PHP but I am new to PHP so I don't understand how to do it. I want to upload a lot of pictures for one model. Like the picture below:
Here is my PHP code:
<?php
include_once('inc/header.php');
if (isset($_REQUEST['add'])) {
try {
$name = $_REQUEST['name'];
$category = $_REQUEST['category'];
$age = $_REQUEST['txt_age'];
$height = $_REQUEST['height'];
$haircolor = $_REQUEST['haircolor'];
$eyecolor = $_REQUEST['eyecolor'];
$bust = $_REQUEST['bust'];
$waist = $_REQUEST['waist'];
$about = $_REQUEST['about'];
$image_file = $_FILES["image"]["name"];
$type = $_FILES["image"]["type"]; //file name "txt_file"
$size = $_FILES["image"]["size"];
$temp = $_FILES["image"]["tmp_name"];
$path="../img/model_images/".$image_file; //set upload folder path
if (empty($name)) {
$errorMsg="Please Enter Name";
} elseif (empty($image_file)) {
$errorMsg="Please Select Image";
} elseif ($type=="image/jpg" || $type=='image/jpeg' || $type=='image/png' || $type=='image/gif') { //check file extension
if (!file_exists($path)) { //check file not exist in your upload folder path
if ($size < 5000000) { //check file size 5MB
move_uploaded_file($temp, "../img/model_images/" .$image_file); //move upload file temperory directory to your upload folder
} else {
$errorMsg="Your File To large Please Upload 5MB Size"; //error message file size not large than 5MB
}
} else {
$errorMsg="File Already Exists...Check Upload Folder"; //error message file not exists your upload folder path
}
} else {
$errorMsg="Upload JPG , JPEG , PNG & GIF File Formate.....CHECK FILE EXTENSION"; //error message file extension
}
if (!isset($errorMsg)) {
$insert_stmt=$connect->prepare('INSERT INTO tbl_model(model_name,model_category,model_image,model_age,model_height,model_haircolor,model_eyecolor,model_bust,model_waist,model_description) VALUES(:name,:category,:image,:txt_age,:height,:haircolor,:eyecolor,:bust,:waist,:about)'); //sql insert query
$insert_stmt->bindParam(':name', $name);
$insert_stmt->bindParam(':category', $category);
$insert_stmt->bindParam(':image', $image_file);
$insert_stmt->bindParam(':txt_age', $age);
$insert_stmt->bindParam(':height', $height);
$insert_stmt->bindParam(':haircolor', $haircolor);
$insert_stmt->bindParam(':eyecolor', $eyecolor);
$insert_stmt->bindParam(':bust', $bust);
$insert_stmt->bindParam(':waist', $waist);
$insert_stmt->bindParam(':about', $about);
if ($insert_stmt->execute()) {
echo $insertMsg="Model Added Successfully!"; //execute query success message
}
} else {
echo $errorMsg;
}
} catch (PDOException $e) {
echo $e->getMessage();
}
}
?>
But with this code I can only upload one picture but I want to upload many pictures.
This is my html code
<div class="form-group col-12">
<label for="slideImages" class="col-form-label">Model Image</label>
<input type="file" name="image" class="dropify" multiple>
</div>
In html you miss '[]' after name as you have to send array when you upload images and also make sure you write enctype in form tag as shown below
The form tag must contain the following attributes.
method="post"
enctype="multipart/form-data"
The input tag must contain type="file[]" and multiple attributes.
<form action="/action_page_binary.asp" method="post" enctype="multipart/form-data">
<div class="form-group col-12">
<label for="slideImages" class="col-form-label">Model Image</label>
<input type="file" name="image[]" class="dropify" multiple>
</div>
</form>
after this just you have to write for loop or foreach loop in php file as shown below in your code you use single column to store multiple image so apply this loop after you $about
if (isset($_REQUEST['add'])) {
try {
$name = $_REQUEST['name'];
$category = $_REQUEST['category'];
$age = $_REQUEST['txt_age'];
$height = $_REQUEST['height'];
$haircolor = $_REQUEST['haircolor'];
$eyecolor = $_REQUEST['eyecolor'];
$bust = $_REQUEST['bust'];
$waist = $_REQUEST['waist'];
$about = $_REQUEST['about'];
//$path="../img/model_images/".$image_file; //set upload folder path
$path = '';
if (empty($name)) {
$errorMsg="Please Enter Name";
exit;
}
foreach($_FILES["image"]["name"] as $key => $value){
$image_file = implode(',', $_FILES["image"]["name"]);
$image_name = $_FILES["image"]["name"][$key];
$type = $_FILES["image"]["type"][$key]; //file name "txt_file"
$size = $_FILES["image"]["size"][$key];
$temp = $_FILES["image"]["tmp_name"][$key];
if (empty($image_file)) {
$errorMsg="Please Select Image";
exit;
} else if (
($type=="image/jpg" ||
$type=='image/jpeg' ||
$type=='image/png' ||
$type=='image/gif')
) { //check file extension
if (!file_exists($path)) { //check file not exist in your upload folder path
if ($size < 5000000) { //check file size 5MB
move_uploaded_file($temp, "images/" .$image_name); //move upload file temperory directory to your upload folder
} else {
$errorMsg="Your File To large Please Upload 5MB Size"; //error message file size not large than 5MB
exit;
}
} else {
$errorMsg="File Already Exists...Check Upload Folder"; //error message file not exists your upload folder path
exit;
}
} else {
$errorMsg="Upload JPG , JPEG , PNG & GIF File Formate.....CHECK FILE EXTENSION"; //error message file extension
exit;
}
}
echo $name.$category.$age.$height.$haircolor.$eyecolor.$bust.$waist.$about.$image_file;
exit;
after this just bind above $image_file in your query
when you want to fetch display image use explode
$explode_images = explode(",", $images_file);
its gives you array then use foreach loop and key to access image name url or whatever you store in that column.
Hope this help .
if you need explanation of implode and explode check this out Implode Explode

Link Parent Record With Child Image Files

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.

Upload Image Files

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

Cannot upload .mpg files

I've built a rather straightforward file uploader in PHP. So far I've had no troubles uploading images and zip files. However, I can't seem to upload .mpg's. Whenever I try then it after hanging for a moment the page seems like it didn't try to upload anything at all. For example: this
// This is also manually set in php.ini
ini_set("upload_max_filesize", "524288000");
...
print_r($_FILES);
print_r($_POST); // I'm sending along one variable in addition to the file
returns nothing but empty arrays. For completeness, here's the front-end
<form action="uploadVideo.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="524288000"/>
<input type="hidden" name="extravar" value="value" />
<p>
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /><br />
<i>Accepted formats: .mp4, .3gp, .wmv, .mpeg and .mpg. Cannot exceed 500MB.</i>
</p>
<p>Description:</p>
<textarea name="description" rows="4" cols="40"></textarea>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>
The file I am testing with is only 33MB and I tested a .wmv of similar size and it uploaded just fine.
Edit: Entire PHP file listed below
<?php
// Ensure that the user can upload up to the maximum size
ini_set("upload_max_filesize", "524288000");
ini_set("post_max_size", "524288000");
print_r($_POST);
print_r($_FILES);
if(!$link = mysql_connect($SERVER_LOCATION, $DB_USER, $DB_PASS)) die("Error connecting to server.");
mysql_select_db($DB_NAME);
$eventID = $_POST['event'];
// Select the event this is associated with
$query = "SELECT eventName FROM event WHERE eventID = $eventID";
if(!$res = mysql_query($query, $link)) die("Error communicating with database.");
$path = mysql_fetch_row($res);
$path = "media/$path[0]";
// If this event doesn't have a media folder, make one
if(!file_exists($path)) {
mkdir($path);
}
// If this event doesn't have a GIS subfolder, make one
$path = "$path/videos";
if(!file_exists($path)) {
mkdir($path);
}
// Generate todays date and a random number for the new filename
$today = getdate();
$seed = $today['seconds'] * $today['minutes'];
srand($seed);
$random = rand(0, 999);
$today = $today['mon']."-".$today['mday']."-".$today['year'];
$fileType = $_FILES["file"]["type"];
$fileExtension = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
$isMP4 = ($fileType == "video/mp4" && $fileExtension == "mp4");
$isWMV = ($fileType == "video/x-ms-wmv" && $fileExtension == "wmv");
$isMPG = ($fileType == "video/mpeg" && ($fileExtension == "mpeg" || $fileExtension == "mpg"));
$is3GP = ($fileType == "video/3gp" && $fileExtension == "3gp");
$sizeIsOK = ($_FILES["file"]["size"] < 524288000);
if( ($isMP4 || $isWMV || $isMPG || $is3GP) && $sizeIsOK ) {
if($_FILES["file"]["error"] > 0) {
echo "<p>There was a problem with your file. Please check that you submitted a valid .zip or .mxd file.</p>";
echo "<p>If this error continues, contact a system administrator.</p>";
die();
} else {
// Ensure that the file get's a unique name
$filename = $today . "-" . $random . "." . $fileExtension;
while(file_exists("$path/$filename")) {
$random = rand(0, 999);
$filename = $today . "-" . $random . "." . $fileExtension;
}
move_uploaded_file($_FILES["file"]["tmp_name"], "$path/$filename");
$description = $_POST['description'];
$query = "INSERT INTO media (eventID,FileName,File,filetype,Description) VALUES ($eventID,'$filename','$path','video','$description')";
if(!$res = mysql_query($query, $link))
echo "<p>Error storing file description. Please contact a system administrator.</p>";
else {
echo "<h3>File: <i>".$_FILES["file"]["name"]."</i></h3>";
if(strlen($description) > 0) {
echo "<h3>Description: <i>".$description."</i></h3>";
}
echo "<p><strong>Upload Complete</strong></p>";
}
echo "<button onclick=\"setTimeout(history.go(-1), '1000000')\">Go Back</button>";
}
} else {
echo "<p>There was a problem with your file. Please check that you submitted a valid .zip or .mxd file.</p>";
echo "<p>If this error continues, contact a system administrator.</p>";
}
?>
You cannot adjust the file upload limits using ini_set() from within the script that the uploads go to - the script does not get executed until after the upload is completed, so the ini_set() overrides cannot take place. The default parameters in PHP will be in place with the lower limit, and will kill the upload if it exceeds the system upload_max_filesize.
You need to override at the .ini level in PHP, or via a php_value directive in a .htaccess file. Those will change PHP's settings as the upload starts.
Ok, the first thing i thougt would be a problem with the filesize but other files with this size are working as you wrote.
But just do get shure it isn't a file size problem:
When you rise the max filesize you hmust also rise the max post size: post_max_size

Categories