2 input files in one form - php

Is it possible to have something like the following
<form id="uploadForm" action="" method="post" enctype="multipart/form-data">
<p>Upload File 1</p>
<input type="file" name="profile"/>
<p>Upload File 2</p>
<input type="file" name="cover"/>
<input type="submit" value="Submit" />
</form>
I then have some php script looking like:
if (empty($_POST['save']) === false) {
// FOR PROFIL CHANGE
if (isset($_FILES['profile']) === true){
$allowed= array('jpg', 'jpeg', 'png', 'bmp');
$file_name = $_FILES['profile']['name']; //name of the file
$file_exts = explode('.', $file_name); // extension of the file
$file_extn = strtolower(end($file_exts)); //inlowercase
$file_temp = $_FILES['profile']['tmp_name'];
$id = $user_data['id'];
change_image2($id, $file_temp, $file_extn);
}
// FOR COVER CHANGE
if (isset($_FILES['cover']) === true){
$allowed= array('jpg', 'jpeg', 'png', 'bmp');
$file_name = $_FILES['cover']['name']; //name of the file
$file_exts = explode('.', $file_name); // extension of the file
$file_extn = strtolower(end($file_exts)); //inlowercase
$file_temp = $_FILES['cover']['tmp_name'];
$id = $user_data['id'];
change_image3($id, $file_temp, $file_extn);
}
But if I upload just one file ( cover for example ); it is saved also in profile for some reason ...
If find this weird because i gave different names to the inputs.
Can anybody explain the problem please?

Use print_r($_FILES) to check what data you receive when only one file is uploaded.
I think $_FILES['profile'] is always set, no matter if a file is uploaded using the corresponding <INPUT> element or not. You should check if $_FILES['profile']['name'] contains the file name or is empty.
You must also use is_uploaded_file() (and move_uploaded_file()) with $_FILES['profile']['tmp_name'] to handle the file.
is_uploaded_file() is the only authoritative answer to the question: "did the user uploaded a file using this <input> control?"
// FOR PROFIL CHANGE
if (! empty($_FILES['profile']['name'])
&& is_uploaded_file($_FILES['profile']['tmp_name'])){
// ... process the file ...

Change your condition from if (isset($_FILES['profile']) === true){ into if (strlen($_FILES['profile']['tmp_name']) > 0){.
There will be always $_FILES['profile'], but $_FILES['profile']['tmp_name'] contains some data only if there is some file transfer.

Related

why do i have a corrupted image file after using move_uploaded_file function

I have a form:
<form action='' enctype="multipart/form-data" method="post">
<input type="file" name="image">
<input type="submit" value="send">
</form>
I have php code:
$file = $_FILES['image']
$ext = explode(",", $file['type'])[0];
$location = "../image/movedimage.$ext";
if(move_uploaded_file($file['tmp_name'], $location)) echo 'moved';
else echo 'internal error';
This echos "moved" but the problem is that when I check the path to which the file was moved, the image file in there is corrupted.
I had to change the system of uploading the image by doing this:
$file_content = file_get_contents($file['tmp_name']);
$file_dump = file_put_contents($location, $file_content);
This attempt of placing the file directly using the file_put_contents works fine and the image file is perfect just as uploaded but using the move_uploaded_file leaves a corrupted file in the destination folder. I would like to understand why this is happening as the $file['error'] returns a value 0 and the move_uploaded_file function does not return false.
In your code by using
$ext = explode(",", $file['type'])[0];
you get the extension as image/your_image_type.
Then you are appending that with the file name, which will create an invalid image.
To get the extension, you can do as follows
$ext= explode("/", $file['type'])[1];
or
$ext = strtolower(end(explode('.',$_FILES['image']['name'])));

Only one file being uploaded using multiple file uploader

The following PHP file script uploads only one file although its supposed to send multiple files. Can't understand where it breaks. Tried using foreach but to no avail.
I did a var_dump and they show the correct number of files being sent.
HTML
<form id="fileupload" method="POST" enctype="multipart/form-data">
<input type="file" name="uploadfile[]" multiple id="uploadfile" />
</form>
PHP
<?php
require_once 'config.php';
############ Edit settings ##############
$UploadDirectory = './storage/';
#########################################
if(!isset($_FILES["uploadfile"])) {
die('Something wrong with upload! Is "upload_max_filesize" set correctly?');
}
//check if this is an ajax request
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
die();
}
// Total number of files to be uploaded
$total_files = count($_FILES['uploadfile']['name']);
//check if there is at least 1 file
if($total_files < 1) {
die();
}
for($i=0; $i<$total_files; $i++) {
//Is file size is less than allowed size.
if ($_FILES["uploadfile"]["size"][$i] > 29000000) {
die("File size is too big!");
}
$allowedTypes = array('gif', 'png', 'jpeg', 'jpg', 'pdf', 'xls', 'xlsx', 'doc', 'docx', 'ppt', 'pptx', 'mp3', 'mp4', 'rar', 'zip', 'txt');
$FileNameFull = strtolower($_FILES['uploadfile']['name'][$i]);
$FileNameShort = pathinfo($FileNameFull, PATHINFO_FILENAME);
$FileExt = pathinfo($FileNameFull, PATHINFO_EXTENSION);
if(!in_array($FileExt, $allowedTypes)) {
die('Unsupported File format!');
}
$FileCode = rand(0, 9999999999); //Random number to be used to rename actual filename
$NewFileName = $FileCode.'.'.$FileExt; //new file name
if(move_uploaded_file($_FILES['uploadfile']['tmp_name'][$i], $UploadDirectory.$NewFileName )) {
// Save the file details to database
//$query = $dbh->prepare("INSERT INTO uploads(file_name, file_code, file_ext, timestamps) VALUES (:file_name, :file_code, :file_ext, :timestamps)");
/*$query->execute(array(
":file_name" => $FileNameShort,
":file_code" => $FileCode,
":file_ext" => $FileExt,
":timestamps" => round(microtime(true) * 1000)
));*/
die('Success! File Uploaded.');
}
else{
die('error uploading File!');
}
}
Well i will give you a small example:
HTML:
<input name="uploadfile[]" type="file" multiple="multiple" />
PHP:
$totalImage = count($_FILES['uploadfile']['name']);
for($i=0; $i<$totalImage; $i++) {
$temporaryPathOfImage = $_FILES['uploadfile']['tmp_name'][$i];
if ($temporaryPathOfImage != ""){
$dirPath = "./storage/" . $_FILES['uploadfile']['name'][$i];
if(move_uploaded_file($temporaryPathOfImage, $dirPath)) {
//Code Here
}
}
}
Problem:
die('Success! File Uploaded.');
Remove this line so you will get all images in that loop.

PHP move_uploaded_file not working but no errors either?

I'm trying to move my uploaded file to a pictures folder. I dont get any errors when it comes to the script. Im using godaddy as the host. All file permissions are set up correctly. Have really no idea what else to do.
This is the php code:
<?php
public function CheckPicture($picture){
if(empty($_FILES['picture']['name'])){
echo "Must choose a file.";
}else{
$allowed = array('jpg', 'jpeg', 'png');
$file_name = $_FILES['picture']['name'];
//line 157->$file_extn = strtolower(end(explode('.', $file_name)));
$file_temp = $_FILES['picture']['tmp_name'];
if(in_array($file_extn, $allowed)){
$this->UploadPicture($username, $file_name, $file_extn);
}else{
echo $file_extn;
echo "Incorect file type. Types allowed: ";
echo implode(', ' , $allowed);
}
}
}
public function UploadPicture($username, $file_temp, $file_extn){
ini_set('display_errors',1);
error_reporting(E_ALL);
$file_path = '/home/content/49/11554349/html/gb/dev/images/pictures/' . substr(md5(time()), 0 , 9) . '.' . $file_extn;
move_uploaded_file($file_temp, $file_path);
echo $file_path;
print_r("$file_temp");
}
?>
This is how I am calling it in the html:
<?php
session_start();
include_once('post.php');
$username = unserialize($_SESSION["username"]);
$email = $_SESSION["email"];
if(!$_SESSION["username"]){
header("Location: http://www.greenboardapp.com/dev/");
}
if(isset($_FILES['picture'])){
$upload = new Post();
$upload->CheckPicture($picture);
}
?>
This is the form:
<div class="tile">
<img src="images/profileimg.png" alt="Tutors" class="tile-image">
<form action="profile.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="picture"><br>
<h6><input type="submit" value="Change Profile Pic" class="btn btn-hg btn-success"></h6>
</form>
</div>
The problem is, that end requires a reference, because it modifies the internal representation of the array (it makes the current element pointer point to the last element).
The result of explode('.', $file_name) cannot be turned into a reference. This is a restriction in the PHP language, that probably exists for simplicity reasons.
Output for 5.1.0 - 5.5.6
Strict Standards: Only variables should be passed by reference
Output for 5.0.5
Fatal error: Only variables can be passed by reference
Process exited with code 255.
Output for 4.3.0 - 5.0.4
Success
Solution
Find:
$file_extn = strtolower(end(explode('.', $file_name)));
$file_temp = $picture['tmp_name'];
Change to:
$file_extn_ex = explode('.', $file_name);
$file_extn_end = end($file_extn_ex);
$file_extn = strtolower($file_extn_end);
$file_temp = $picture['tmp_name'];

PHP upload image

Alright I have way to much time invested in this. I am new to PHP programming and trying to grasp the basics, but I am a little lost as of last night I was able to get a PHP form to upload basic data like a name address and stuff to my (MySQL) server.
But today I said let's do the next step which would be an image to the server.
I have watched 3 videos on YouTube probably a 100 times just recoping code and trying it in so many different ways.
http://www.youtube.com/watch?v=CxY3FR9doHI
http://www.youtube.com/watch?v=vFZfJZ_WNC4&feature=relmfu
and still haven't been able to get it.
But long story short: I have a config.php file that connects to the server and here is the the code I'm running on the upload form page:
<html>
<head>
<title>Upload an image</title>
</head>
<body>
<form action="UploadContent.php" method="POST" enctype="multipart/form-data">
File:
<input type="file" name="image"> <input type="submit" value="Upload">
</form>
<?php
// connect to database
include"config.php";
// file properties
$file = $_FILES['image']['tmp_name'];
if (!isset($file))
echo "Please select a profile pic";
else
{
$image = addslashes(file_get_content($_FILES['image']['tmp_name']));
$image_name = addslashes($FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if ($image_size==FALSE)
echo "That isn't a image.";
else
{
$insert = mysql_query("INSERT INTO content VALUES ('','','','','','','','','','$image_name','$image',)");
}
}
?>
</body>
</html>
The reason for all the '', '', '', '' on the insert line is because I have the name in the 10th field and the image blob in the 11th and all the ones leading up to that are first name, last name and random stuff like that. How can I fix this? It is returning the error:
Fatal error: Call to undefined function file_get_content() in /home/content/34/9587634/html/WEBPAGE/UploadContent.php on line 22
I don't know what to do.
The code overlooks calling the function move_uploaded_file() which would check whether the indicated file is valid for uploading.
You may wish to review a simple example at:
http://www.w3schools.com/php/php_file_upload.asp
You need to add two new file one is index.html, copy and paste the below code and other is imageup.php which will upload your image
<form action="imageup.php" method="post" enctype="multipart/form-data">
<input type="file" name="banner" >
<input type="submit" value="submit">
</form>
imageup.php
<?php
$banner=$_FILES['banner']['name'];
$expbanner=explode('.',$banner);
$bannerexptype=$expbanner[1];
date_default_timezone_set('Australia/Melbourne');
$date = date('m/d/Yh:i:sa', time());
$rand=rand(10000,99999);
$encname=$date.$rand;
$bannername=md5($encname).'.'.$bannerexptype;
$bannerpath="uploads/banners/".$bannername;
move_uploaded_file($_FILES["banner"]["tmp_name"],$bannerpath);
?>
The above code will upload your image with encrypted name
Change function file_get_content() in your code to file_get_contents() . You are missing 's' at the end of function name. That is why it is giving undefined function error.
file_get_contents()
Remove last unnecessary comma after $image filed in line
"INSERT INTO content VALUES ('','','','','','','','','','$image_name','$image',)
I would recommend you to save the image in the server, and then save the URL in MYSQL database.
First of all, you should do more validation on your image, before non-validated files can lead to huge security risks.
Check the image
if (empty($_FILES['image']))
throw new Exception('Image file is missing');
Save the image in a variable
$image = $_FILES['image'];
Check the upload time errors
if ($image['error'] !== 0) {
if ($image['error'] === 1)
throw new Exception('Max upload size exceeded');
throw new Exception('Image uploading error: INI Error');
}
Check whether the uploaded file exists in the server
if (!file_exists($image['tmp_name']))
throw new Exception('Image file is missing in the server');
Validate the file size (Change it according to your needs)
$maxFileSize = 2 * 10e6; // = 2 000 000 bytes = 2MB
if ($image['size'] > $maxFileSize)
throw new Exception('Max size limit exceeded');
Validate the image (Check whether the file is an image)
$imageData = getimagesize($image['tmp_name']);
if (!$imageData)
throw new Exception('Invalid image');
Validate the image mime type (Do this according to your needs)
$mimeType = $imageData['mime'];
$allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($mimeType, $allowedMimeTypes))
throw new Exception('Only JPEG, PNG and GIFs are allowed');
This might help you to create a secure image uploading script with PHP.
Code source: https://developer.hyvor.com/php/image-upload-ajax-php-mysql
Additionally, I suggest you use MYSQLI prepared statements for queries to improve security.
Thank you.
Simple PHP file/image upload code on same page.
<form action="" method="post" enctype="multipart/form-data">
<table border="1px">
<tr><td><input type="file" name="image" ></td></tr>
<tr><td> <input type="submit" value="upload" name="btn"></td></tr>
</table>
</form>
<?php
if(isset($_POST['btn'])){
$image=$_FILES['image']['name'];
$imageArr=explode('.',$image); //first index is file name and second index file type
$rand=rand(10000,99999);
$newImageName=$imageArr[0].$rand.'.'.$imageArr[1];
$uploadPath="uploads/".$newImageName;
$isUploaded=move_uploaded_file($_FILES["image"]["tmp_name"],$uploadPath);
if($isUploaded)
echo 'successfully file uploaded';
else
echo 'something went wrong';
}
?>
Here is a basic example of how an image file with certain restrictions (listed below) can be uploaded to the server.
Existence of the image.
Image extension validation
Checks for image size.
<?php
$newfilename = "newfilename";
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$expensions= array("jpeg","jpg","png");
if(file_exists($file_name)) {
echo "Sorry, file already exists.";
}
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$newfilename.".".$file_ext);
echo "Success";
echo "<script>window.close();</script>";
}
else{
print_r($errors);
}
}
?>
<html>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit"/>
</form>
</body>
</html>
Credit to this page.
<?php
$filename=$_FILES['file']['name'];
$filetype=$_FILES['file']['type'];
if($filetype=='image/jpeg' or $filetype=='image/png' or $filetype=='image/gif')
{
move_uploaded_file($_FILES['file']['tmp_name'],'dir_name/'.$filename);
$filepath="dir_name`enter code here`/".$filename;
}
?>
<?php
$target_dir = "images/";
echo $target_file = $target_dir . basename($_FILES["image"]["name"]);
$post_tmp_img = $_FILES["image"]["tmp_name"];
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
$post_imag = $_FILES["image"]["name"];
move_uploaded_file($post_tmp_img,"../images/$post_imag");
?>
This code is very easy to upload file by php. In this code I am performing uploading task in same page that mean our html and php both code resides in the same file. This code generates new name of image name.
first of all see the html code
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="banner_image" >
<input type="submit" value="submit">
</form>
now see the php code
<?php
$image_name=$_FILES['banner_image']['name'];
$temp = explode(".", $image_name);
$newfilename = round(microtime(true)) . '.' . end($temp);
$imagepath="uploads/".$newfilename;
move_uploaded_file($_FILES["banner_image"]["tmp_name"],$imagepath);
?>

