Multiple File Upload results in foreach() error - php

Actually trying to upload multiple pictures in a folder at once with some kind of renaming. The upload goes to the foreach loop. However, it does stop at this point:
foreach ($_FILES['pictures']['name'] as $f => $name) {
if ($_FILES['pictures']['error'][$f] == 0) {
$name = $date;
$name .= "-";
$name .= $i;
$name .= ".";
$extsearch = $_FILES['pictures']['name'][$f];
$ext = pathinfo($extsearch, PATHINFO_EXTENSION);
$name .= $ext;
if(move_uploaded_file($_FILES["pictures"]["tmp_name"][$f], $path.$name)) {
if ($i == 1) {
create_image_thumb($albumFolder, $name);
}
$i++;
resize_image($albumFolder, $name);
}
}
}
However, I receive this error in the error_log and the files aren't moved:
PHP Warning: Invalid argument supplied for foreach() in /home/clublabo/public_html/management/create_album_action.php on line 43
UPDATE: Here is the HTML Code:
<form class="form form-horizontal" action="create_album_action.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="email-2" class="col-sm-3 col-md-4 control-label">Date</label>
<div class="col-sm-6 col-md-4">
<div class="input-with-icon">
<input name="dateAlbum" class="form-control" type="text" value="<?php echo date('Y-m-d'); ?>" data-provide="datepicker" data-date-autoclose="true" data-date-format="yyyy-mm-dd"><span class="icon icon-calendar input-icon"></span></div>
</div>
</div>
<div class="form-group">
<label for="password-2" class="col-sm-3 col-md-4 control-label">Pictures</label>
<div class="col-sm-6 col-md-4">
<input name="pictures" id="password-2" class="form-control" type="file" multiple>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6 col-md-offset-4 col-md-4">
<button class="btn btn-primary pull-right" type="submit">Create Album</button>
</div>
</div>
</form>
Maybe you guys has any Idea how to have this resolved?
Thanks :)

Replace:
<input name="pictures" id="password-2" class="form-control" type="file" multiple>
with:
<input name="pictures[]" id="password-2" class="form-control" type="file" multiple>

Just needed to add [] at the end of the form input "name".

Related

Laravel upload image field in Dashboard Error: SyntaxError: Unexpected token < in JSON at position 0

I'm running the latest version of laravel using custom admin panel and i'm new to laravel development so this is kind of a newbie question, i'm trying to upload image in a form all other fields in the ads form is working fine except the image upload field it's giving me syntax Error even though i used the same code for posts form and it's working just fine
the form upload the image to upload folder then store it's id and url in database->media table and then put the same id in the ->ads table in the images column
here is the source code for the html form
<div class="col-sm-12">
<label>Name - English</label>
<div class="form-group">
<input type="text" name="name_en" value="" class="form-control">
<i class="form-group__bar"></i>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label>Description - English</label>
<textarea class="wysiwyg-editor" name="description_en"></textarea>
</div>
</div>
<div class="col-sm-12 margin-bottom-30">
<label>Media - English</label>
<div class="row lightbox photos margin-bottom-30 media_sort" data-link="https://****/admin/ads/6/mediasort" data-language="en">
</div>
<div class="form-group color-picker">
<input type="file" class="form-control " name="media_en[]" accept=".jpg,.png,.jpeg,.webm,.mp4" multiple>
<i class="form-group__bar"></i>
</div>
</div>
<div class="col-sm-12">
<label>Name - Spanish</label>
<div class="form-group">
<input type="text" name="name_sp" value="" class="form-control">
<i class="form-group__bar"></i>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label>Description - Spanish</label>
<textarea class="wysiwyg-editor" name="description_sp"></textarea>
</div>
</div>
<div class="col-sm-12 margin-bottom-30">
<label>Media - Spanish</label>
<div class="row lightbox photos margin-bottom-30 media_sort" data-link="https://*****/admin/ads/6/mediasort" data-language="sp">
</div>
<div class="form-group color-picker">
<input type="file" class="form-control " name="media_sp[]" accept=".jpg,.png,.jpeg,.webm,.mp4" multiple>
<i class="form-group__bar"></i>
</div>
</div>
Here is the adservice.php starting from line 81
foreach ($active_languages as $language) {
$ad->translate($language->code)->name = $request['name_' . $language->code] ? $request['name_' . $language->code] : $request['name_en'];
$ad->translate($language->code)->description = $request['description_' . $language->code];
$ad->translate($language->code)->excerpt = $request['excerpt_' . $language->code];
$media_key = null;
if ($request->hasFile('media_' . $language->code)) {
$media_key = 'media_' . $language->code;
}
if ($media_key) {
$media = $this->mediaService->upload($request, $media_key);
if (count($media)) {
$media_array = [];
foreach ($media as $m) {
$m->authorable_type = \get_class(Auth::user());
$m->authorable_id = Auth::user()->id;
$m->save();
$media_array[] = $m->id;
}
$old_images = (array) (\json_decode($ad->translate($language->code)->images, true));
$media_array = \array_merge($old_images, $media_array);
$ad->translate($language->code)->images = \json_encode($media_array);
}
} else {
if (!empty($request['images_' . $language->code])) {
$media_key = ('images_' . $language->code);
}
if ($media_key) {
$ad->translate($language->code)->images = \json_encode(explode(',', $request[$media_key]));
}
}
}

