Multiple image upload with PHP - php

I'm trying upload multiple images. Below you can see my code.
Image uploaded massage repenting (exactly the amount of image chosen to upload.)
How can i show "Image uploaded" massage only ones on successful submit?
If i put the message after the loop it will start to show no matter if there is any errors.
This is my PHP code:
<?php
error_reporting(0);
session_start();
include('db.php');
$id = $mysqli->escape_string($_GET['id']);
define ("MAX_SIZE","9000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "gallery/"; //a directory inside
foreach ($_FILES['photos']['name'] as $name => $value)
{
$filename = stripslashes($_FILES['photos']['name'][$name]);
$size=filesize($_FILES['photos']['tmp_name'][$name]);
//get the extension of the file in a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
if(in_array($ext,$valid_formats))
{
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
$newname=$uploaddir.$image_name;
if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname))
{
$mysqli->query("INSERT INTO galleries(image) VALUES('$image_name')");
echo "Image uploaded";
}
else
{
echo '<span class="imgList">You have exceeded the size limit! so moving unsuccessful! </span>';
}
}
else
{
echo '<span class="imgList">You have exceeded the size limit!</span>';
}
}
else
{
echo '<span class="imgList">Unknown extension!</span>';
}
}
}
?>
Any help will be appropriated.

You can implement a counter and when an upload completes successfully you can increment that counter variable then compare it against total number of array items after foreach loop completes. I modified your code for this (haven't checked it but should work).
<?php
error_reporting(0);
session_start();
include('db.php');
$id = $mysqli->escape_string($_GET['id']);
define ("MAX_SIZE","9000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "gallery/"; //a directory inside
$successfulUploads = 0;
foreach ($_FILES['photos']['name'] as $name => $value)
{
$filename = stripslashes($_FILES['photos']['name'][$name]);
$size=filesize($_FILES['photos']['tmp_name'][$name]);
//get the extension of the file in a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
if(in_array($ext,$valid_formats)) {
if ($size < (MAX_SIZE*1024)) {
$image_name=time().$filename;
$newname=$uploaddir.$image_name;
if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname)) {
$mysqli->query("INSERT INTO galleries(image) VALUES('$image_name')");
//echo "Image uploaded";
$successfulUploads = $successfulUploads + 1;
} else {
echo '<span class="imgList">Moving unsuccessful! </span>';
}
} else {
echo '<span class="imgList">You have exceeded the size limit!</span>';
}
} else {
echo '<span class="imgList">Unknown extension!</span>';
}
}
if($successfulUploads === count($_FILES['photos'])){
echo 'UPLOAD SUCCESS!';
} else {
echo 'NOT ALL IMAGES WERE UPLOADED SUCCESSFULLY';
}
}
*If you wanted to get more complex with it you could create another array variable instead of a counter and if the upload fails you could add the file name to the array and then check the length of the array where I'm doing the comparison. If count > 0 then you would know there was an error and you could echo the filenames that failed to upload

Related

Php multiple image upload processing error