File Upload not working in IE and Firefox

I have the following code to upload a file to the server. For some weird reason, it does not work in IE and Mozilla Firefox but works perfect in Chrome. What is the problem?
PHP:
// Check post_max_size (http://us3.php.net/manual/en/features.file-upload.php#73762)
$POST_MAX_SIZE = ini_get('post_max_size');
$unit = strtoupper(substr($POST_MAX_SIZE, -1));
$multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));
if ((int)$_SERVER['CONTENT_LENGTH'] > $multiplier*(int)$POST_MAX_SIZE && $POST_MAX_SIZE)
HandleError('File exceeded maximum allowed size. Your file size <b>MUST NOT</b> be more than 100kb.');
// Settings
$save_path = 'uploads/'; //getcwd() . '/uploads/';The path were we will save the file (getcwd() may not be reliable and should be tested in your environment)
$upload_name = 'userfile'; // change this accordingly
$max_file_size_in_bytes = 102400; // 100k in bytes
$whitelist = array('jpg', 'png', 'gif', 'jpeg'); // Allowed file extensions
$blacklist = array('php', 'php3', 'php4', 'phtml','exe','txt','scr','cgi','pl','shtml'); // Restrict file extensions
$valid_chars_regex = 'A-Za-z0-9_-\s ';// Characters allowed in the file name (in a Regular Expression format)
// Other variables
$MAX_FILENAME_LENGTH = 260;
$file_name = $_FILES[$upload_name]['name'];
//echo "testing-".$file_name."<br>";
//$file_name = strtolower($file_name);
////////$file_extension = end(explode('.', $file_name));
$parts = explode('.', $file_name);
$file_extension = end($parts);
$uploadErrors = array(
0=>'There is no error, the file uploaded with success',
1=>'The uploaded file exceeds the upload max filesize allowed.',
2=>'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3=>'The uploaded file was only partially uploaded',
4=>'No file was uploaded',
6=>'Missing a temporary folder'
);
// Validate the upload
if (!isset($_FILES[$upload_name]))
**HandleError('No upload found for ' . $upload_name);**//THROWS UP ERROR HERE in IE and Firefox
else if (isset($_FILES[$upload_name]['error']) && $_FILES[$upload_name]['error'] != 0)
HandleError($uploadErrors[$_FILES[$upload_name]['error']]);
else if (!isset($_FILES[$upload_name]['tmp_name']) || !#is_uploaded_file($_FILES[$upload_name]['tmp_name']))
HandleError('Upload failed.');
else if (!isset($_FILES[$upload_name]['name']))
HandleError('File has no name.');
HTML:
<form name="upload" action="/upload" method="POST" ENCTYPE="multipart/formdata">
<table border="0" cellpadding="3" cellspacing="3" class="forms">
<tr>
<tr>
<td style="height: 26px" align="center">
<font class="font_upload_picture">'.MSG142.': <input class="font_upload_picture" type="file" name="userfile">
<input type=hidden name=MAX_FILE_SIZE value=102400 />
</td>
</tr>
<tr>
<td colspan="2">
<p align="center">
<input type="image" name="upload" value="upload" src="/img/layout/btnupload.gif" border="0" />
</p>
<p> </p>
<td><img src="/img/layout/takepicture.gif" border="0" /><br> '.MSG143.'</td>
</tr>
</table>
</form>
The enctype of the form should be multipart/form-data
You have errors in your html. You're missing closing tags for a tr and td tag. Also, close off your file upload input tag />.
Some of your logic is off:
if (!isset($_FILES[$upload_name]))
will always pass. For every <input type="file"> in your form, there'll be a matching $_FILES entry, whether a file was actually uploaded or not. If no file was uploaded to being with, then you'll get error code 4.
else if (isset($_FILES[$upload_name]['error']) && $_FILES[$upload_name]['error'] != 0)
You don't have to check if the error parameter is set. as long as $upload_name has a valid file field name in it, the error section will be there. You can check for $_FILES[$upload_name], though. in case your variable's set wrong.
You've commented it out, but you're checking for valid upload types by checking the user-provided filename. Remember that the ['type'] and ['name'] parameters in $_FILES are user-supplied and can be subverted. Nothing says a malicious user can't rename bad_virus.exe to cute_puppies.jpg and get through your 'validation' check. Always determine MIME type on the server, by using something like Fileinfo. That inspects the file's actual contents, not just the filename.
So, your upload validation should look something like:
if (isset($_FILES[$upload_name]) && ($_FILES[$upload_name]['error'] === UPLOAD_ERR_OK)) {
$fi = finfo_open(FILE_INFO_MIME_TYPE);
$mime = finfo_file($fi, $_FILES[$upload_name]['tmp_name']);
if (!in_array($valid_mime_type, $mime)) {
HandleError("Invalid file type $mime");
}
etc...
} else {
HandleError($uploadErrors[$_FILES[$upload_name]['error']]);
}

Categories