how can uploaded multi images in this class [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i want to upload multi images in my database just url images the code is work fine but i can upload just one image i need to upload 3 images i have in database table e_img - e_img2 - e_img3 how can upload images url in 3 columns
this my class upload :
<?php
class Upload {
private $allowedExts = array('doc','docx','pdf','txt','jpg','png');
private $maxSize;
private $file;
private $uploadsDirecotry;
private $fileUrl;
private $filenames = array();
function __construct($file,$allowedExts,$uploadsDirecotry,$maxSize){
if(is_array($allowedExts) AND is_int($maxSize)){
$this->file = $file;
$this->allowedExts = $allowedExts;
$this->maxSize = $maxSize;
$this->uploadsDirecotry = $uploadsDirecotry;
}else{
throw new Exception("File extension must be in an array and max size value must be intger value.");
}
}
function uploadFiles(){
$file = $this->file;
$allowedExts = $this->allowedExts;
$maxsize = $this->maxSize;
$uploadsDir = $this->uploadsDirecotry;
for($i = 0; $i < count($file['name']); $i++){
$errors = array();
// print_r($_FILES);
$filename = $file['name'][$i];
$fileext = strtolower(end(explode('.',$filename)));
$filesize = $file['size'][$i];
$filetmpname = $file['tmp_name'][$i];
if(in_array($fileext, $allowedExts) === FALSE){
$errors[] = "Extension in sot allowed";
}
if($filesize > $maxsize){
$errors[] = "File size must be less than {$maxsize} KB !";
}
if(empty($errors)){
$random = rand(0,199);
$this->fileUrl = $random . "_" . date("d-m-Y") . "_" . $filename;
$destination = $uploadsDir. $random."_".date("d-m-Y") . "_" . $filename;
move_uploaded_file($filetmpname, $destination);
$this->filenames[] = $this->fileUrl;
}else{
foreach($errors as $error){
throw new Exception($error);
}
}
} // end for
return TRUE;
}
function getFileUrl()
{
return $this->fileUrl;
}
function getFilesNames()
{
return $this->filenames;
}
}
?>
and this html php file
<?php include 'header.php';
if(isset($_POST['add']))
{
$e_title = $_POST['e_title'];
$e_user = $userRow['user_name'];
try{
include 'models/Upload.php';
$file = $_FILES['e_img'];
$allowedExts = array('jpg','png','gif','jpeg');
$uploadsDirectory = "imgupload/";
$maxSize = 4000000;
$upload = new Upload($file, $allowedExts, $uploadsDirectory, $maxSize);
$upload->uploadFiles();
$e_img = $uploadsDirectory.$upload->getFileUrl();
}catch(Exception $exc){
echo'<div class="alert alert-block alert-danger">fail image uploaded</div>';
exit;}
$insert = $user->insert($e_title,$e_img,$e_user);
echo"<div class='alert alert-block alert-success'>Save success</div>";
exit;
}
?>
<form action='newads.php' method="POST" enctype="multipart/form-data">
<p>إضافة صور </p>
<input type="file" name='e_img[]' id="exampleInputFile">
<input type="submit" name='add' class='btn btn-primary' value='add' />
</form>
<?php include 'footer.php'; ?>
i try this but But it did not succeed
<form action='newads.php' method="POST" enctype="multipart/form-data">
<p>إضافة صور </p>
<input type="file" name='e_img[]' id="exampleInputFile">
<input type="file" name='e_img2[]' id="exampleInputFile">
<input type="file" name='e_img3[]' id="exampleInputFile">
<input type="submit" name='add' class='btn btn-primary' value='add' />
</form>

You do not need to increment the field names in your file fields. That will break the array when PHP receives it. Change to this: (they should all be e_img[]
<input type="file" name='e_img[]' id="exampleInputFile">
<input type="file" name='e_img[]' id="exampleInputFile">
<input type="file" name='e_img[]' id="exampleInputFile">

Related

Uploading Multiple Files to Location and Updated Database

I have been working on a multi-image upload function that I can't seem to make work. It currently will only work if I have a single image uploaded. I can't figure out what is going wrong with this script.
This is the function to upload images:
if(isset($_POST["btnSubmit"])){
$errors = array();
$extension = array("jpeg","jpg","png","gif");
$bytes = 1000000;
$allowedKB = 10485760000;
$totalBytes = $allowedKB * $bytes;
$imgDir = "assets/users/".$userLoggedIn."/images/";
if(isset($_FILES["files"])==false)
{
echo "<b>Please, Select the files to upload!!!</b>";
return;
}
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name)
{
$uploadThisFile = true;
$file_name=$_FILES["files"]["name"][$key];
$file_tmp=$_FILES["files"]["tmp_name"][$key];
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
if(!in_array(strtolower($ext),$extension))
{
array_push($errors, "File type is invalid. Name:- ".$file_name);
$uploadThisFile = false;
}
if($_FILES["files"]["size"][$key] > $totalBytes){
array_push($errors, "File size is too big. Name:- ".$file_name);
$uploadThisFile = false;
}
if($uploadThisFile){
$filename = basename($file_name,$ext);
$newFileName = uniqid().$filename.$ext;
move_uploaded_file($_FILES["files"]["tmp_name"][$key],$imgDir.$newFileName);
// current date and time
$date_added = date("Y-m-d H:i:s");
$imagePath = $imgDir.$newFileName;
$query = "INSERT INTO images(date_added, added_by, image, deleted) VALUES('$date_added', '$userLoggedIn','$imagePath', 'no')";
mysqli_query($con, $query);
}
}
header("Location: edit-images.php");
$count = count($errors);
if($count != 0){
foreach($errors as $error){
echo $error."<br/>";
}
}
}
?>
I thought the issue might be with size but I cut the condition to prevent it from uploading with no luck. I feel like I might be missing something in the foreach but I am completely stuck. I appreciate your help!
Here is the form I am using to upload:
<form method="post" enctype="multipart/form-data" name="formUploadFile" id="uploadForm" action="edit-images.php">
<div class="form-group">
<label for="exampleInputFile">Select file to upload:</label>
<input type="file" id="exampleInputFile" name="files[]" multiple="multiple">
<p class="help-block"><span class="label label-info">Note:</span> Please, Select the only images (.jpg, .jpeg, .png, .gif)</p>
</div>
<button type="submit" class="btn btn-primary" name="btnSubmit" >Start Upload</button>
</form>

File upload with php issue moving file

I can't upload a file in my server using php. The problem is that I can't find see which is the error, or I don't know how see it. By the way, I think is something about the file moving. This is the php code
<!-- upload -->
<?php
if (isset($_FILES["myFile"])) {
$myFile = $_FILES["myFile"];
// File prop
$myFileName = $myFile["name"];
$myFileTmp = $myFile["tmp_name"];
$myFileSize = $myFile["size"];
$myFileError = $myFile["error"];
//File extension
$myFileExt = explode(".", $myFileName);
$myFileExt = strtolower(end($myFileExt));
$allowed = array ('png' , 'jpg' , 'txt');
if(in_array($myFileExt, $allowed)) {
if($myFileError === 0) {
$newFileName = uniqid('', true) . '.' .$myFileExt;
$fileDestination = "/var/www/upload".$newFileName;
if(move_uploaded_file($myFileTmp, $fileDestination)) {
print_r($fileDestination);
} else {
print_r($myFileError);
}
} else {
print_r("error");
}
} else {
print_r("error");
}
}
?>
Here is the form:
<form action="" method="post" enctype="multipart/form-data" style="margin:15px">
<input type="file" style="margin:5px" name="myFile">
<input type="submit" class="btn-upload-file" style="margin:5px" value="Upload">
</form>
Any idea?
Your issue is very Minor...
You just missed a Slash(/) after the /www/uploads.
Try this:
<?php
if (isset($_FILES["myFile"])) {
$myFile = $_FILES["myFile"];
// File prop
$myFileName = $myFile["name"];
$myFileTmp = $myFile["tmp_name"];
$myFileSize = $myFile["size"];
$myFileError = $myFile["error"];
//File extension
$myFileExt = explode(".", $myFileName);
$myFileExt = strtolower(end($myFileExt));
$allowed = array ('png' , 'jpg' , 'txt');
if(in_array($myFileExt, $allowed)) {
if($myFileError === 0) {
$newFileName = uniqid('', true) . '.' . $myFileExt;
$fileDestination = "/var/www/upload/{$newFileName}"; //YOU WERE ONLY MISSING A SLASH (/) HERE AFTER /upload
if(move_uploaded_file($myFileTmp, $fileDestination)) {
print_r($fileDestination);
} else {
print_r($myFileError);
}
} else {
print_r("error");
}
} else {
print_r("error");
}
}
?>
<form action="" method="post" enctype="multipart/form-data" style="margin:15px">
<input type="file" style="margin:5px" name="myFile">
<input type="submit" class="btn-upload-file" style="margin:5px" value="Upload">
</form>

post multiple image using 1 field in a form

My code in here. how can I upload more then 1 image using 1 input field?
<?php
if (isset($_POST['beopen_form'])) {
if ($_FILES["file1"]["error"] > 0) {
echo "Error: " . $_FILES["file1"]["error"] . "<br>";
} else {
$x = mysql_insert_id();
$path_array = wp_upload_dir();
$old_name = $_FILES["file1"]["name"];
$split_name = explode('.', $old_name);
$time = time();
$file_name = $time . "." . $split_name[1];
$tmp_name = $_FILES["file1"]["tmp_name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $path . "/" . $old_name);
$path2 = $path . "/" . $old_name;
mysql_query("INSERT INTO carimage (image,carid,created,updated) VALUES ('$path2','$x','$created','$updated') ON DUPLICATE KEY UPDATE image='$path2',description='$makeid',updated='$updated'");
}
}
?>
<form enctype="multipart/form-data" class="beopen-contact-form" id="signupForm" novalidate="novalidate" action="<?php echo get_permalink(); ?>" method="post">
<input type="file" name="file" id="file">
<div id="recaptcha_div"></div><br>
<input type="hidden" name="beopen_form" value="1" /><!-- button -->
<button class="button send-message" type="submit">
<span class="send-message"></span><?php _e('Update', 'beopen');?>
</button>
</form>
html :-
<input type="file" name="file" id="file" multiple>
PHP CODE:-
//Loop through each file
for($i=0; $i<count($_FILES['file']['name']); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['file']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "./uploadFiles/" . $_FILES['file']['name'][$i];
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
//Handle other code here
}
}
}
I TAKE THIS CODE FROM :-
Multiple file upload in php
Before Post any question you should search for problem....!!!