In the form and process file below I am trying to upload 3 sizes of multiple images upload and it is uploading 3 size perfectly fine.
But it is uploading the same image on all sizes of the last image selected.
UPDATE
What i have observed that something has to be played with $src i tried below and when i do this images saved black. $src does not accept [$Kv]
foreach($_FILES['file']['tmp_name'] as $src[$Kv]) {
if($extension[$Kv]=="jpg" || $extension[$Kv]=="jpeg" ){
$uploadedfile[$Kv] = $_FILES['file']['tmp_name'][$Kv];
$src[$Kv] = imagecreatefromjpeg($uploadedfile[$Kv]);
}
list($width,$height)=getimagesize($uploadedfile[$Kv]);
////// 1st Size of Image
$newwidth=350;
$newheight=350;
$tmp[$Kv]=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp[$Kv],$src[$Kv],0,0,0,0,$newwidth,$newheight,$width,$height);
}
.
Suppose I selected 3 images to upload.
Image A
Image B
Image C
It is converting and uploading all sizes of all images (3x3) but image shows on all sizes of all images selected is the image of Image C.
Can you please help on this issue that where I am wrong?
Thanks.
form.php
<form action="process.php" method="post" enctype="multipart/form-data">
<div class="col-lg-12 col-md-9 col-sm-12" id="thumb-output">
<div class="m-dropzone dropzone m-dropzone--primary" id="m-dropzone-two">
<h3 class="m-dropzone__msg-title">
Drop files here or click to upload.
</h3>
<input id="files" class="" type="file" name="file[]" multiple>
</div>
</div>
</form>
process.php
$change="";
$abc="";
if(count($_FILES['file']['name']) > 0){
$Kv = 0;
define ("MAX_SIZE","12000");
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$errors=0;
if($_SERVER["REQUEST_METHOD"] == "POST"){
$image =$_FILES["file"]["name"][$Kv];
if ($image) {
foreach($_FILES['file']['name'] as $filename) {
$filename = stripslashes($_FILES['file']['name'][$Kv]);
$extension = getExtension($filename);
$extension = strtolower($extension);
}
foreach($_FILES['file']['size'] as $size) {
$size=filesize($_FILES['file']['tmp_name'][$Kv]);
}
if ($size > MAX_SIZE*1024){
$change='<div class="msgdiv">You have exceeded the size limit!</div> ';
$errors=1;
}
if($extension=="jpg" || $extension=="jpeg" ){
$uploadedfile = $_FILES['file']['tmp_name'][$Kv];
$src = imagecreatefromjpeg($uploadedfile);
}else if($extension=="png"){
$uploadedfile = $_FILES['file']['tmp_name'][$Kv];
$src = imagecreatefrompng($uploadedfile);
}else {
$src = imagecreatefromgif($uploadedfile);
}
//echo $scr;
list($width,$height)=getimagesize($uploadedfile);
////// 1st Size of Image
$newwidth=350;
$newheight=350;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
////// 2nd Size of Image
$newwidths=400;
$newheights=400;
$tmps=imagecreatetruecolor($newwidths,$newheights);
imagecopyresampled($tmps,$src,0,0,0,0,$newwidths,$newheights,$width,$height);
////// 3rd Size of Image
$newwidthsz=92;
$newheightsz=92;
$tmpsz=imagecreatetruecolor($newwidthsz,$newheightsz);
imagecopyresampled($tmpsz,$src,0,0,0,0,$newwidthsz,$newheightsz,$width,$height);
/////////////////////////////////////////////////////
foreach($_FILES['file']['name'] as $name) {
$name = $_FILES["file"]["name"][$Kv];
$ext = end((explode(".", $name))); # extra () to prevent notice
}
$folderPath = "../images/combo2_images";
if (file_exists($folderPath)){
}else{
mkdir("$folderPath");
}
//mkdir($folderPath);
if ($execute == true) {
if ($type == 'm') {
foreach($_FILES['file']['name'] as $filenames) {
$filenames = "../images/combo2_mimages/m".$idz.'_'.$Kv++.'.'.$ext;
imagejpeg($tmps,$filenames,100);
}
//$savefilenames = 'sc1_'.$id.'.'.$ext;
foreach($_FILES['file']['name'] as $filenamesz) {
$filenamesz = "../images/combo2_mimages/small/m".$idz.'_'.$Kv++.'.'.$ext;
imagejpeg($tmpsz,$filenamesz,100);
}
//$savefilenamesz = 'sc1_'.$id.'.'.$ext;
}
$filename = "../images/combo2_images/".$idz.'.'.$ext;
imagejpeg($tmp,$filename,100);
$savefilename = $idz.'.'.$ext;
if ($_FILES['file']['size'] !== 0 && $_FILES['file']['error'] == 0) {
if ($type == 'm') {
$querys = "insert into items_images
(combo_type, combo_id, item_id, filename, status)
values (2, '$idz', '$mitem', '$savefilename', '$status')
";
$executes = $dba->query($querys);
}
$queryu = "update items_combobox2
set filename = '$savefilename'
where id = '$idz'
";
$executeu = $dba->query($queryu);
imagedestroy($src);
imagedestroy($tmp); ////// 1st Size of Image
imagedestroy($tmps); ////// 2nd Size of Image
imagedestroy($tmpsz); ////// 3rd Size of Image
}
}
}
header("location: all/items/");
echo "<script>parent.document.location.href = 'all/items/';</script>";
exit();
}
}
Finally i got i working as i want.
if(count($_FILES['file']['name']) > 0){
define ("MAX_SIZE","12000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$errors=0;
$i=1; // auto increment number
$uploaddir = "../images/combo2_images"; //a directory inside
foreach ($_FILES['file']['name'] as $name => $value) {
$filename = stripslashes($_FILES['file']['name'][$name]);
//get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
echo "\n This is the extension: ",$extension;
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
//print error message
?>
<h4>Unknown extension!</h4>
<?php
$errors=1;
} else {
$size=filesize($_FILES['file']['tmp_name'][$name]);
if ($size > MAX_SIZE*1024) {
?>
<h4>You have exceeded the size limit!</h4>
<?php
$errors=1;
}
if($extension=="jpg" || $extension=="jpeg" && $extension!=="png"){
$uploadedfile = $_FILES['file']['tmp_name'][$name];
$src = imagecreatefromjpeg($uploadedfile);
}else if($extension=="jpg" || $extension=="jpeg" && $extension=="png"){
$uploadedfile = $_FILES['file']['tmp_name'][$name];
$src = imagecreatefromjpeg($uploadedfile);
}else if($extension!=="jpg" || $extension!=="jpeg" && $extension=="png"){
$uploadedfile = $_FILES['file']['tmp_name'][$name];
$src = imagecreatefrompng($uploadedfile);
}
list($width,$height)=getimagesize($uploadedfile);
$newwidth=350;
$newheight=350;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$newwidths=400;
$newheights=400;
$tmps=imagecreatetruecolor($newwidths,$newheights);
imagecopyresampled($tmps,$src,0,0,0,0,$newwidths,$newheights,$width,$height);
$newwidthsz=92;
$newheightsz=92;
$tmpsz=imagecreatetruecolor($newwidthsz,$newheightsz);
imagecopyresampled($tmpsz,$src,0,0,0,0,$newwidthsz,$newheightsz,$width,$height);
//$image_name=($i++).$filename.'.'.$extension;
//$newname="files/".$image_name;
//$copied = copy($_FILES['file']['tmp_name'][$name], $newname);
if ($execute == true) {
if ($type == 'm') {
$filenames = "../images/combo2_mimages/m".$idz.'.'.$extension;
//imagejpeg($tmps,$filenames,100);
$copied1 = copy(imagejpeg($tmps,$filenames,100));
$filenamesz = "../images/combo2_mimages/small/m".$idz.'_'.($i++).'.'.$extension;
//imagejpeg($tmpsz,$filenamesz,100);
$copied2 = copy(imagejpeg($tmpsz,$filenamesz,100));
}
$filename = "../images/combo2_images/".$idz.'.'.$extension;
imagejpeg($tmp,$filename,100);
$savefilename=$idz.'.'.$extension;
if ($type == 'm') {
$querys="insert into items_images
(combo_type, combo_id, item_id, filename, status)
values (2, '$idz', '$mitem', '$savefilename', '$status')
";
$executes=$dba->query($querys);
}
$queryu="update items_combobox2
set filename = '$savefilename'
where id = '$idz'
";
$executeu=$dba->query($queryu);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmps);
imagedestroy($tmpsz);
}
if (!$copied) {
?>
<h4>Copy unsuccessfull!</h4>
<?php
$errors=1;
}
}
}
header("location: all/items/");
echo "<script>parent.document.location.href = 'all/items/';</script>";
exit();
}

