I'm trying to upload some images in my PHP application but I'm unable to do so. After some images, the post doesn't send data. It depends on the file size how many I can send like sometimes it works for 5 images sometimes for 3 images itself it throws this error.
<form action="store.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Top Image:</label><br>
<input type="file" name="topimg" class="form-control-file" style="padding-bottom:15px;">
</div>
<div class="form-group">
<label>Sub Images:</label><br>
<input type="file" name="img[]" class="form-control-file" id="exampleFormControlFile2" multiple required>
</div>
<center>
<button type="submit" class="btn btn-success" name="button">Save</button>
</center>
</form>
This is the form I'm using and it sends data to store.php
$uploaddir = '../../../img/gallery/';
$dirname = "/img/gallery/";
$newname = time() . basename($_FILES['topimg']['name']);
$fileup = $dirname . $newname;
$uploadfile = $uploaddir . $newname;
$img = '';
foreach ($_FILES['img']['name'] as $nam) {
$img = $img.",".$dirname.time().$nam;
}
$img = substr($img,1);
The above part is for setting the name and then the code to insert into my DataBase follows this (I think it's unnecessary so I left it out)
move_uploaded_file($_FILES['topimg']['tmp_name'], $uploadfile);
$count=0;
foreach ($_FILES['img']['name'] as $filename)
{
$tmp=$_FILES['img']['tmp_name'][$count];
$count=$count + 1;
move_uploaded_file($tmp,$uploaddir.time().$filename);
$tmp='';
}
Then this code to upload the files.
So when I try to upload the files it says "Undefined index: topimg" and "Undefined index: img" with errors that relate to these being invalid. I'm I doing the PHP part wrong or is it some setting in the server. I'm using MAMP pro if this info is needed
I think you need to change the upload_max_filesize and post_max_size directives in php.ini. See the php website https://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize for more information on these directives.
To change the php.ini file for mamp pro, check this question.
Related
I am using Heroku and their S3 addon - "Bucketeer".
I have this working and I can upload images no problem. The thing is I don't care about uploading images. My app deals with uploading MP3s (nothing sinister - it's a web app for local bands).
I can't upload MP3s. It doesn't error out or anything, it's just that files don't end up in S3 - whereas images uploaded exactly the same way, do.
Editing to add - It's not a file type issue as I tested by uploading a very small mp3 file and this worked great.
Code below:
<form class="form" action="../model/process-track-upload.php" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-xs-12 col-sm-4">
<div class="dashboard-widget">
<h3>Add a song to your collection</h3>
<input class="input" type="text" name="trackname" placeholder="Track Name" required/>
<input class="input-margin" name="userfile" type="file">
<input type="hidden" name="userID" value="<?php echo $userID ?>" />
<button class="btn btn-large btn-block " type="submit" name="btn-upload">upload</button>
</div>
</div>
</form>
And the backend code:
require('../vendor/autoload.php');
$s3 = Aws\S3\S3Client::factory();
$bucket = getenv('S3_BUCKET')?: die('No "S3_BUCKET" config var in found in env!');
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['userfile']) && $_FILES['userfile']['error'] == UPLOAD_ERR_OK && is_uploaded_file($_FILES['userfile']['tmp_name'])) {
try {
$upload = $s3->upload($bucket, $_FILES['userfile']['name'], fopen($_FILES['userfile']['tmp_name'], 'rb'), 'public-read');
?>
<p>Upload successful :)</p>
<?php } catch(Exception $e) { ?>
<p>Upload error :(</p>
<?php } }
The answer to this question lay in default php settings.
HOWEVER as I was using Heroku, I didn't have access to the php.ini file.
So the answer was to create a .users.ini file which is like a user created override of the php.ini.
In that file I just set the following params:
upload_max_filesize = 15M
post_max_size = 15M
max_input_time = 0
LimitRequestBody 0
After this I was good to go!
Can anyone help me solve this problem of file upload in php. I am getting undefined index at line! The codes are in two seperate files. I tried several codes, still not working. Please help. Thank you all in advance.
HTML File
<form role="form" name="uploadPro" id="uploadPro" method="post" action="upload.php" enctype="multipart/form-data">
<div class="col-lg-6">
<div class="form-group">
<label>Product Tags</label>
<textarea class="form-control" rows="2" name="pTags" id="PTags"></textarea>
<p class="help-block">Add Tags to your products to enable faster search.</p>
</div>
<div class="form-group">
<label>Product Expiry Date</label>
<input type="text" name="pExpDate" id="datepicker" class="form-control">
<p class="help-block">Until which date will product be displayed.</p>
</div>
<div class="form-group">
<label>Upload Main Image</label>
<input type="file" name="mainPath" id="mainPath">
<p class="help-block">This image will appear everywhere. Make sure it has a good quality to impress users and size greater than 400px X 400px. </p>
</div>
<div class="form-group">
<label>Upload Sub Image 1</label>
<input type="file" name="sub1" id="sub1">
<p class="help-block">Make sure image has a good quality to impress users and size greater than 400px X 400px. </p>
</div>
<div class="form-group">
<label>Upload Sub Image 2</label>
<input type="file" name="sub2" id="sub2">
<p class="help-block">Make sure image has a good quality to impress users and size greater than 400px X 400px. </p>
</div>
<div class="form-group">
<label>Upload Sub Image 3</label>
<input type="file" name="sub3" id="sub3">
<p class="help-block">Make sure image has a good quality to impress users and size greater than 400px X 400px. </p>
</div>
<input type="submit" value="Upload Image" name="submit" class="btn btn-default">
</div>
</form>
PHP Code
if(isset($_POST['submit'])){
/*Uploading main image*/
$filetmp = $_FILES["mainPath"]["tmp_name"];//getting error here
$filename = $_FILES["mainPath"]["name"];//getting error here
$filepath = "../uploads/".$filename;
move_uploaded_file($filetmp, $filepath);
/*Uploading sub image1*/
$filetmp1 = $_FILES["sub1"]["tmp_name"];//getting error here
$filename1 = $_FILES["sub1"]["name"];//getting error here
$filepath1 = "../uploads/".$filename1;
move_uploaded_file($filetmp1, $filepath1);
/*Uploading sub image2*/
$filetmp2 = $_FILES["sub2"]["tmp_name"];//getting error here
$filename2 = $_FILES["sub2"]["name"];//getting error here
$filepath2 = "../uploads/".$filename2;
move_uploaded_file($filetmp2, $filepath2);
/*Uploading sub image3*/
$filetmp3 = $_FILES["sub3"]["tmp_name"];//getting error here
$filename3 = $_FILES["sub3"]["name"];//getting error here
$filepath3 = "../uploads/".$filename3;
move_uploaded_file($filetmp3, $filepath3);
}
First, ensure that PHP is configured to allow file uploads.
In your "php.ini" file, search for the file_uploads directive, and set it to On:
file_uploads = On
Error Messages Explained
PHP returns an appropriate error code along with the file array. The error code can be found in the error segment of the file array that is created during the file upload by PHP. In other words, the error might be found in $_FILES['userfile']['error'].
First use print_r($_FILES) to check if the values r posting.
Use for loop instead of accessing index,
if(isset($_POST['submit'])){
foreach ($_FILES as $row) {
$filetmp = $row['tmp_name']; //getting error here
$filename = $row["name"]; //getting error here
$filepath = "../uploads/" . $filename;
move_uploaded_file($filetmp, $filepath);
}
I can check you code in my test file and its working file it may be issue is on your "php.ini" file. please send me your error so i can identify.
I did not change anything. I restarted my Wamp server and run the page in incognito window. Its working now.
Thank you all for your help. It makes me really happy to see how you help each other.
I am trying to upload an image using laravel4 and I've successfully managed to upload a file from a form and store it in a directory of my choice in the public folder. However the issue I am running into is viewing the images. I am developing in Netbeans and when I try to open my newly uploaded image I am told the image is corrupted.
This is my form:
<form action="{{ action('BookController#handleCreate') }}" method="post" role="form" enctype="multipart/form-data">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" />
</div>
<div class="form-group">
<label>Description</label>
<input type="textarea" class="form-control" name="desc" />
</div>
<!-- Img upload -->
<input type="file" name="img"/>
<input type="submit" value="Create" class="btn btn-primary" />
Cancel
</form>
This is my controller:
public function handleCreate(){
$book = new Book;
$book->book_name = Input::get('name');
$book->book_desc = Input::get('desc');
$destinationPath = public_path().'/uploads/covers/';//Set up destination path
$file = Input::file('img');//Get the file
$extension = $file->getClientOriginalExtension();//Get the extension
$filename = str_random(12).".".$extension;//Create a filename
$upload_success = $file->move($destinationPath, $filename);//Move the file to the destination
$pathToFile = '/uploads/covers/'.$filename;
echo $pathToFile;
//If successful.....
if($upload_success){
$book->book_cover = $filename;//store value in db
$book->save();//Save the book
return Redirect::action('BookController#index');
}else{//Else return to form with an error message....
return Response::json('error', 400);
}
}
This is the path to my image
/uploads/covers/VFBDJPqEdI6P.jpg
My plan is that I will store this path in the database and use it to display the image on the screen.
I don't know why but whilst I am uploading the files they are being corrupted and I'd appreciate if someone might suggest a way I could fix this.
Regards
I tried this and worked without losing any content
Storage::put($pathToFile,file_get_contents($request->file('img')->getRealPath()));
I have a form in which I want to upload at most five images. The name and extension of the images are supposed to be inserted in the database table 'images' and then uploaded to the _uploads/name_of_the_album/ directory.
The problem is, when I choose some images and hit upload, only the first image is uploaded correctly, the other images fail.
Here is my code:
if(isset($_FILES['image']) === true){
$files = $_FILES['image'];
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$album_id = (int)$_GET['album_id'];
$album_name = $_GET['album_name'];
for($i=0; $i<count($files['name']); $i++){
$name = $files['name'][$i];
$tmp_name = $files['tmp_name'][$i];
$size = $files['size'][$i];
$ext = explode('.', $files['name'][$i]);
$ext = strtolower(end($ext));
$img_name = explode('.', $files['name'][$i]);
$img_name = strtolower(current($img_name));
//do some testing echos to see the result
//echo $img_name."<br>";
//here i'm going to add some validation as soon as
// i fix the multi-upload problem
//insert image into database
$query_insert_image = "INSERT INTO `images` (album_id, image_name, image_ext) VALUES ({$album_id}, '{$img_name}', '{$ext}') ";
$insert_image = mysql_query($query_insert_image, $connection) or die(mysql_error());
if(mysql_affected_rows() == 1){
move_uploaded_file($tmp_name, '../_uploads/'.$album_name.'/'.$name);
}
//redirect
redirect_to("view_album.php?succeed=1");
}//end the for loop
//echo '<pre>',print_r($files, true),'</pre>';
}
And here is some of the code of the form:
<form action="" method="post" enctype="multipart/form-data" name="formUploadImages" id="formUploadImages">
<p>
<label for="image">Choose one or more Image(s):</label><br />
<input type="file" name="image[]" id="image" /><br />
<input type="file" name="image[]" id="image" /><br />
<input type="file" name="image[]" id="image" /><br />
<input type="file" name="image[]" id="image" /><br />
<input type="file" name="image[]" id="image" />
</p>
......
Any ideas what I'm doing wrong?
I think you're cutting the branch from under your own feet.
redirect_to("view_album.php?succeed=1");
Redirecting means refreshing the page which means the end of execution. When that redirect is triggered after the first for loop ends and first image is uploaded the for will not continue to the next iteration.
And the fix of course is to push that line after the for loop (and never expect anything after a redirect to ever execute - unless the headers are already sent).
Most functions that do what redirect_to() does (it's not a core function it's based on another function header()) also make sure execution stops (have a line calling header() and another line calling die()/exit()).
try this php code ,working for me:
for($i=1;$i<6;$i++)
{
if(!empty($_FILES['image_upload'.$i])):
$target = "images/".$_FILES['image_upload'.$i]['name'];
$image_upload.= ",".mysql_real_escape_string(($_FILES['image_upload'.$i]['name']));
move_uploaded_file($_FILES['image_upload'.$i]['tmp_name'], $target);
endif;
}
create a folder in your root named "images" ,all the images will be moved in this folder.
html form may be looks like:
<form action="" method="post" enctype="multipart/form-data" name="formUploadImages" id="formUploadImages">
<p>
<label for="image">Choose one or more Image(s):</label><br />
<input type="file" name="image_upload1" id="image_upload1" /><br />
<input type="file" name="image_upload2" id="image_upload2" /><br />
<input type="file" name="image_upload3" id="image_upload3" /><br />
<input type="file" name="image_upload4" id="image_upload4" /><br />
<input type="file" name="image_upload5" id="image_upload5" />
</p>
......
this code is running on my end ,and after some editing as according to your needs may be useful for you.
Happy coding!
foreach($_POST['image'] as $report_id){
$sql="INSERT INTO images (album_id, image_name, image_ext) VALUES ('{$album_id}', '{$report_id}', '{$ext}') ";
$queryExe=mysql_query($sql);
}
replace this code in the place of your code after "//insert image into database" .
http://php.net/manual/en/features.file-upload.multiple.php
Read the Warning block 'Since PHP 5.2.12, the max_file_uploads configuration...'. Maybe that's the problem.
And there are some good examples and maybe You should use foreach instead of for.
1) Create a .htaccess file in the root folder of web server.
2) Put the following code in side the .htaccess file and save it.
php_value upload_max_filesize 20M
php_value post_max_size 20M
php_value max_execution_time 200
php_value max_input_time 200
Now you can upload the file-size up-to 20MB in a simple way using file field in your html form and move_uploaded_file() function available in PHP.
I am unable to successfully upload an image/file to my server. The php is as follows:
//This is the directory where images will be saved
$uploadDir = "./";
$uploadFile = $uploadDir . basename( $_FILES['photo']['name']);
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $uploadFile)){
echo "The file has been uploaded successfully.";
} else {
print_r($_FILES);
}
I chose the directory at which this script lives, to ensure the functionality before I upload to the final directory. I want to upload photo's, and will check for file extensions later - but for now I at least need the upload functionality to work.
I get an empty array returned.
The form is as follows:
<form id="imageUploadForm" name="imageForm" enctype="multipart/form-data" action="imageController.php">
<label for="photo" class="blogLabel">Upload an Image</label>
<input type="file" name="photo" id="imageUpload">
<input type="submit" name="submit" id="imageSubmit" class="btn btn-primary" value="Upload">
</form>
You forgot the most important thing about a form -- the method!
If there is no method set it defaults to get.
You want post!
Add method="post" to your form.