Curious problème with images upload in PHP from form

I try to upload pictures from a form in PHP.
I've got a strange problem regarding my images upload:
My form:
<form id="booking-step" method="post" action="add.php" class="booking" autocomplete="off" enctype="multipart/form-data">
<input type="file" id="AddPhotos1" name="AddPhotos[]" />
<input type="file" id="AddPhotos2" name="AddPhotos[]" />
<input type="file" id="AddPhotos3" name="AddPhotos[]" />
<input type="file" id="AddPhotos4" name="AddPhotos[]" />
<input type="file" id="AddPhotos5" name="AddPhotos[]" />
</form>
My PHP:
if($_FILES['AddPhotos']){
$errorAddPhotos = "";
$validAddPhotos = "";
for($x=0;$x<sizeof($_FILES["AddPhotos"]["name"]);$x++){
$fichier = basename($_FILES['AddPhotos']['name'][$x]);
$taille_maxi = 3000;
$taille = filesize($_FILES['AddPhotos']['tmp_name'][$x]);
$extensions = array('.png', '.jpg', '.jpeg');
$extension = strrchr($_FILES['AddPhotos']['name'][$x], '.');
if(!in_array($extension, $extensions))
{
$errorAddPhotos .= "Wrong extension.<br />";
}
if($taille>$taille_maxi)
{
$errorAddPhotos .= "Wrong size.<br />";
}
if((in_array($extension, $extensions)) && ($taille<$taille_maxi))
{
$fichier = strtr($fichier,
'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ',
'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
$fichier = preg_replace('/([^.a-z0-9]+)/i', '-', $fichier);
if(move_uploaded_file($_FILES['AddPhotos']['tmp_name'][$x], $destin . $fichier))
{
$validAddPhotos = 'Success!';
}
else
{
$errorAddPhotos = 'Wrong';
}
}
}
}
echo $validAddPhotos;
echo $errorAddPhotos
My code looks good, but I cant upload my files...
Error: my files stay in condition "if(!in_array($extension, $extensions))".
Could you please help ?
Thanks.
I think you should use this logic is more perform than yours with testing image type and file size. Also, you can custom it with what you want like you did name of the file :)
multiple upload image function php?

