Hello! I have file upload that I want to upload only six images not less not more only six images with the PNG and JPG types i have written the below code.
But that is giving this below error please some one check my code and find the mistakes.
"Warning: preg_match() expects parameter 2 to be string, array given in C:\xampp\htdocs\hiddenprocess.php on line 21
Your Images Must Be JPG OR PNG And equal to six images
Warning: preg_match() expects parameter 2 to be string, array given in C:\xampp\htdocs\hiddenprocess.php on line 21
Your Images Must Be JPG OR PNG And equal to six images"
HTML Code:
<form name="myWebForm" action="hiddenprocess.php" method="post" enctype="multipart/form-data">
<input type="file" name="Upload_Property_Images[]" multiple="multiple"/>
<input type="submit" name="submit" value="Upload_Images" style="cursor:pointer;"/>
</form>
Here is the PHP FILE UPLOAD CODE:
<?php
$imagename = $_FILES['Upload_Property_Images']['name'];
$imagetype = $_FILES["Upload_Property_Images"]['type'];
if (empty($imagename))
{
echo 'You have\'nt Entered Value for upload field';
exit();
}
else
{
$whitelist = array(".jpg",".png");
foreach ($whitelist as $item)
{
if(preg_match("/$item\$/i", $imagename) && count($imagename ==6))
{
//code for uploading goes in here
}
else
{
echo 'Your Images Must Be
-JPG OR PNG
-Only six images allowed';
}
}
}
?>
Try following:
// Process files one by one
foreach($_FILES as $file) {
// Allowed file types
$whitelist = array("jpg","png");
// Match uploaded file extension
if ( in_array(end(explode('.', $file['Upload_Property_Images']['name'])), $whitelist ) {
// Count total uploads
if (count($_FILES['Upload_Property_Images']) == 6) {
// Code here
} else {
// Count error
}
} else {
// File extension error
}
}
Related
I'm trying to get my image uploader to handle multiple files.
In my HTML I have added the array brackets to the name attribute and added the multiple attribute:
HTML
<input id="standard-upload-files" type="file" name="standard-upload-files[]" multiple>
PHP
I've reduced the code down, but the images aren't being processed and I'm getting the error message that displays in the else part of the code.
Any help as to why the files aren't being processed would be hugely appreciated.
if(isset($_POST['submit-images'])) {
$profileImage = $_POST['submit-images'];
foreach($_FILES['standard-upload-files']['name'] as $filename) {
if($_FILES['standard-upload-files']['error'] === 0 ) {
$temp = $_FILES['standard-upload-files']['tmp_name'];
// set base time and ID for all images before loop
$filebase = uniqid() . '_' . time();
// FULL SIZE IMAGE THAT WILL BE DOWNLOADED BY USERS
move_uploaded_file($temp, "images-download/{$filebase}");
} else {
$error[] = "Image failed to load please try again";
}
} // foreach
}
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";
}
I'm having troubles uploading a bunch of files from a form. I need to make the input fields separately, my form is something like this:
<form action="upload.php" method="post" id="form" name="form" enctype="multipart/form-data">
<input type="file" name="upload[]" >
<input type="file" name="upload[]" >
...(more inputs)
<input type="file" name="upload[]" >
<button id="submit-button">Upload</button>
</form>
I'm using jQuery 1.9 for this project for anything else but this upload, I can't seem to find anything that suits what I'm trying to do. I found a lot of multiple input stuff, but in that way I can't differenciate every file from one another, and I need to so save the url of every file to the right column in my DB.
I've used some of the code I've found on other similar questions but they doesn't seem to work. I've tried this one now :
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to exeicute all files
foreach ((array)$_FILES['upload']['name'] as $f => $name) {
if ($_FILES['upload']['error'][$f] == 4) {
continue; // Skip file if any error found
}
if ($_FILES['upload']['error'][$f] == 0) {
if ($_FILES['upload']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
continue; // Skip invalid file formats
}
else{ // No error found! Move uploaded files
if(move_uploaded_file($_FILES["upload"]["tmp_name"][$f], $path.$name))
$count++; // Number of successfully uploaded file
}
}
}
}
I just get plain nothing, and the file I'm trying to upload doesn't show up on the server. I've checked with php_info() and it seems that the upload is enabled, and since I'm uploading a .pdf with just "Test" written on it about 7kb, I think the size is not the problem here.
I hope you guys can help me out, thanks.
UPDATE
I've removed the (array) casting and I have the following error:
Warning: Invalid argument supplied for foreach() in path_of_file
You are missing very important element in this which is enctype.
enctype='multipart/form-data'
Use this in your form tag and check again.
<form action="upload.php" method="post" enctype='multipart/form-data' id="form" name="form">
-> For your error, use the following code (updated) to upload multiple images
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to exeicute all files
foreach ($_FILES['username']['name'] as $f => $name) {
$path = 'uploads'; //path of directory
if ($_FILES['username']['error'][$f] == 4) {
continue; // Skip file if any error found
} else {
if ($_FILES['username']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
continue; // Skip invalid file formats
}
else {
// No error found! Move uploaded files
//$name_of_file = $_FILES['username']['name'][$f];
$temp_name = $_FILES['username']['tmp_name'][$f]; //[$count];
move_uploaded_file($temp_name, "$path/"."$name");
$count++; // Number of successfully uploaded file
}
}
}
}
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.
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}