need php code to post below 5 images into one field of db separated by br

Please help me
My html code is as follows:
here image_name is getting through echo from another upload query
My upload script code
$path = "uploads/";
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name)){
$ext = getExtension($name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
$time = time();
$ip = $_SERVER['REMOTE_ADDR'];
mysql_query("INSERT INTO uploads(image_name,poster_user,created,cat,status,ip) VALUES('$actual_image_name','$u_id','$time', 'Photos', '1', '$ip')");
echo "<img src='uploads/".$actual_image_name."' class='previewOfimgss'> ";
$allimages_name = "$actual_image_name";
echo "$allimages_name";
}
else
echo "Fail upload folder with read access.";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
It is working quite good and giving result like
and i want images names in on textbox like
$items=$_POST["post_items"];
$final = "";
foreach($items as $item){
$final .= $item."<br>";
}
echo $final
And you can then pass the $final variable to the column.
There is another way to do it.
$items= $_POST["post_items"];
$final = implode("<br>",$items);
It will work only if $items is array.
Ok I've done a working solution for you. This is a kind of prototype of your system. Hope it helps you in what you are building.
fileForm.php (Where you select file to upload.)
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="uploadFile.php" method="post" enctype="multipart/form-data">
<input type="file" name="photoimg[]" multiple="yes">
<input type="submit" name="fileUploader">
</form>
</body>
</html>
uploadFile.php (Where you upload your files as in your question)
<?php
if ($_SERVER["REQUEST_METHOD"]=="POST") {
$path = "uploads/"; // Upload directory
// Return's files extension
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP"); // Valid formats to upload
$fileCount=count($_FILES["photoimg"]["name"]); // Number of files uploaded
$files=array(); // Initilize an empty array to save names
// Loop through all files and upload them
for ($i=0; $i < $fileCount; $i++) {
$name=$_FILES["photoimg"]["name"][$i];
$tmp=$_FILES["photoimg"]["tmp_name"][$i];
$size=$_FILES["photoimg"]["size"][$i];
// If name is not empty
if(!empty($name)){
$ext = getExtension($name); // Get file extension
// If file is valid to upload
if(in_array($ext,$valid_formats)){
If file is less than 1 MB.
if($size<(1024*1024)){
$actual_image_name = time().substr(str_replace(" ", "_", $name), 5); // Final name of image
// If file uploads successfully
if(move_uploaded_file($tmp, $path.$actual_image_name)){
$time=time();
$ip=$_SERVER['REMOTE_ADDR'];
mysql_query("INSERT INTO uploads(image_name,poster_user,created,cat,status,ip) VALUES('$actual_image_name','$u_id','$time', 'Photos', '1', '$ip')"); // Insert into your table
echo "<img src='uploads/$actual_image_name' class='previewOfimgss'> "; // Show the image
$files[$i] = $actual_image_name; // Save file names
}else{
echo "Fail upload folder with read access.";
}
}else{
echo "Image file size max 1 MB";
}
}else{
echo "Invalid file format..";
}
}else{
echo "Please select image..!";
}
}
}
?>
<form action="toSaveFileName.php" method="post">
<?php
for ($i=0; $i < $fileCount; $i++) {
// Generate input fields
echo "<input type='text' name='post_items[]' value='{$files[$i]}'>";
}
?>
<input type="submit">
</form>
toSaveFileName.php (This is what you originally asked for.)
$items=$_POST["post_items"]; // from input fields
$todb=""; // to send to database
if(is_array($items)){
$todb=implode("<br>",$items);
}else{
$todb=$items;
}
echo $todb; // for output
//save to database
Now implementing it to your system is your job. And I hope you should be able to do it on your own.
Don't forget to mark this as answer and vote up.

php upload file issue using array

in my form I'm trying to upload multiple or single file using php. So my html table is look like this :
<tr>
<td width="142"><b>Docs</b>
<td width="142"><input type="file" name="files[]" id="project_docs1" class="docfile" /></td>
<td width="142"><input type="file" name="files[]" id="project_docs2" class="docfile" /></td>
<td width="142"><input type="file" name="files[]" id="project_docs3" class="docfile" /></td>
</td>
Now when I upload only one file it's showing me error message like : Invalid Format but it's should be accept one file. it's not require to must be upload all 3 files. Can you tell me why it's showing this error message called Invalid Format ? If upload all 3 files then it's working fine.
and when I press the upload button without upload any file it's showing me value 1 for $noOfUpload variable. why ?
$valid_formats = array("jpg", "png", "gif", "txt", "bmp");
$max_file_size = 1024*100; //100 kb
$path = "project_docs"; // Upload directory
$error = array(); // load error message
$files_name = array(); // get uploaded file name
foreach ($_FILES['files']['name'] as $key => $name) {
$size = $_FILES['files']['size'][$key]. "<br>";
$noOfUpload = count($name);
if($noOfUpload <= 0){
$error[] = "Upload your document/s<br>";
}elseif(!in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats)){
$error[] = "invalid file formate : $name<br>";
}
//$name = md5(uniqid()) . '-' . htmlspecialchars_decode($name);
$files_name[] = "$name";
}
if(!empty($error)){
foreach ($error as $e) {
echo "<div class='error'>$e</div>";
}
}else{
foreach ($files_name as $fn) {
echo "$fn<br>";
}
}
You help is more appreciate. :)
Try this
if (isset($_FILES))
{
$valid_formats = array("jpg", "png", "gif", "txt", "bmp");
for ($i = 0; $i < count($_FILES['files']['name']); $i++)
{
if (in_array(pathinfo($FILES['files']['name'][$i], PATHINFO_EXTENSION), $valid_formats))
{
$tmp_path = $_FILES['files']['tmp_name'][$i];
if ($tmp_path != "")
{
if (move_uploaded_file($tmp_path, $new_path))
{
//Handle other code here
}
else
{
$error[] = ""; //your error handling
}
}
else
{
$error[] = ""; //your error handling
}
}
else
{
$error[] = "invalid file formate : $name<br>";
}
}
}
Your code is run for whole array either it's blank or not. First, count your array then run your code upto that count.
<tr>
<td width="142"><b>Docs</b>
<td width="142"><input type="file" name="files[]" id="project_docs1" class="docfile" /></td>
</tr>
PHP Code:
$valid_formats = array("jpg", "png", "gif", "txt", "bmp");
$max_file_size = 1024*100; //100 kb
$path = "project_docs"; // Upload directory
$error = array(); // load error message
$files_name = array(); // get uploaded file name
foreach ($_FILES['files']['name'] as $key => $name) {
$size = $_FILES['files']['size'][$key]. "<br>";
$noOfUpload = count($name);
if($noOfUpload <= 0){
$error[] = "Upload your document/s<br>";
}elseif(!in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats)){
$error[] = "invalid file format : $name<br>";
}
//$name = md5(uniqid()) . '-' . htmlspecialchars_decode($name);
$files_name[] = "$name";
}
if(!empty($error)){
foreach ($error as $e) {
echo "<div class='error'>$e</div>";
}
}else{
foreach ($files_name as $fn) {
echo "$fn<br>";
}
}

