Here is the form
form action="index.php" method="POST" enctype="multipart/form-data" >
<input type="file" name="image[]" multiple="multiple">
<input type="submit" value="upload">
</form>
I am trying to only run my code when only when if(!empty($_FILES['image'])){ but for some reason the array is not empty upon submitting no files and only clicking submit.
Here is the rest of the code if that will help, thanks.
<html>
Image Upload
<form action="index.php" method="POST" enctype="multipart/form-data" >
<input type="file" name="image[]" multiple="multiple">
<input type="submit" value="upload">
</form>
<?php
include 'connect.php';
if(!empty($_FILES['image'])){
echo $_FILES['image']['error'];
$allowed = array('jpg', 'gif', 'png', 'jpeg');
$count = 0;
foreach($_FILES['image']['name'] as $key => $name){
$image_name = $name;
$tmp = explode('.', $image_name);
$image_extn = strtolower(end($tmp)); //can only reference file
$image_temp = $_FILES['image']['tmp_name'][$count];
$filesize = filesize($_FILES['image']['tmp_name'][$count]);
$count = $count +1;
if(count($_FILES['image']['tmp_name']) > 5){
echo "You can upload a maximum of five files.";
break;
}
else if(in_array($image_extn, $allowed) === false){
echo $name." is not an allowed file type<p></p>";
}
else if($filesize > 1024*1024*0.3){
echo $name." is too big, can be a maximum of 3MB";
}
else{
$image_path = 'images/' . substr(md5($name), 0, 10) . '.' . $image_extn;
move_uploaded_file($image_temp, $image_path);
mysql_query("INSERT INTO store VALUES ('', '$image_name', '$image_path')") or die(mysql_error());
$lastid = mysql_insert_id();
$image_link = mysql_query("SELECT * FROM store WHERE id = $lastid");
$image_link = mysql_fetch_assoc($image_link);
$image_link = $image_link['image'];
echo "Image uploaded.<p></p> Your image: <p></p><a href = $image_link>$image_path</a>";
}
}
}
else{
echo "Please select an image.";
}
?>
This is how $_FILES array looks like when nothing uploaded
Array ( [image] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) )
So it's never empty.
The error code 4 [error] => 4 indicates no file was uploaded and error code 0 indicates no error and file was uploaded so you can check
if($_FILES['image']['error']==0) {
// file uploaded, process code here
}
Here is another answer on SO.
Use the is_uploaded_file PHP function instead:
if(is_uploaded_file($_FILES['image']['tmp_name'])) {
//code here
}
http://php.net/manual/en/function.is-uploaded-file.php
You should first of all take a look into the PHP manual because - you're not the first one with that problem - the solution has been written in there:
If no file is selected for upload in your form, PHP will return $_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name'] as none.
So if you actually want to find out if any file for the image element has has been submitted, check for it:
$noFile = $_FILES['image']['size'][0] === 0
&& $_FILES['image']['tmp_name'][0] === '';
Yes, that simple it is.
The test you used:
empty($_FILE);
will only tell you if the whole form has been submitted or not. So an example in full:
$submitted = empty($_FILE);
if ($submitted) {
$noFile = $_FILES['image']['size'][0] === 0
&& $_FILES['image']['tmp_name'][0] === '';
if ($noFile) {
...
}
}
Check value is not null:
in_array(!null,$_FILES['field_name']['name'])
if($_FILES['image']['error'] === UPLOAD_ERR_OK) {
// Success code Goes here ..
}
UPLOAD_ERR_OK returns value 0 if there is no error, the file was uploaded successfully.
http://php.net/manual/en/features.file-upload.post-method.php
If no file is selected for upload in your form, PHP will return
$_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name']
as none.
You get an array entry per "file" upload field, even if the user didn't select a file to upload.
I have confronted this issue with a multiple file input.
What I found to be working for checking if any file has been selected is:
<?php
$size_sum = array_sum($_FILES['img']['size']);
if ($size_sum > 0) {
// at least one file has been uploaded
} else {
// no file has been uploaded
}
?>
if(!empty($_FILES['image']['name'][0]) || !empty($_FILES['image']['name'][1]) ||
!empty($_FILES['image']['name'][2]))
or
for($1=0;$i<count($_FILES['image']);$i++){
if(!empty($_FILES['image']['name'][$i])){
// do something
}
}
if(isset($_FILES['file'])){//do some thing here}
Related
Hello I am trying to check the size of a file in PHP but it does not seem to work. My input page is
<html>
<title>File Upload</title>
<body>
<h1>
Upload Files
</h1>
<form action = "yes.php" method = "POST" enctype="multipart/form-data">
Upload your file
<input type = "file" name = "file" id = "fileToUpload">
<input type ="submit" name ="submit" value = "Start Upload">
</form>
</body>
</html>
This is the yes.php
<?php
$filename = $_FILES["file"]["name"];
$filesize = $_FILES["file"]["size"];
if (isset($_POST["submit"])) {
echo "$filename";
echo "\n$filesize";
if ($filesize < 4) {
echo "good";
} else {
echo "bad";
}
}
?>
It outputs
disc.mp4 0good
The file disc.mp4 is 5.8 MB but it returns as 0 MB even when it correctly identifies the name of the file. How can I fix this?
The different keys of the $_FILES array are explained here. Your code is taking for granted that every script invocation contains a valid file upload, which of course if often untrue: just open yes.php in your browser and you'll see (or you should see) lots of error messages. You're also making a strange check: the upload is valid if the file size is 0 to 3 bytes :-!
The bare minimum you need is:
Accommodate the fact that $_FILES['file'] may or may not exist.
Verify whether the upload succeeded.
If you expect a 5.8 MB file, don't require it to have an arbitrary smaller size.
Following you code style, I'd be something like:
<?php
$error = $_FILES["file"]["error"] ?? null;
$filename = $_FILES["file"]["name"] ?? null;
$filesize = $_FILES["file"]["size"] ?? null;
$expected_size = 5.8 * 1024 * 1024; # Assuming you want to enforce this for some reason
if ($error === UPLOAD_ERR_OK) {
echo "$filename";
echo "\n$filesize";
if ($filesize != $expected_size) {
echo "good";
} else {
echo "bad";
}
} elseif($error !== UPLOAD_ERR_NO_FILE) {
echo "upload failed";
}
Am doing multiple file upload in the controller but the file doesn't get uploaded
controller code: for the upload
$images = $_FILES['evidence'];
$success = null;
$paths= ['uploads'];
// get file names
$filenames = $images['name'];
// loop and process files
for($i=0; $i < count($filenames); $i++){
//$ext = explode('.', basename($filenames[$i]));
$target = "uploads/cases/evidence".DIRECTORY_SEPARATOR . md5(uniqid()); //. "." . array_pop($ext);
if(move_uploaded_file($images['name'], $target)) {
$success = true;
$paths[] = $target;
} else {
$success = false;
break;
}
echo $success;
}
// check and process based on successful status
if ($success === true) {
$evidence = new Evidence();
$evidence->case_ref=$id;
$evidence->saved_on=date("Y-m-d");
$evidence->save();
$output = [];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];
foreach ($paths as $file) {
unlink($file);
}
} else {
$output = ['error'=>'No files were processed.'];
}
// return a json encoded response for plugin to process successfully
echo json_encode($output);
I have tried var_dump($images['name'] and everything seems okay the move file does not upload the file
Check what you obtain in $_FILES and in $_POST and evaluate your logic by these result...
The PHP manual say this function return false when the filename is checked to ensure that the file designated by filename and is not a valid filename or the file can be moved for some reason.. Are you sure the filename generated is valid and/or can be mooved to destination?
this is the related php man php.net/manual/en/function.move-uploaded-file.php
Have you added enctype attribute to form tag?
For example:
<form action="demo_post_enctype.asp" method="post" enctype="multipart/form-data">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
I am creating simple file upload (for pictures). I tried in Opera and in FireFox and uploading is working fine. But when I upload via Google Chrome, picture is not uploaded. Can you please tell me where is problem:
here is php script that is used for storing picture in database
<?php
$id=$_SESSION['user_id'];
$user_id=$_SESSION['user_id'];
$album_id=$_POST['album'];
$max_size = 500; // Sets maxim size allowed for the uploaded files, in kilobytes
// sets an array with the file types allowed
$allowtype = array('bmp', 'gif', 'htm', 'html', 'jpg', 'jpeg', 'mp3', 'pdf', 'png', 'rar', 'zip');
// if the folder for upload (defined in $updir) doesn't exist, tries to create it (with CHMOD 0777)
/*if (!is_dir($updir)) mkdir($updir, 0777);*/
/** Loading the files on server **/
$result = array(); // Array to store the results and errors
// if receive a valid file from server
if (isset ($_FILES['files'])) {
// checks the files received for upload
$file_name=$_FILES['files']['name'];
$file_type=$_FILES['files']['type'];
$file_size=$_FILES['files']['size'];
$file_tmp=$_FILES['files']['tmp_name'];
for($f=0; $f<count($_FILES['files']['name']); $f++) {
$file_name = $_FILES['files']['name'][$f];
$random_name=rand();
// checks to not be an empty field (the name of the file to have more then 1 character)
if(strlen($file_name)>1) {
// checks if the file has the extension type allowed
$type=explode('.', $file_name);
$type=end($type);
if (in_array($type, $allowtype)) {
// checks if the file has the size allowed
if ($_FILES['files']['size'][$f]<=$max_size*1000) {
// If there are no errors in the copying process
if ($_FILES['files']['error'][$f]==0) {
$query = mysql_query("SELECT username from users WHERE id = '$id' ");
while($run=mysql_fetch_array($query)){
$username=$run['username'];
}
$query = mysql_query("SELECT album.name an from album WHERE album.id = '$album_id' ");
while($run=mysql_fetch_array($query)){
$album_name=$run['an'];
}
mysql_query("INSERT INTO photos VALUE ('', '$album_id', '$random_name.jpg', '$user_id')");
// Sets the path and the name for the file to be uploaded
// If the file cannot be uploaded, it returns error message
if (move_uploaded_file ($_FILES['files']['tmp_name'][$f],"./users/".$username."/".$album_name."/".$random_name.".jpg")) {
/*$result[$f] = ' The file could not be copied, try again';*/
$result[$f] = '<b>'.$file_name.'</b> - OK';
}
else {
$result[$f] = ' The file could not be copied, try again';
}
}
}
else { $result[$f] = 'The file <b>'. $file_name. '</b> exceeds the maximum allowed size of <i>'. $max_size. 'KB</i>'; }
}
else { $result[$f] = 'File type extension <b>.'. $type. '</b> is not allowed'; }
}
}
// Return the result
$result2 = implode('<br /> ', $result);
echo '<h4>Files uploaded:</h4> '.$result2;
}
?>
and here is form that is used for picture uploading:
<form id="uploadform" action="uploaderimg.php" method="post" enctype="multipart/form-data" target="uploadframe" onSubmit="uploading(this); return false">
<br>
Select album:
<select name="album">
<?php
$query=mysql_query("SELECT id, name, user_id FROM album WHERE user_id = '$id'");
while($run=mysql_fetch_array($query)){
$album_id=$run['id'];
$album_name=$run['name'];
$album_user = $run['user_id'];
echo "<option value='$album_id'>$album_name</option>";
}
?>
</select>
<br /><br />
<h1>Chose your photo/s</h1>
<br>
<input type="file" name="files[]" />
<input type="submit" value="UPLOAD" id="sub" />
</form>
EDIT:
THis is error according to PHP(it's in first script that store uploaded file):
Notice: Undefined index: album in..
After conversing with the OP, the problem lay in this line:
<form id="uploadform" action="uploaderimg.php" method="post" enctype="multipart/form-data" target="uploadframe" onSubmit="uploading(this); return false">
Where onSubmit="uploading(this); return false" was at fault.
Working on a little upload script here. I'm trying to check if the uploaded image really is an image and not just a renamed PHP file.
When the script is posted I can print the array with
foreach ($_FILES['images']['name'] as $key => $value){
print_r(getimagesize($_FILES['images']['tmp_name'][$key]));
That works just fine, so it won't return false. But even if I upload a file that is not an image, it won't give false. It just returns nothing at all, and the rest of my script just processes the thing like an image.
Could anyone tell me what I am doing wrong?
Upload
you can not use getimagesize on $_FILES['images']['tmp_name'][$key] directly .. you need to copy it into your system first before you can use it
Use $_FILES['images']['size'][$key] temporarily
Or
move_uploaded_file($_FILES['images']['tmp_name'][$key], $destination);
print_r(getimagesize($destination));
Fake Image
Please not that $_FILES['images']['type'][$key] can be faked
Using Fake image Headers
Example
file_put_contents("fake.png", base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAABGdBTUEAALGPC/xhBQAAAAZQTFRF////
AAAAVcLTfgAAAAF0Uk5TAEDm2GYAAAABYktHRACIBR1IAAAACXBIWXMAAAsSAAALEgHS3X78AAAAB3RJTUUH0gQCEx05cq
KA8gAAAApJREFUeJxjYAAAAAIAAUivpHEAAAAASUVORK5CYII='));
Uploading fake.png
array
'name' =>
array
0 => string 'fake.png' (length=8)
'type' =>
array
0 => string 'image/png' (length=9)
'tmp_name' =>
array
0 => string 'C:\Apache\xampp\tmp\php44F.tmp' (length=30)
'error' =>
array
0 => int 0
'size' =>
array
0 => int 167
Validate Image
Usage
var_dump ( getimagesizeReal ( "fake.png" ) );
Function Used
function getimagesizeReal($image) {
$imageTypes = array (
IMAGETYPE_GIF,
IMAGETYPE_JPEG,
IMAGETYPE_PNG,
IMAGETYPE_SWF,
IMAGETYPE_PSD,
IMAGETYPE_BMP,
IMAGETYPE_TIFF_II,
IMAGETYPE_TIFF_MM,
IMAGETYPE_JPC,
IMAGETYPE_JP2,
IMAGETYPE_JPX,
IMAGETYPE_JB2,
IMAGETYPE_SWC,
IMAGETYPE_IFF,
IMAGETYPE_WBMP,
IMAGETYPE_XBM,
IMAGETYPE_ICO
);
$info = getimagesize ( $image );
$width = #$info [0];
$height = #$info [1];
$type = #$info [2];
$attr = #$info [3];
$bits = #$info ['bits'];
$channels = #$info ['channels'];
$mime = #$info ['mime'];
if (! in_array ( $type, $imageTypes )) {
return false; // Invalid Image Type ;
}
if ($width <= 1 && $height <= 1) {
return false; // Invalid Image Size ;
}
if($bits === 1)
{
return false; // One Bit Image .. You don't want that ;
}
return $info ;
}
I'd like to recommend against trusting the results of getimagesize() when deciding whether to place the uploaded file anywhere in your document root. That's because PHP code embedded in GIF files (titled like image.gif.php) will be identified as images by getimagesize(), but serving them will run the PHP code inside them in addition to displaying the image. Here is some more information on the issue.
The article linked above recommends setting up a separate controller through which all the user uploaded files are served. Files read with readfile() are not parsed when accessed through the local filesystem.
Firstly, you can use getimagesize on $_FILES['images']['tmp_name'], so that's not an issue.
If you want to check if the file is an image, then try this:
if(isset($_POST['submit'])) {
$check = getimagesize($_FILES['images']['tmp_name']);
if($check !== false) {
echo 'File is an image - ' . $check['mime'];
}
else {
echo 'File is not an image';
}
}
You can simply use $_FILES['images']['type'] . it'll give you the type of file uploaded. Then check it againt octate stream or other executable file. If so then do not allow it.
#user1362916 If you are uploading multiple images with HTML then perhaps you need to add one more array like this.
if(isset($_POST['submit'])) {
$check = getimagesize($_FILES['images']['tmp_name'][$i]);
if($check !== false) {
echo 'File is an image - ' . $check['mime'];
}
else {
echo 'File is not an image';
}
}
Here check [i] because this is for multiple file upload.
Below is full script
<!DOCTYPE html>
<html>
<body>
<form action="#" method="post" enctype="multipart/form-data">
Select image to upload:
<input name="my_files[]" type="file" multiple="multiple" />
<input type="submit" value="Upload Image" name="submit">
</form>
<?php
if (isset($_FILES['my_files']))
{
$myFile = $_FILES['my_files'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i <$fileCount; $i++)
{
$error = $myFile["error"][$i];
if ($error == '4') // error 4 is for "no file selected"
{
echo "no file selected";
}
else
{
if(isset($_POST['submit'])) {
$check = getimagesize($_FILES['my_files']['tmp_name'][$i]);
if($check !== false) {
echo 'File is an image - ' . $check['mime'];
}
else {
echo 'File is not an image';
}
}
}
}
}
?>
</body>
</html>
am having some trouble with PHP on the webserver I am using.
I am sure the answer is obvious but for some reason it is eluding me completely.
I have a php file which uploads two files, a before and an after shot of the client.
The script on my server(localhost) works fine, it uploads the files, renames the files to a timestamp and puts the images into there folders for further sorting by another script.
Yet when I upload it to the webserver, and some files work (i.e mel.jpg, test.jpg) but files like IMG_0042.jpg do not work, Im sure the answer is something simple, but is completely eluding me.
Im thinking the underscore may have something to do with it, but cannot for the life of my figure it out, any help greatly appreciated,
thanks very much.
<?php
if(!isset($_COOKIE['auth'])) {
header("Location: login12.php");
exit();
}
$page_title="test";
include('header.html');
// Upload and Rename File
if (isset($_POST['submitted'])) {
$filenamebef = $_FILES["uploadbef"]["name"];
$filenameaft = $_FILES["uploadaft"]["name"];
$file_basename_bef = substr($filenamebef, 0, strripos($filenamebef, '.'));
$file_basename_aft = substr($filenameaft, 0, strripos($filenameaft, '.'));
// get file extention
$file_ext_bef = substr($filenamebef, strripos($filenamebef, '.'));
$file_ext_aft = substr($filenameaft, strripos($filenameaft, '.'));
// get file name
$filesize_bef = $_FILES["uploadbef"]["size"];
$filesize_aft = $_FILES["uploadaft"]["size"];
$allowed = array('image/pjpeg','image/jpeg','image/JPG','image/X-PNG','image/PNG','image /png','image/x-png');
if ((in_array($_FILES['uploadbef']['type'], $allowed)) && in_array($_FILES['uploadaft']['type'], $allowed)) {
if (($filesize_bef < 200000) && ($filesize_aft < 200000)){
// rename file
$date = date("mdy");
$time = date("His");
$timedate = $time . $date;
$newfilenamebef = $timedate . $file_ext_bef;
$newfilenameaft = $timedate . $file_ext_aft;
if ((file_exists("upload/images/before" . $newfilenamebef)) && (file_exists("uploads/images/after" . $newfilenameaft))) {
// file already exists error
echo "You have already uloaded this file.";
} else {
move_uploaded_file($_FILES["uploadbef"]["tmp_name"], "uploads/images/before/" . $newfilenamebef) && move_uploaded_file($_FILES["uploadaft"]["tmp_name"], "uploads/images/after/" . $newfilenameaft);
echo "File uploaded successfully.";
}
}
} elseif ((empty($file_basename_bef)) && (empty($file_basename_aft))) {
// file selection error
echo "Please select a file to upload.";
} elseif (($filesize_bef > 200000) && ($filesize_aft > 200000)) {
// file size error
echo "The file you are trying to upload is too large.";
} else {
// file type error
echo "Only these file typs are allowed for upload: " . implode(', ',$allowed);
unlink($_FILES["uploadbef"]["tmp_name"]);
unlink($_FILES["uploadaft"]["tmp_name"]);
}
}
echo $newfilenamebef;
echo $newfilenameaft;
?>
<form enctype="multipart/form-data" action="uploading.php" method="post">
<input type="hidden" value="MAX_FILE_SIZE" value="524288">
<fieldset>
<legend>Select a JPEG or PNG image of 512kb or smaller to be uploaded : </legend>
<p><b>Before</b> <input type="file" name="uploadbef" /></p>
<p><b>After</b> <input type="file" name="uploadaft" /></p>
</fieldset>
<div align="center"><input type="submit" name="submit" value="Submit" /></div>
<input type="hidden" name="submitted" value="TRUE" />
</form>
<?php
include('footer.html');
?>
You should but these two lines at the top of your index.php or bootstrap.php :
error_reporting( -1 );
ini_set( "display_errors" , 1 );
And see if some error messages turn up.
It is quite possible that problem is caused by wrong file permissions.
At a quick guess I would say that your localhost is not case sensitive, whereas your webserver is.
In other words, on your localhost IMG_12345.JPG is the same as img_12345.jpg. On your webserver, though, they are treated differently.
Without any actual reported errors, it's hard to be certain, but this is a common problem.
You're not checking for valid uploads properly. Something like the following would be FAR more reliable:
// this value is ALWAYS present and doesn't depend on form fields
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errmsgs = array();
if ($_FILES['uploadbef']['error'] !== UPLOAD_ERR_OK) {
$errs++;
$errmsgs[] = "'uploadebef' failed with code #" . $_FILES['uploadebef']['error'];
}
if ($_FILES['uploadaft']['error'] === UPLOAD_ERR_OK) {
$errs++;
$errmsgs[] = "'uploadeaft' failed wicode #" . $_FILES['uploadeaft']['error'];
}
if (count($errmsgs) > 0) {
print_r($errmsgs);
die();
}
... process the files here ...
}
As well, why re-invent the wheel to split up the file names?
$parts = path_info($_FILES['uploadaft']['name']);
$basename = $parts['basename'];
$ext = $parts['extension'];