move_uploaded_file( ) not working on video/audio/pdf

I've done an upload page that should upload the files and set their name in the database. It works just perfect with the pictures , but the sound formats and the other ones doesn't seem to work.
This is how my html part look
<form method="post" enctype="multipart/form-data">
<div class="card card-login">
<?= FH::csrfInput() ?>
<div class="card-header text-center" data-background-color="rose" >
<h3 class="card-title">Upload</h3>
</div>
<div class="card-content">
<div class="input-group">
<span class="input-group-addon">
</span>
<div class="form-group label-floating">
<label class="control-label"><h4>Chose a name for the file</h4></label>
<br>
<input type="textd" name="name" id="name" class="form-control" value="">
</div>
<br><br>
<div class="form-group label-floating">
<label class="control-label"><h4>Choose a file</h4></label>
<br>
<input type="file" id="file" name="file" >
</div>
</div>
</div>
<div class="footer text-center">
<div class="file-upload">
<label for="submit" class="file-upload__label">
<div class="isa_error_class">
<?= FH::displayErrors($this->displayErrors)?>
</div>
<button class="btn btn-wd btn-lg" data-background-color="rose">Submit</button>
</label>
<input type="submit" name="submit" value="Submit" class="file-upload__input">
</div>
</div>
</form>
And there is the php part
if($this->request->isPost())
{
$this->request->csrfCheck();
$upload->assign($this->request->get());
$upload->user_id = Users::currentUser()->id;
$upload->name .= "." . pathinfo($_FILES['file']['name'] , PATHINFO_EXTENSION);
$value = pathinfo($_FILES['file']['name'] , PATHINFO_EXTENSION);
$upload->format = Upload::setFormat($value);
$dir = Users::currentUser()->id;
if(move_uploaded_file($_FILES["file"]["tmp_name"],'files' . DS . $dir . DS . $upload->name ))
{
if($upload->save())
{
Router::redirect('upload');
}
else
{
$upload->addErrorMessage('file','There were a problem saving in the database.');
}
}
else
{
$upload->addErrorMessage('file','There were a problem uploading it.');
}
}
The DS is the separator. The image formats seems to work perfect , but the other formats don't. Any ideas ?
You should check if u have allowed file_uploads = On in your php.ini and also check the maximum file size upload_max_filesize= 20M and to make sure that you are not passing it.

Move uploaded file in php work only sometimes when use multiple uploads

