I want to put a restriction on the size of images uploaded.
Below I have condition for image size.
if ($_FILES["upload_attachment"]["size"] < 25000)) // Max File Size: 25KB
{
echo "File size exceeds maximum.";
}
I want insert condition in this code.
if ( $_FILES ) {
$files = $_FILES['upload_attachment'];
foreach ($files['name'] as $key => $value) {
if ($files['name'][$key]) {
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
$_FILES = array("upload_attachment" => $file);
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$post->ID);
}
}
}
}
Basically, you want to check that early, before you proceed with file processing, so you're not making the server do any work if it doesn't have to.
Also, FYI, the upload size is specified in bytes, so if you want 25KB, it will be (25 * 1024) = 25600 bytes.
To incorporate that condition, you could do this. It gets a little gnarly, so I've added comments on the closing brackets to note which closes what. fe = foreach
if ( $_FILES ) {//if files exist
if ($_FILES["upload_attachment"]["size"] < 25600) { // Max File Size: 25KB
//I would also recommend adding error handling early.
if ($_FILES['filename']['error'] > 0){
echo 'Error: ' . $_FILES['filename']['error'] . '<br />';
} else {
$files = $_FILES['upload_attachment'];
foreach ($files['name'] as $key => $value) {
if ($files['name'][$key]) {
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
$_FILES = array("upload_attachment" => $file);
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$post->ID);
}//fe
}//if
}//fe
}//if no errors (else)
} //if size ok
else {
echo "File size exceeds maximum.";
}
}//if $_FILES
Related
What's My Problem?
I am trying to use RecursiveDirectoryIterator Function in place of Scandir but not getting the required Json response.
I know this is a bit long piece of code but i really want to implement other features like directory permissions ,owner etc using iterator If someone can have a look at this i ll be very much thankful.
$path = dirname(__DIR__).'/files';
$dirname = explode('/',$path);
$dirname = end($dirname);
Scan Dir Function:
function scan($path,$dirname){
$files = array();
// Is there actually such a folder/file?
if(file_exists($path)){
foreach(scandir($path) as $f) {
if(!$f || $f[0] == '.') {
continue; // Ignore hidden files
}
$ext_to_exclude = array('php','html','.htacces');
if(cmprExtension($f,$ext_to_exclude)) {
continue; // Ignore some extensions
}
if(is_dir($path . '/' . $f)) {
// The path is a folder
$files[] = array(
"name" => $f,
"type" => "folder",
"path" => $dirname.'/'.$f,
"items" => scan($path.'/'.$f, $dirname.'/'.$f) // Recursively get the contents of the folder
);
}
else {
// It is a file
$files[] = array(
"name" => $f,
"type" => "file",
"path" => $dirname.'/'.$f,
"size" => filesize($path.'/'.$f) // Gets the size of this file
);
}
}
}
return $files;
}
RecursiveDirectoryiterator Function:
function scanRDI($path){
$rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS));
$files = array();
foreach ($rii as $file){
if($file->isDir()) {
// The path is a folder
$files[] = array(
"name" => $file->getFilename(),
"type" => "folder",
"path" => $file->getPathname(),
"items" => scanRDI($file->getPath())
);
}
else {
// It is a file
$files[] = array(
"name" => $file->getFilename(),
"type" => "file",
"path" => $file->getPathname(),
"size" => $file->getSize() // Gets the size of this file
);
}
}
return $files;
}
Json Endoing:
header('Content-type: application/json');
echo json_encode(array(
"name" => $dirname,
"type" => "folder",
"path" => $dirname,
"items" => scan($path) OR scanRDI($path)
));
Json responses:(In jsonviewer change view to code from Right panel)
For Scandir : https://codebeautify.org/jsonviewer/cb94493e
For RDI : https://codebeautify.org/jsonviewer/cb9e1297
How to add a progress bar on my uploading page?
I will be using A Wordpress template to integrate the uploader.
This is the uploader code I have right now:
global $post;
/*Video Uploading*/
if ( isset($_FILES['upload_attachment']) ) {
$count = '0';
$files = $_FILES['upload_attachment'];
foreach ($files['name'] as $key => $value) {
if ($files['name'][$key]) {
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
$_FILES = array("upload_attachment" => $file);
foreach ($_FILES as $file => $array) {
$newupload = betube_insert_attachment($file,$post->ID);
$attachvideo = wp_get_attachment_url( $newupload);
add_post_meta($post_id, 'jtheme_video_file', $attachvideo);
add_post_meta($post_id, '_video_thumbnail', $newupload);
set_post_thumbnail( $post_id, $newupload );
$count++;
}
}
}
}
To add progressbar you must have to upload file with jquery/ajax. There is one default javascript event listener called 'progress' which is used to increment progress bar. Here is a full working example, but make sure as you are working in wordpress so ajax php code will be changed as per your requirement. demo: http://theonlytutorials.com/jquery-ajax-file-upload-with-percentage-progress-bar/
I am using this PHP Code:
foreach ($_FILES['ticket_files']['name'] as $key => $value)
{
if(!empty($_FILES['ticket_files']))
{
}
}
But if the file input is blank, it still thinks that there is a file there and runs the code.
foreach ($_FILES['ticket_files']['name'] as $key => $value)
{
if (count($_FILES['ticket_files']) > 0)
{
}
}
Try this instead of what you have now.
try this
foreach ($_FILES['ticket_files']['name'] as $key => $value)
{
if(!$_FILES['ticket_files']['error'][$key])
{
//Do Stuff
}
}
You can use this:
if (file_get_contents( $file_path ) == '')
{
// file is empty
}
You need check the contents of the file to see if it's empty.
foreach ($_FILES['ticket_files']['name'] as $key => $value)
{
if(!empty(file_get_contents($path . $_FILES['ticket_files']['name']))
{
//Do Stuff
}
}
If nothing is uploaded $_FILES array looks like:
Array ( [image] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) )
The error code 4 [error] => 4 indicates no file was uploaded and error code 0 indicates no error and file was uploaded. You can add below check instead of empty check.
if($_FILES['ticket_files']['error']==0) {
// file uploaded, process code here
}
I'm iterating over a folder and formatting its contents in a certain way.
I've to form an array from this set of strings:
home--lists--country--create_a_country.jpg
home--lists--country--list_countries.jpg
profile--edit--account.jpg
profile--my_account.jpg
shop--orders--list_orders.jpg
The array needs to look like this:
<?php
array(
'home' => array(
'lists' => array(
'country' => array(
'create_a_country.jpg',
'list_countries.jpg'
)
)
),
'profile' => array(
'edit' => array(
'account.jpg'
),
'my_account.jpg'
),
'shop' => array(
'orders' => array(
'list_orders.jpg',
)
);
The thing is, the depth of the array could be infinitely deep depending on how many '--' dividers the file name has. Here's what I've tried (assuming each string is coming from an array:
$master_array = array();
foreach($files as $file)
{
// Get the extension
$file_bits = explode(".", $file);
$file_ext = strtolower(array_pop($file_bits));
$file_name_long = implode(".", $file_bits);
// Divide the filename by '--'
$file_name_bits = explode("--", $file_name_long);
// Set the file name
$file_name = array_pop($file_name_bits).".".$file_ext;
// Grab the depth and the folder name
foreach($file_name_bits as $depth => $folder)
{
// Create sub-arrays as the folder structure goes down with the depth
// If the sub-array already exists, don't recreate it
// Place $file_name in the lowest sub-array
// .. I'm lost
}
}
Can anyone shed some light on how I might do this? All insight appreciated.
w001y
Try this:
$files=array("home--lists--country--create_a_country.jpg","home--lists--country--list_countries.jpg","profile--edit--account.jpg","profile--my_account.jpg","shop--orders--list_orders.jpg");
$master_array=array();
foreach($files as $file)
{
$file=explode("--",$file);
$cache=end($file);
while($level=prev($file))
{
$cache=array($level=>$cache);
}
$master_array=array_merge_recursive($master_array,$cache);
}
print_r($master_array);
Live demo
Model function:
public function file_upload($folder, $allowed_type, $max_size = 0, $max_width = 0, $max_height = 0)
{
$folder = $this->path . $folder;
$files = array();
$count = 0;
foreach ($_FILES as $key => $value) :
$file_name = is_array($value['name']) ? $value['name'][$count] : $value['name'];
$file_name = $this->global_functions->char_replace($file_name, '_');
$count++;
$config = array(
'allowed_types' => $allowed_type,
'upload_path' => $folder,
'file_name' => $file_name,
'max_size' => $max_size,
'max_width' => $max_width,
'max_height' => $max_height,
'remove_spaces' => TRUE
);
$this->load->library('image_lib');
$this->image_lib->clear();
$this->load->library('upload');
$this->upload->initialize($config);
if (!$this->upload->do_upload($key)) :
$error = array('error' => $this->upload->display_errors());
var_dump($error);
return FALSE;
else :
$file = $this->upload->data();
$files[] = $file['file_name'];
endif;
endforeach;
if(empty($files)):
return FALSE;
else:
return implode(',', $files);
endif;
}
This function is working partially. Files are being uploaded to the selected folder, but I am getting this error: You did not select a file to upload. and getting FALSE as a result? What seems to be a problem? (form is using form_open_multipart)
Please make sure that you have this name of your file tag field:
$key='userfile' //which is name of input type field name
Are any of your file inputs empty when this happens? $_FILES will contain an array of "empty" data if there is no file specified for the input. For example, my file input name is one, and I submitted it without specifying a file:
Array
(
[one] => Array
(
[name] =>
[type] =>
[tmp_name] =>
[error] => 4
[size] => 0
)
)
You should check if the file data is empty before processing the upload. PHP's is_uploaded_file() is useful for this.