Yii multiple row insert

I have a problem with this code.. When I post 3 images, the script inserts just last one in database.. How can i solve this?
Here's my code:
<?php
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
$valid_formats = array("jpg", "png", "gif", "bmp");
$max_file_size = 1024*2220; //100 kb
$path = "galerija/"; // Upload directory
$count = 0;
$key = generateRandomString();
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to execute all files
foreach ($_FILES['files']['name'] as $f => $name) {
if ($_FILES['files']['error'][$f] == 4) {
continue; // Skip file if any error found
}
if ($_FILES['files']['error'][$f] == 0) {
if ($_FILES['files']['size'][$f] > $max_file_size) {
$message[] = "Slika $name je pre velika!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "Ekstenzija $name nije valjana!";
continue; // Skip invalid file formats
} else { // No error found! Move uploaded files
if (move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$key.$name)){
$model->naziv = $key.$name;
$model->save();
}
}
}
}
}
?>
I think I should probably put some code after } else { //No error found, but i don't know what :S
You need to create an instance each time like below:
$model=new ModelName();
$model->naziv = $key.$name;
$model->save();

error handling and image type cat get it to work

I been working on this image script for too long now, and I still can't seem to get two things to work - the image type and error handling (if the fields are empty). I have the code for this, but every place I try to add it, it doesn't work.
my code:
$error_message="";
$MaxSize = "600000";
if (isset($_POST['btn_update'])){
function createRandomPassword() {
$chars = "abcde!##%^fghijkmnoABCDEFGHIJKpqrstuvwxyz023456789ABCDEFGHIJKLMNOPQRSTUVWZ!##%^&";
srand((double)microtime()*10000000);
$i = 0;
$pass = '' ;
while ($i <= 19) {
$num = rand() % 60;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
if ($_FILES['aMyUploads0']['size'] > $MaxSize || $_FILES['aMyUploads1']['size'] > $MaxSize || $_FILES['aMyUploads2']['size'] > $MaxSize)
{
$error_message = "ERROR: File too big!";
}
$aMyUploads = array();
$password = createRandomPassword();
foreach($_FILES as $aFile)
{
$newLocation = 'uploads/'.$password .$aFile["name"];
if(0 === $aFile['error'] && (false !== move_uploaded_file($aFile['tmp_name'], $newLocation)))
{
$aMyUploads[] = $newLocation;
}
else
{
$aMyUploads[] = '';
}
}
$error_message="Journal successfully saved.";
$connection = mysql_connect("localhost", "????", "???");
mysql_select_db("????", $connection);
$insert = "INSERT INTO photos (image1, image2, image3) VALUES
(
' ".$aMyUploads[0]." ',
' ".$aMyUploads[1]." ',
' ".$aMyUploads[2]." '
)";
$add_member = mysql_query($insert) or die(mysql_error());
}
code im trying to add with no luck:
//ERROR HANDLING CODE:
if(empty($aMyUploads[0]) || empty($aMyUploads[1]) || empty($aMyUploads[2]))
{
$error_message="Please fill in all fields.";
}
else
{
$error_message="Journal successfully saved.";
//IMAGE TYPE CODE:
$allowed_filetypes = array(".jpg", ".gif", ".jpeg", ".png");
$ext = substr($newLocation, strpos($newLocation,'.'), strlen($newLocation)-1);
if(!in_array($ext,$allowed_filetypes))
{
die('The file you attempted to upload is not allowed.');
}
Try this for checking required fields, inserted before the code that checks the file sizes.
// ERROR HANDLING CODE:
if (empty($_FILES) || empty($_FILES['aMyUploads0']) || empty($_FILES['aMyUploads1']) || empty($_FILES['aMyUploads2']))
{
// Handle error
}
And this for validating file types, inserted into your foreach.
// IMAGE TYPE CODE:
$allowed_filetypes = array("jpg", "gif", "jpeg", "png");
$ext = pathinfo($aFile['name'], PATHINFO_EXTENSION);
if (!in_array($ext, $allowed_filetypes))
{
// Handle error
}

Categories