I have a web page for uploading tile image and a concept design image using that tile with a single submit button. But when uploading 2 images with a single submit, move uploaded file is not working always. Sometimes it just moves tile images only, not concept image.
Here is my code:
if(isset($_POST['upload']))
{
$name=$_POST['name'];
$size=$_POST['size'];
$finish=$_POST['finish'];
/* Concept Image */
$concept=$_FILES['concept']['name'];
$contmp=$_FILES['concept']['tmp_name'];
$location='concept';
$upload=move_uploaded_file($contmp,'concept/'.$concept);
$confile='concept/'.$concept;
/* Tile Image */
$image=$_FILES['image']['name'];
$imgtmp=$_FILES['image']['tmp_name'];
$location='tileimage';
$uploading=move_uploaded_file($imgtmp,"tileimage/".$image);
$upfile="tileimage/".$image;
$qry="insert into tile_list value('','$name','$size','$finish','$upfile','$confile')";
$ex=mysqli_query($con,$qry);
$query="insert into availcolors value('','$name','$name','$upfile','$confile')";
$exe=mysqli_query($con,$query);
}
and here is my html markup:
<form method="post" enctype="multipart/form-data" class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-4">TILE IMAGE<br>
</label>
<div class="col-sm-10 col-md-offset-0 col-md-4">
<input type="file" class="form-control" name=image>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4">CONCEPT 3D<br>
</label>
<div class="col-sm-10 col-md-offset-0 col-md-4">
<input type="file" class="form-control" name="concept">
</div>
</div>
<div class="col-sm-10 col-md-7 col-md-offset-4">
<button type="submit" name="upload"><img src="images/upload.jpg" alt="" width="106" height="25" class="img-responsive"></button>
</div>
<form>
Please help me to find out what is the problem
Please try this code:
<?php
//error_reporting(0);
if(isset($_POST['upload']))
{
$name = $_POST['name'];
$size = $_POST['size'];
$finish = $_POST['finish'];
/* Concept Image */
$aMyUploads = array();
foreach ($_FILES as $key => $aFile) {
for($i = 0; $i<count($aFile['error']); $i++){
//echo $aFile['error'][$i]; exit;
if(0 === $aFile['error'][$i]){
if($i == 0)
$newLocation = 'concept/'.$aFile['name'][$i];
else if($i == 1)
$newLocation = 'tileimage/'.$aFile['name'][$i];
}
if(0 === $aFile['error'][$i] && (false !== move_uploaded_file($aFile['tmp_name'][$i], $newLocation))){
$aMyUploads[] = $newLocation;
} else {
$aMyUploads[] = '';
}
}
}
if(is_array($aMyUploads)){
$confile=$aMyUploads[0];
$upfile=$aMyUploads[1];
$qry="insert into tile_list value('','$name','$size','$finish','$upfile','$confile')";
$ex=mysqli_query($con,$qry);
$query="insert into availcolors value('','$name','$name','$upfile','$confile')";
$exe=mysqli_query($con,$query);
}else{
echo "ERROR :: Not insert Please try";
}
}
?>
<html>
<form method="post" enctype="multipart/form-data" class="form-horizontal" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div class="form-group">
<label class="control-label col-sm-4">TILE IMAGE<br></label>
<div class="col-sm-10 col-md-offset-0 col-md-4">
<input type="file" class="form-control" name="upload_files[]">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4">CONCEPT 3D<br></label>
<div class="col-sm-10 col-md-offset-0 col-md-4">
<input type="file" class="form-control" name="upload_files[]">
</div>
</div>
<div class="col-sm-10 col-md-7 col-md-offset-4">
<button type="submit" name="upload"><img src="images/upload.jpg" alt="" width="106" height="25" class="img-responsive"></button>
</div>
</form>
</html>

Unable to save multiple images in database Laravel 5

I have a table named "cases" where the column are id image1,content1,image2,content2,image3 and content3
My content1,content2,content3 will be saved in database when i submit it from form but images are nither saved in folder nor in database. I need help
Controller
public function store(Request $request,SidContainRequest $request)
{
$sidContain = new sidcontain;
$sidContain->content1 = $request->get('page_content1');
$sidContain->content2 = $request->get('page_content2');
$sidContain->content3 = $request->get('page_content3');
//upload multiple files
$files= [];
if($request->file('leftimage')) $files[] = $request->file('leftimage');
if($request->file('Middleimage')) $files[] = $request->fiel('Middleimage');
if($request->file('Rightimage')) $files[] = $request->file('Rightimage');
foreach($files as $flle)
{
if(!empty($file))
{
$filename[] = $file->getClientOrginalName();
if(isset($filename)){
$file->move(base_path().'/frontend/sidimage/',end($filename));
}
}
$sidContain->image1 = $filename[0];
$sidContain->image2 = $filename[1];
$sidContain->image3 = $filename[2];
}
$ok = $sidContain->save();
if($ok)
{
\Session::flash('flash_message','Report Added Successfully!');
return Redirect::to('administrator/sidConatin/create');
}
}
view/form
<div class="form-group">
<label>Left Image</label>
<input type="file" name="leftimage">
#if($errors->has('leftimage')) <p style="color:red;">{{$errors->first('leftimage')}}</p>#endif
</div>
<div class="form-group">
<label>Left Content</label>
<textarea name="page_content1" id="page_content1" class="editor form-control"></textarea>
#if($errors->has('page_content1'))<p style="color:red;">{{$errors->first('page_content1')}}</p>#endif
</div>
<div class="form-group">
<label>Middle Image</label>
<input type="file" name="Middleimage">
#if($errors->has('Middleimage')) <p style="color:red;">{{$errors->first('Middleimage')}}</p>#endif
</div>
<div class="form-group">
<label>Middle Content</label>
<textarea name="page_content2" id="page_content2" class="editor form-control"></textarea>
#if($errors->has('page_content2')) <p style="color:red;">{{$errors->first('page_content2')}}</p>#endif
</div>
<div class="form-group">
<label>Right Image</label>
<input type="file" name="Rightimage">
#if($errors->has('Rightimage')) <p style="color:red;">{{$errors->first('Rightimage')}}</p>#endif
</div>
<div class="form-group">
<label>Right Content</label>
<textarea name="page_content3" id="page_content3" class="editor form-control"></textarea>
#if($errors->has('page_content3')) <p style="color:red;">{{$errors->first('page_content3')}}</p>#endif
</div>
<div style="margin-top: 15px;">
<button type="submit" class="btn btn-danger">Submit</button>
</div>
</form>

