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
}
Related
First off, the upload folder is given 777, and my old upload script works, so the server accepts files. How ever this is a new destination.
I use krajee bootstrap upload to send the files. And I receive a Jason response. The error seems to be around move uploaded file. I bet it's a simple error from my side, but I can't see it.
<?php
if (empty($_FILES['filer42'])) {
echo json_encode(['error'=>'No files found for upload.']);
// or you can throw an exception
return; // terminate
}
// get the files posted
$images = $_FILES['filer42'];
// a flag to see if everything is ok
$success = null;
// file paths to store
$paths= [];
// get file names
$filenames = $images['name'];
// loop and process files
for($i=0; $i < count($filenames); $i++){
$ext = explode('.', basename($filenames[$i]));
$target = "uploads" . DIRECTORY_SEPARATOR . md5(uniqid()) . "." . array_pop($ext);
if(move_uploaded_file($_FILES["filer42"]["tmp_name"][$i], $target)) {
$success = true;
$paths[] = $target;
} else {
$success = false;
break;
}
}
// check and process based on successful status
if ($success === true) {.
$output = [];
$output = ['uploaded' => $paths];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];
// delete any uploaded files
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 think field name is the issue. Because you are getting image name with filer42 and upload time, you are using pictures.
Please change
$_FILES["pictures"]["tmp_name"][$i]
to
$_FILES["filer42"]["tmp_name"][$i]
And check now, Hope it will work. Let me know if you still get issue.
The error is not in this script but in the post.
I was using <input id="filer42" name="filer42" type="file">
but it have to be <input id="filer42" name="filer42[]" type="file" multiple>
as the script seems to need an arrey.
It works just fine now.
how can I check that user has selected at-least one file for upload in below code ?
i have tried with in_array, isset, !empty functions but no success
please note that userfile input is array in html
if(!empty($_FILES['userfile']['tmp_name'])){
$upload_dir = strtolower(trim($_POST['name']));
// Create directory if it does not exist
if(!is_dir("../photoes/". $upload_dir ."/")) {
mkdir("../photoes/". $upload_dir ."/");
}
$dirname = "../photoes/".$upload_dir;
for($i=0; $i < count($_FILES['userfile']['tmp_name']);$i++)
{
// check if there is a file in the array
if(!is_uploaded_file($_FILES['userfile']['tmp_name'][$i]))
{
$messages[] = 'No file selected for no. '.$i.'field';
}
/*** check if the file is less then the max php.ini size ***/
if($_FILES['userfile']['size'][$i] > $upload_max)
{
$messages[] = "File size exceeds $upload_max php.ini limit";
}
// check the file is less than the maximum file size
elseif($_FILES['userfile']['size'][$i] > $max_file_size)
{
$messages[] = "File size exceeds $max_file_size limit";
}
else
{
// copy the file to the specified dir
if(#copy($_FILES['userfile']['tmp_name'][$i],$dirname.'/'.$_FILES['userfile']['name'][$i]))
{
/*** give praise and thanks to the php gods ***/
$messages[] = $_FILES['userfile']['name'][$i].' uploaded';
}
}
}
}else{
$messages[] = 'No file selected for upload, Please select atleast one file for upload';
dispform();
}
Here's how I do it its a couple of if's and I use a for loop as I allow multiple file uploads from a single drop down but its the if's that are more important to you
$uploaded = count($_FILES['userfile']['name']);
for ($i=0;$i<$uploaded;$i++) {
if (strlen($_FILES['userfile']['name'][$i])>1) {
// file exists so do something
} else {
//file doesn't exist so do nothing
}
}
You'll note I compare against the name element of the global $_FILES this is because you should never be able to upload a file without a name which also applies for no file uploaded
Don't do it client side thats a dumb place to do validation as the user can simply turn js processing off in the browser or it can be blocked by certain addons etc or intercepted and altered via firebug and various browser search hijacking toolbars etc.
Anything like this should always be done server side!
finally I found the answer, I am giving it here for other users,
I have 5 keys in html input array so array index is up to 4
if(!empty($_FILES['userfile']['tmp_name'][0]) or !empty($_FILES['userfile']['tmp_name'][1]) or !empty($_FILES['userfile']['tmp_name'][2]) or !empty($_FILES['userfile']['tmp_name'][3]) or !empty($_FILES['userfile']['tmp_name'][4])){
//at-least one file is selected so proceed to upload
}else{
//no file selected, notify user
}
There are several methods of doing this with PHP (e.g. Check if specific input file is empty), but with JS it's faster and less expensive on the server. Using jQuery you can do this:
$.fn.checkFileInput = function() {
return ($(this).val()) ? true : false;
}
if ($('input[type="file"]').checkFileInput()) {
alert('yay');
}
else {
alert('gtfo!');
}
The purpose of the script is to change the names of of a list of images within a directory for an ecommerce site. So specifically when the script is rand a user will type in a word or phrase that they would like a set or list of files to be prefixed with. The script will iterate over each file changing the prefix and appending the next available number starting from zero.
I'd like to display/render on the page to the user what files have been changed. right now when the script is ran it displays the current files within the directory, and then it list the changed files and their names within the directory.
How can i get the file list only to display when the script has finish processing the new names?
Why does the script not append the proper incremented number to the file name? It renames files the following order:
abc0.jpg
abc1.jpg
abc10.jpg
abc11.jpg
abc12.jpg
abc13.jpg
<?php
$display_file_list;
//Allow user to put choose name
if (isset($_POST['file_prefix'])){
$the_user_prefix = $_POST['file_prefix'];
//open the current directory change this to modify where you are looking
$dir = opendir('.');
$i=0;
//Loop though all the files in the directory
while(false !==($file = readdir($dir)))
{
//This is the way we would like the page to function
//if the extention is .jpg
if(strtolower(pathinfo($file, PATHINFO_EXTENSION)) =='jpg')
{
//Put the JPG files in an array to display to the user
$display_file_list[]= $file;
//Do the rename based on the current iteration
$newName = $the_user_prefix.$i . '.jpg';
rename($file, $newName);
//increase for the next loop
$i++;
}
}
//close the directory handle
closedir($dir);
}else{
echo "No file prefix provided";
}
?>
<html>
<body>
<form action="<?=$_SERVER['PHP_SELF']?>" method="POST">
<input type="text" name="file_prefix"><br>
<input type="submit" value="submit" name="submitMe">
</form>
</body>
</html>
<?php
foreach ($display_file_list as $key => $value) {
echo $value. "<br>";
}
?>
"How can i get the file list only to display when the script has finish processing the new names?"
I think this will work for you;
$path = "path/to/files";
$files = glob("{$path}/*.jpg");
$files_renamed = array();
foreach ($files as $i => $file) {
$name = "{$path}/{$prefix}{$i}.jpg";
if (true === rename($file)) {
$files_renamed[] = $name;
}
}
print_r($files_renamed);
I am not real good at reading the code for uploading images via php/ajax so i am hoping a php guru can help me out. I am trying to take the image file name and if it has spaces in it then replace those spaces with an underscore "_"
The php code for uploading is this:
$file_name = ( isset($_REQUEST['ax-file-name']) && !empty($_REQUEST['ax-file-name']) )?$_REQUEST['ax-file-name']:'';
$currByte = isset($_REQUEST['ax-start-byte'])?$_REQUEST['ax-start-byte']:0;
if($is_ajax)//Ajax Upload, FormData Upload and FF3.6 php:/input upload
{
//we get the path only for the first chunk
$full_path = ($currByte==0) ? checkFileExits($file_name, $upload_path):$upload_path.$file_name;
//Just optional, avoid to write on exisiting file, but in theory filename should be unique from the checkFileExits function
$flag = ($currByte==0) ? 0:FILE_APPEND;
//formData post files just normal upload in $_FILES, older ajax upload post it in input
$post_bytes = isset($_FILES['Filedata'])? file_get_contents($_FILES['Filedata']['tmp_name']):file_get_contents('php://input');
//some rare times (on very very fast connection), file_put_contents will be unable to write on the file, so we try until it writes
while(#file_put_contents($full_path, $post_bytes, $flag) === false)
{
usleep(50);
}
//delete the temporany chunk
if(isset($_FILES['Filedata']))
{
#unlink($_FILES['Filedata']['tmp_name']);
}
//if it is not the last chunk just return success chunk upload
if($isLast!='true')
{
echo json_encode(array('name'=>basename($full_path), 'size'=>$full_size, 'status'=>1, 'info'=>'Chunk uploaded'));
}
}
else //Normal html and flash upload
{
$isLast = 'true';//we cannot upload by chunks here so assume it is the last single chunk
$full_path = checkFileExits($file_name, $upload_path);
$result = move_uploaded_file(str_replace(" ", "_",$_FILES['Filedata']['tmp_name']), $full_path);//make the upload
if(!$result) //if any error return the error
{
echo json_encode( array('name'=>basename($full_path), 'size'=>$full_size, 'status'=>-1, 'info'=>'File move error') );
return false;
}
}
I've already tried the following (with str_replace(" ", "_", $nameoffile):
$post_bytes = isset($_FILES['Filedata'])? file_get_contents(str_replace(" ", "_",$_FILES['Filedata']['tmp_name'])):file_get_contents('php://input');
That seems to do nothing to rename it. So where am i missing it at?
The problem in your code is , you are trying to rename the temporary name of image file not the actual name
move_uploaded_file(str_replace(" ", "_",$_FILES['Filedata']['tmp_name']), $full_path);//make the upload
So you have to remove the str_replace from temporary name and append this to actual name like this.
move_uploaded_file($_FILES['Filedata']['tmp_name'], str_replace(" ", "_",$full_path));//make the upload
Hope it clarifies your doubt.
I have a simple file uploader, which thanks to stackoverflow is now fully working, however when I copied the PHP code across to my main layout, once initialised to upload a file, but it is wrong format or size and it echos the error, it breaks the HTML below it. Im thinking its to do with the "exit;" after each echo? but could be wrong.
<?php
if($_POST['upload']) {
if($_FILES['image']['name'] == "")
{
#there's no file name return an error
echo "<br/><b>Please select a file to upload!\n</b>";
exit;
}
#we have a filename, continue
#directory to upload to
$uploads = '/home/habbonow/public_html/other/quacked/photos';
$usruploads = 'photos';
#allowed file types
$type_array = array(image_type_to_mime_type(IMAGETYPE_JPEG), image_type_to_mime_type(IMAGETYPE_GIF), image_type_to_mime_type(IMAGETYPE_PNG), 'image/pjpeg');
if(!in_array($_FILES['image']['type'], $type_array))
{
#the type of the file is not in the list we want to allow
echo "<br/><b>That file type is not allowed!\n</b>";
exit;
}
$max_filesize = 512000;
$max_filesize_kb = ($max_filesize / 1024);
if($_FILES['image']['size'] > $max_filesize)
{
#file is larger than the value of $max_filesize return an error
echo "<br/><b>Your file is too large, files may be up to ".$max_filesize_kb."kb\n</b>";
exit;
}
$imagesize = getimagesize($_FILES['image']['tmp_name']);
#get width
$imagewidth = $imagesize[0];
#get height
$imageheight = $imagesize[1];
#allowed dimensions
$maxwidth = 1024;
$maxheight = 1024;
if($imagewidth > $maxwidth || $imageheight > $maxheight)
{
#one or both of the image dimensions are larger than the allowed sizes return an error
echo "<br/><b>Your file is too large, files may be up to ".$maxwidth."px x ".$maxheight."px in size\n</b>";
exit;
}
move_uploaded_file($_FILES['image']['tmp_name'], $uploads.'/'.$_FILES['image']['name']) or die ("Couldn't upload ".$_FILES['image']['name']." \n");
echo "<br/>The URL to your photo is <b>" . $usruploads . "/" . $_FILES['image']['name'] . "</b>. Please use this when defining the gallery photos";
}
?>
<form name="uploader" method="post" action="" enctype="multipart/form-data">
<input type="file" name="image" style="width:300px;cursor:pointer" />
<input type="submit" name="upload" value="Upload Image" />
</form>
Indeed, when you call exit; it means "immediately stop all processing; this script is finished." Anything that comes after it — including HTML — will not be interpreted.
A better organization would be to make this code a function, to the effect of:
function uploadMyStuffPlease() {
if($_POST['upload']) {
if($_FILES['image']['name'] == "")
{
#there's no file name return an error
echo "<br/><b>Please select a file to upload!\n</b>";
return;
}
#we have a filename, continue
// ....
}
Now you can simply call uploadMyStuffPlease(), which will do as much processing as it can, and perhaps return early in the event of an error. Either way, the function will return, and so the rest of your script (including that HTML) can still be interpreted.
If you call exit; your PHP script won't be able to output anything anymore. That's why the layout is broken.
You should maybe try to keep the HTML parts out of your PHP code and especially avoid opening tags that you don't close afterwards (i.e. divs or anything).
That being said, it's probably safest to just put everything into a function that won't exit the script when finished (see other's posts).
if(isset($_POST['upload'])){
OR
if(!empty($_POST['upload'])){
And remove exit...