cannot get file to upload in PhP - php

I have added this to my form_action.php:
if(isset($_FILES['attachment1'])){
$errors= array();
$file_name = $_FILES['attachment1']['name'];
$file_size = $_FILES['attachment1']['size'];
$file_tmp = $_FILES['attachment1']['tmp_name'];
$file_type = $_FILES['attachment1']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['attachment1']['name'])));
$expensions= array("jpeg","jpg","png","doc","pdf");
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG, PNG, PDF or DOC file.";
}
if(empty($errors)==true) {
move_uploaded_file($file_tmp,"uploads/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
with the form field being
<form method="post" action="form_action1.php">
<div class="form-group">
<label for="attachment1">Add file(s)</label>
<input type="file" class="form-control-file" id="attachment1" aria-describedby="fileHelp" name="attachment1">
<input type="file" class="form-control-file" id="attachment2" aria-describedby="fileHelp" name="attachment2">
<input type="file" class="form-control-file" id="attachment3" aria-describedby="fileHelp" name="attachment3">
</div>
</form>
The path gets saved but the file does not upload. Am I missing a step that I am not aware of? Also, can I set an ARRAY in the $_FILES field to allow for three uploads?
This is the last step in a personal project that I am trying to complete. Thank you.

You need to add enctype for the form to post files.
<form method="post" action="form_action1.php" enctype="multipart/form-data">
From MDN:
enctype
When the value of the method attribute is post, enctype is the MIME type of content that is used to submit the form to the server. Possible values are:
application/x-www-form-urlencoded: The default value if the attribute is not specified.
multipart/form-data: The value used for an element with the type attribute set to "file".
text/plain (HTML5): This value can be overridden by a formenctype attribute on a or element.

Related

move_uploaded_file() only uploads small files

I want to implement a small file upload on a web portal. I found this solution on PHP.net:
<form action='action.php' method='post' enctype="multipart/form-data">
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<!-- Name of input element determines name in $_FILES array -->
Send this file:
<input name="userfile" type="file"/>
<!-- hidden input fields to sent variables to action.ph -->
<innput type="hidden" name='casenumber' id="caseForFileUpload" />
<input type="hidden" name='key' id="keyForFileUpload" />
<input type="submit" value="Send File" name="uploadfiles"/>
</form>
and this is the relevant part of action.php
if(isset($_POST['uploadfiles'])){
if(!empty($_FILES)){
$target_dir = "upload/";
$target_file = $target_dir.basename($_FILES['userfile']['name']);
$fileType = pathinfo($target_file,PATHINFO_EXTENSION);
if($fileType == "pdf"){
if(move_uploaded_file($_FILES['userfile']['tmp_name'], $target_file)){
echo "<br><br>File uploaded";
}else{
echo "<br><br>File could not be uploaded";
}
}
}
}
This works well for small files <150KB, but fails for files larger than that and I don't know why this is happening.
Relevant info from php.ini:
upload_max_filesize = 20M
post_max_size = 20M
max_execution_time = 30
max_input_time = 60
So it really should work for files that are larger than 150KB. There is no message in the PHP log and no .htaccess is used that may override these settings.
Where else can I look to track down this behavior or how else can I implement a file upload to allow file sizes for up to 2MB?
PS: Please also note that the server is still running with PHP 5.2.17 and that it's not in my power to update it to a newer version.
As request by the OP:
name="MAX_FILE_SIZE" value="30000"
That is 30,000 bytes. As per the manual http://php.net/manual/en/features.file-upload.post-method.php
"The MAX_FILE_SIZE hidden field (measured in bytes)".
Either remove that input, or increase it.

PHP - accessing a form-submitted file for validation

I've been doing form validation using $_POST for text entries. Now I have to validate uploaded files through the HTML type='file' forms. I'm having trouble accessing them through $_POST or $_FILES. Is there a different way to do this? I need to get the file so that I can check the MIME type using getimagesize() or mime_content_type()
Here are the relevant bits from my form:
<form action='submission.php' method='POST'>
<p>Upload photo of professor</p>
<input type="file" name="pic" accept="image/*>
<p>Upload video of professor</p>
<input type="file" name="video" accept="video/*">
<p><input type="submit" onclick="validate()"></p>
</form>
submission.php is supposed to call on a validation function to check that the MIME type is image, if I can get the file.
function validateimage(&$errors, $field_list, $field_name, $pattern) {
if (isset($field_list[$field_name])) {
if (!preg_match($pattern, mime_content_type($field_list[$field_name]))) {
$errors[$field_name] = 'Please upload an image file';
}
} else {
$errors[$field_name] = 'Required field';
}
}
After adding enctype="multipart/form-data" to my field and setting $field_list to $_FILES it almost works. However, it appears isset($_FILES['pic']) is always true, as when I try to submit with no upload, I get this warning:
validateimage($errors, $_FILES, 'pic', '/^image/i');
Warning: mime_content_type(): Empty filename or path in /Applications/XAMPP/xamppfiles/htdocs/cs4ww3/Assignment 3/validate.inc.php on line 36
In order for $_FILES to be populated with the submitted files, in your html you need to set enctype attr on your form to multipart/form-data:
<form action='submission.php' method='POST' enctype="multipart/form-data">
...
</form>

PHP - prevent html5 input type file attribute multiple hack?

Hello I'm doing form upload 4 files field. Each field can upload 1 file.
but I just know that hacker can hack with firebug to add html5 "multiple" attribute.(see the screenshot)
and then hacker can upload exceed 4 files now that I don't want to happen.
Question : How can I do to limit the upload file to 4 files?
here is my current code
for($i=0;$i<count($_FILES["file"]["name"]);$i++) {
if($_FILES["file"]["name"][$i] != "") {
$split = explode('.', $_FILES["file"]["name"][$i]);
$ext = end($split);
$tempFile = $_FILES['file']['tmp_name'][$i]; //3
$targetFile = "upload/". date('Y-m-d')."_".($i+1).".".$ext; //5
move_uploaded_file($tempFile,$targetFile); //6
}
}
..
<form method="post" action="upload.php" enctype="multipart/form-data">
<input type="file" name="file[]"/><br>
<input type="file" name="file[]"/><br>
<input type="file" name="file[]"/><br>
<input type="file" name="file[]"/><br><br>
<input type="submit" value="Upload"/>
</form>
Things like this must be validated server-side.
if(count($_FILES["file"]["name"]) > 4) {
// show the user an error and refuse to continue
}

Image upload form inside larger form?

I have a form that allows users to create events. Inside this form I have a form for an image upload. The HTML looks like this:
<form id="upload_event" method="post" action="system/upload_event.php">
<input type="text" name="title">
<textarea name="description"></textarea>
<form id="upload_image" method="post" action="system/upload_image.php">
<!-- code -->
</form>
Upload event
<input style="display:none" type="submit" id="submit_upload_event" name="submit_upload_event">
</form>
This is what my upload_image.php, which processes the image upload, looks like:
// A list of permitted file extensions
$allowed = array('png', 'jpg', 'gif','zip');
if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0){
$extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"error"}';
exit;
}
if(move_uploaded_file($_FILES['upl']['tmp_name'], 'uploads/'.$_FILES['upl']['name'])){
echo '{"status":"success"}';
exit;
}
}
echo '{"status":"error"}';
exit;
As I found out, it is not possible to nest a form into another one. What would be the solution here?
If you're using Ajax you could return a value from your upload form to your main form. Like putvande said you can't have a form inside a form.

PHP cannot upload multiple images

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.

Categories