redisplay PHP form with errors

I have a dozen fully functional scripts that use heredoc statements to display HTML including e.g. $errors[field_name] yet this nearly identical script results in POST errors like
"Notice: Undefined index: user_password in register.php on line 162"
When the user enters a password with 5 characters when 8+ characters are required, a validation function populates $errors['password'] and the form is supposed to re-display along with validation errors.
Can't see what I'm missing in this Bootstrap style form. The $errors array is global and I can force the display of errors, so I know errors are initialized but I keep getting
"Notice: Undefined index"
$fields = array( 'user_name', 'user_email', 'user_password', 'user_password2' );
function display_form($string = '')
{
global $error_token, $cfg, $fields, $form, $errors, $s, $token, $validation_status;
$error_message = '';
switch($_SERVER['REQUEST_METHOD'])
{
Case 'POST':
// validation failed, redisplay the form
$autofocus = '';
foreach($fields as $field){
$$field = htmlentities(get_cgi_var($field), ENT_QUOTES, 'UTF-8');
// wrap errors in Bootstrap alert markup
$errors[$field] = !empty($errors[$field]) ? '<div class="alert alert-danger">'.htmlentities($errors[$field], ENT_QUOTES, 'UTF-8').'</div>' : '';
// debug, force the premature display of errors.
// echo !empty($errors[$field]) ? '<div class="alert alert-danger">'.htmlentities($errors[$field], ENT_QUOTES, 'UTF-8').'</div>' : '<p>empty</p>';
}
break;
Case 'GET':
default:
$autofocus = 'autofocus';
foreach($fields as $field){
$$field = '';
$errors[$field] = '';
}
$error_token = '';
break;
};
foreach($fields as $field){
$validation_status[$field] = empty($errors[$field]) ? ' has-success' : ' has-error';
}
$self = SELF;
print<<<_HTML_
<div class="col-lg-6">
<div class="panel panel-primary">
<div class="panel-heading">Registration</div>
<div class="panel-body">
$string
$error_message
<form name="form1" id="form1" action="$self" class="form-horizontal" role="form" method="POST">
<fieldset>
$error_token
$errors[user_name]
<div class="row form-group$validation_status[user_name]">
<label for="user_name" class="col-lg-3 control-label">Name</label>
<div class="col-lg-9">
<input type="text" name="user_name" id="user_name" value="$user_name" maxlength="255" $autofocus required placeholder="Your First & Last Name" title="Your First & Last Name" autocomplete="on" class="form-control">
</div>
</div>
$errors[user_email]
<div class="row form-group$validation_status[user_email]">
<label for="user_email" class="col-lg-3 control-label">Email</label>
<div class="col-lg-9">
<input type="email" name="user_email" id="user_email" value="$user_email" maxlength="255" required placeholder="Your Email Address" autocomplete="on" class="form-control">
</div>
</div>
$errors[user_password]
<div class="row form-group$validation_status[user_password]">
<label for="user_password" class="col-lg-3 control-label">Password</label>
<div class="col-lg-9">
<input type="text" name="user_password" id="user_password" value="$user_password" maxlength="255" required placeholder="Password or Passphrase" autocomplete="on" class="form-control">
<p class="help-block">Case sensitive password containing 8+ characters or a phrase containing 3-5 words</p>
</div>
</div>
$errors[user_password2]
<div class="row form-group$validation_status[user_password2]">
<label for="user_password2" class="col-lg-3 control-label">Password</label>
<div class="col-lg-9">
<input type="text" name="user_password2" id="user_password2" value="$user_password2" maxlength="255" required placeholder="Re-enter Password or Passphrase" autocomplete="on" class="form-control">
</div>
</div>
<div class="row form-group">
<label for="submit_button" class="col-lg-3 control-label"> </label>
<div class="col-lg-9 text-center">
<input type="hidden" name="token" value="$token">
<input type="submit" name="submit_button" id="submit_button" value="Submit" onClick="return captcha_validation(this.form);" class="btn btn-primary">
</div>
</div>
</fieldset>
</form>
</div><!-- /panel-body -->
<div class="panel-footer text-center"> </div>
</div><!-- /panel -->
</div><!-- /col -->
<div class="col-lg-6">
<div class="well">unused column</div>
</div><!-- /col -->
_HTML_;
};
Here's your problem:
default:
$autofocus = 'autofocus';
foreach($fields as $field){
$$field = ''; // <------------------
$errors[$field] = '';
}
$error_token = '';
break;
replace $$field with $field or remove it altogether - it's not needed here.

Categories