Multiple File Upload PHP

I use the Following code to upload a single file .With This code I can Upload a single file to the database .I want to make multiple files uploaded by selecting multiple files in a single input type file.What Changes should i make in the code to make it upload multiple files?
<?PHP
INCLUDE ("DB_Config.php");
$id=$_POST['id'];
$fileTypes = array('txt','doc','docx','ppt','pptx','pdf');
$fileParts = pathinfo($_FILES['uploaded_file']['name']);
if(in_array($fileParts['extension'],$fileTypes))
{
$filename = $_FILES["uploaded_file"]["name"];
$location = "E:\\test_TrainingMaterial/";
$file_size = $_FILES["uploaded_file"]["size"];
$path = $location . basename( $_FILES['uploaded_file']['name']);
if(file_exists($path))
{
echo "File Already Exists.<br/>";
echo "Please Rename and Try Again";
}
else
{
if($file_size < 209715200)
{
$move = move_uploaded_file( $_FILES["uploaded_file"]["tmp_name"], $location . $_FILES['uploaded_file']['name']);
$result = $mysqli->multi_query("call sp_upload_file('".$id."','" . $filename . "','".$path."')");
if ($result)
{
do {
if ($temp_resource = $mysqli->use_result())
{
while ($row = $temp_resource->fetch_array(MYSQLI_ASSOC)) {
array_push($rows, $row);
}
$temp_resource->free_result();
}
} while ($mysqli->next_result());
}
if($move)
{
echo "Successfully Uploaded";
}
else
{
echo "File not Moved";
}
}
else
{
echo "File Size Exceeded";
}
}
}
else
{
echo " Invalid File Type";
}
?>
The Html That is used is
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file" id="uploaded_file" style="color:black" /><br/>
</form>
Basically you need to add to input name [] brackets and attribute "multiple"
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file[]" multiple="true" id="uploaded_file" style="color:black" /><br/>
</form>
Now all uploaded file will be available via
$_FILES['uploaded_file']['name'][0]
$_FILES['uploaded_file']['name'][1]
and so on
More info at
http://www.php.net/manual/en/features.file-upload.multiple.php

Categories