How to select image sized between 100-500 kb? - php

I have a short PHP code to help me display random images from a specific folder. But now it seems to select any image in any size. I want those selected images are between 100-500 kb. If it's less than 100 kb or over 500 kb, the function won't select and display it.
Could you please tell me how to modify this code? Probably need to add some function.
<?php $randomdir = dir('images/random');
$count = 1;
$pattern="/(gif|jpg|jpeg|png)/";
while($file = $randomdir->read()) {
$ext = pathinfo($file, PATHINFO_EXTENSION);
if (preg_match($pattern, $ext)) {
$imagearray[$count] = $file;
$count++;
}
}
$random = mt_rand(1, $count - 1);
echo '<img src="images/random/'.$imagearray[$random].'" alt />';
?>

Try this one We have to set 2 conditions
$min = 100; //KB
$max = 500; //KB
if($_FILES['myfile']['size'] < $min * 1024 || $_FILES['myfile']['size'] > $max * 1024){
echo 'error';
}

Try now
<?php
$dir_name = 'images/random/';
$pattern="/(gif|jpg|jpeg|png)/";
$min = 100;
$max = 500;
$imagearray = array();
$scanned_directory = array_diff(scandir($dir_name), array('..', '.'));
$count = count($scanned_directory);
$ids = array_keys($scanned_directory);
$s = TRUE;
$stop = $count;
while( ($s === TRUE) && ($stop >=0))
{
$random = mt_rand(0, $count - 1);
$full_path_to_file = $dir_name.$scanned_directory[$ids[$random]];
$ext = pathinfo($full_path_to_file, PATHINFO_EXTENSION);
$file_size_kb = round(filesize($full_path_to_file)/1024);
if (preg_match($pattern, $ext) && ($file_size_kb>=$min && $file_size_kb<=$max))
{
$s = FALSE;
echo '<img src="'.$full_path_to_file.'" alt />';
}
$stop--;
}
?>

Related

Rename files while uploading with php

I have a html form + php for uploading 3 pdfs similarly. while uploading i have to cut the names of the files. For instance instead of AB_2020_02_02.pdf i want to have it changed in AB.pdf - for all three files simultaneously. I tried with rename($original_filename, substr($original_filename, 2) . '.pdf'); Any other ideas?
This is the entire code:
<?php
// Set Upload Path
$target_dir = '';
$_FILES = substr($_FILES, 2, strlen($_FILES) - 12);
if( isset($_FILES['fileUpload']['name'])) {
$total_files = count($_FILES['fileUpload']['name']);
for($key = 0; $key < $total_files; $key++) {
// Check if file is selected
if(isset($_FILES['fileUpload']['name'][$key])
&& $_FILES['fileUpload']['size'][$key] > 0) {
$original_filename = $_FILES['fileUpload']['name'][$key];
rename($original_filename, substr($original_filename, 2) . '.pdf');
$target = $target_dir . basename($original_filename);
$tmp = $_FILES['fileUpload']['tmp_name'][$key];
move_uploaded_file($tmp, $target);
}
}
}
?>
$target_dir = '';
if( isset($_FILES['fileUpload']['name'])) {
$total_files = count($_FILES['fileUpload']['name']);
for($key = 0; $key < $total_files; $key++) {
// Check if file is selected
if(isset($_FILES['fileUpload']['name'][$key])
&& $_FILES['fileUpload']['size'][$key] > 0) {
$original_filename = $_FILES['fileUpload']['name'][$key];
$rename = explode('_',$original_filename);
$target = $target_dir . $rename[0].".pdf";
$tmp = $_FILES['fileUpload']['tmp_name'][$key];
move_uploaded_file($tmp, $target);
}
}
}
Rename directly in move_uploaded_file(...)
<?php
// Set Upload Path
$target_dir = '';
$_FILES = substr($_FILES, 2, strlen($_FILES) - 12);
if( isset($_FILES['fileUpload']['name'])) {
$total_files = count($_FILES['fileUpload']['name']);
for($key = 0; $key < $total_files; $key++) {
// Check if file is selected
if(isset($_FILES['fileUpload']['name'][$key])
&& $_FILES['fileUpload']['size'][$key] > 0) {
$original_filename = $_FILES['fileUpload']['name'][$key];
$target = $target_dir . substr($original_filename, 2).'.pdf' ;
$tmp = $_FILES['fileUpload']['tmp_name'][$key];
move_uploaded_file($tmp, $target);
}
}
}
?>

Codeigniter File Upload Permit Only For Images not For Others

I have to file upload operation consecutive, first for images like gif|jpg|jpeg|png|svg and the second psd|rar|zip|doc|word|txt|xlsx|pdf
First one is working just fine, i can upload all images but the second, i can not upload any of these types but when i try to upload image on second segment it works.
if (isset($_FILES['content_images']['name'])) {
$count_files = count($_FILES['content_images']['name']);
for ($i = 0; $i < $count_files; $i++) {
$_FILES['image']['name'] = $_FILES['content_images']['name'][$i];
$_FILES['image']['type'] = $_FILES['content_images']['type'][$i];
$_FILES['image']['tmp_name'] = $_FILES['content_images']['tmp_name'][$i];
$_FILES['image']['error'] = $_FILES['content_images']['error'][$i];
$_FILES['image']['size'] = $_FILES['content_images']['size'][$i];
$config_images['upload_path'] = "./public/site/images/contents";
$config_images['allowed_types'] = 'gif|jpg|jpeg|png|svg';
$config_images['max_size'] = 5000;
$config_images['max_width'] = 7680;
$config_images['max_height'] = 4320;
$this->load->library("upload", $config_images);
if (!$this->upload->do_upload('image')) {
echo $this->upload->display_errors();
exit;
} else {
$data = $this->upload->data();
$path_images[] = "public/site/images/contents/".$data['file_name'];
}
}
}
if (isset($_FILES['content_files']['name'])) {
$count_files=count($_FILES['content_files']['name']);
for ($i = 0; $i < $count_files; $i++) {
$_FILES['file']['name'] = $_FILES['content_files']['name'][$i];
$_FILES['file']['type'] = $_FILES['content_files']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['content_files']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['content_files']['error'][$i];
$_FILES['file']['size'] = $_FILES['content_files']['size'][$i];
$config_files['upload_path'] = "./public/site/files/contents";
$config_files['allowed_types'] = 'psd|rar|zip|doc|word|txt|xlsx|pdf';
$config_files['max_size'] = 5000;
$config_files['max_width'] = 7680;
$config_files['max_height'] = 4320;
$this->load->library("upload",$config_files);
if (!$this->upload->do_upload('file')) {
foreach($path_images as $p){
unlink($p);
}
echo $this->upload->display_errors();
exit;
} else {
$data=$this->upload->data();
$path_files[] = "public/site/files/contents/".$data['file_name'];
}
}
}
I found the solution
For help :
You should load the library at the top for 1 time only, and then u should initialize it inside 'if condition'.
When you load upload library and config array inside first condition, when you pass to second condition upload library had already loaded and uses the first condition's config array.
$this->load->library("upload");
if(isset($_FILES['content_images']['name'])){
$count_files=count($_FILES['content_images']['name']);
for($i = 0;$i<$count_files;$i++){
$_FILES['image']['name'] = $_FILES['content_images']['name'][$i];
$_FILES['image']['type'] = $_FILES['content_images']['type'][$i];
$_FILES['image']['tmp_name'] = $_FILES['content_images']['tmp_name'][$i];
$_FILES['image']['error'] = $_FILES['content_images']['error'][$i];
$_FILES['image']['size'] = $_FILES['content_images']['size'][$i];
$config_images['upload_path'] = "./public/site/images/contents";
$config_images['allowed_types'] = 'gif|jpg|jpeg|png|svg';
$config_images['max_size'] = 5000;
$config_images['max_width'] = 7680;
$config_images['max_height'] = 4320;
$this->upload->initialize($config_images);
if(!$this->upload->do_upload('image')){
echo $this->upload->display_errors();
exit;
}else{
$data=$this->upload->data();
$path_images[] = "public/site/images/contents/".$data['file_name'];
}
}
}
if(isset($_FILES['content_files']['name'])){
$count_files=count($_FILES['content_files']['name']);
for($i = 0;$i<$count_files;$i++){
$_FILES['file']['name'] = $_FILES['content_files']['name'][$i];
$_FILES['file']['type'] = $_FILES['content_files']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['content_files']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['content_files']['error'][$i];
$_FILES['file']['size'] = $_FILES['content_files']['size'][$i];
$config_files['upload_path'] = "./public/site/files/contents";
$config_files['allowed_types'] = 'psd|rar|zip|doc|word|txt|xlsx|pdf';
$config_files['max_size'] = 5000;
$config_files['max_width'] = 7680;
$config_files['max_height'] = 4320;
$this->upload->initialize($config_files);
if(!$this->upload->do_upload('file')){
foreach($path_images as $p){
unlink($p);
}
echo $this->upload->display_errors();
exit;
}else{
$data=$this->upload->data();
$path_files[] = "public/site/files/contents/".$data['file_name'];
}
}
}

How to get 15 random images from a folder in Wordpress?

I need to get 15 random images from a folder and show them on a page:
I tried the following code, however it did not do what I wanted:
$string =array();
$filePath='wp-content/themes/tema/img-test/';
$dir = opendir($filePath);
while ($file = readdir($dir)) {
if (eregi("\.png",$file) || eregi("\.jpg",$file) || eregi("\.gif",$file) ) {
$string[] = $file;
}
}
while (sizeof($string) != 0){
$img = array_pop($string);
echo "<img src='$filePath$img' width='100px'/>";
}
So, you have all the files in $string array, that's good.
You can either use the rand() function to get some random integer in the arrays size:
$string = ['img1.jpg','img2.jpg','img3.jpg'];
$rand = rand(0,count($string)-1);
echo $string[$rand];
You would have to loop that.
Or, you could use array_rand() which will automate all that:
$string = ['img1.jpg','img2.jpg','img3.jpg'];
$amount = 3;
$rand_arr = array_rand($string, $amount);
for($i=0;$i<$amount;$i++) {
echo $string[$rand_arr[$i]] ."<br>";
}
You could do this using the glob() function native to PHP. It will get all files in a directory. Following that you can pick one file from the retrieved list.
$randomFiles = array();
$files = glob($dir . '/*.*');
$file = array_rand($files);
for ($i = 0; $i <= 15; $i++) {
$randomFiles[] = $files[$file];
}
Use this code. Your random image will be available in $arRandomFiles.
$filePath = 'wp-content/themes/tema/img-test/';
$files = glob($filePath. '*.{jpeg,gif,png}', GLOB_BRACE);
$arKeys = array_rand($files, 15);
$arRandomFiles = array();
foreach ($arKeys as $key) {
$arRandomFiles[] = $files[$key];
}
var_dump($arRandomFiles);
Simple function that handles that
<?php
function getImg( $path ) {
$filePath= $path . '*';
$imgs = glob( $filePath );
if( $imgs ) {
$i = 1;
foreach( $imgs as $img ) {
if( $i <= 15 ) {
$ext = pathinfo( $img, PATHINFO_EXTENSION );
if( in_array( $ext, array( 'jpg', 'jpeg', 'png', 'gif' ) ) )
$r[] = $img;
}
else
break;
$i++;
}
shuffle( $r );
return $r;
}
else
return array();
}
print_r( getImg( 'wp-content/themes/tema/img-test/' ) );
You can try function like:
function getRandomFile($directory)
{
$directoryIterator = new DirectoryIterator($directory);
$count = iterator_count($directoryIterator) - 2;
foreach ($directoryIterator as $fileInfo) {
$last = $fileInfo->getRealPath();
if ($fileInfo->isFile() && (rand() % $count == 0)) {
break;
}
}
return $last;
}

Generating a string of file names, alternative to global variable?

I'm creating a function where users can upload multiple images and upload them to the server. Using a global variable for this matter works, but I've heard global variables are bad especially in OOP. So, I'm wondering what a good alternative would be? (I'm a starting PHP programmer, any detailed information is appreciated)
Code:
function addImgToNieuws($images){
if (isset($images) && $images != "") {
$countFiles = count($images["name"]);
for ($i = 0; $i < $countFiles; $i++) {
$fileName = $images["name"][$i];
$fileType = $images["type"][$i];
$fileSize = $images["size"][$i];
$fileError = $images["error"][$i];
$fileTmp = $images["tmp_name"][$i];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
$db_file_name = rand(100000, 999999) . "." . $fileExt;
$output = $this->db->real_escape_string($db_file_name);
global $string;
$string .= ",$output";
$string = substr($string, 1);
}
echo $string;
}
}
function addImgToNieuws($images){
if (isset($images) && $images != "") {
throw new Exception("bad input bro");
}
$countFiles = count($images["name"]);
$db_names = array();
for ($i = 0; $i < $countFiles; $i++) {
$fileName = $images["name"][$i];
$fileType = $images["type"][$i];
$fileSize = $images["size"][$i];
$fileError = $images["error"][$i];
$fileTmp = $images["tmp_name"][$i];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
$db_file_name = rand(100000, 999999) . "." . $fileExt;
$db_names[] = $this->db->real_escape_string($db_file_name)
}
return $db_names;
}
Assuming you wanted to get the $db_names. It's a little bit odd to do the escaping here, I would delay it until the very moment you insert it in the query.
If you really wanted the $db_names as a string you can do:
echo join(",", $obj->addImgToNieuws($images));

error in upload form

hello i copyed 1 upload file source code with upload progress bar
its work if i delete foreach and make 1 file for upload
but i want have 5 file field in my form
this is my code now:
$upload_directory = "$fUllp/";
//5M
$allowsize = 5242880;
foreach($_FILES as $file) {
$n = $file['name'];
$s = $file['size'];
$t = $file['type'];
$tmp = $file['tmp_name'];
if (is_array($n)) {
$c = count($n);
for ($i=0; $i < $c; $i++) {
if($s <= $allowsize){
$filename = explode('.',$n);
$filetype = $filename[1];
if(!isset($filename[2])){
$glast = mysql_query("select id from up_guest order by id desc limit 1");
$flast = mysql_fetch_array($glast);
if($flast['id'] == '' or $flast['id'] <= 0){
$flast = 1;
}
else{
$flast = $flast['id'] + 1;
}
$time = time();
$filename = $flast.'.'.$filename[1];
if(in_array($t,$allow)){
if (move_uploaded_file($tmp, $upload_directory . $filename)) {
//insert db
//img full
$fullurl = $siteurl.'/'.$upload_directory.$filename;
//for sql
$fullurlsq = '/'.$upload_directory.$filename;
$fullurlsqt = '/'.$upload_directory.'t/'.$filename;
//img resize
$image = new SimpleImage();
$image->load($upload_directory.'/'.$filename);
$image->resizeToHeight(100);
$image->resizeToWidth(100);
$image->save($upload_directory.'/t/'.$filename);
//img koochik
$imgt = $upload_directory.'/t/'.$filename;
mysql_query("insert into up_guest(name,name_t,type,time,ip) values('$fullurlsq','$fullurlsqt','$filetype',$time,'$ip')");
print '<br><div class="system-message"><ul class="index_info"><li>توضیح: <span>فایل با موفقیت آپلود شد<bR /><div class="thumb_img">';
print "<img src=\"$imgt\"></div>";
//tbl1
print '<table border="0" width="100%" cellspacing="0" cellpadding="0" class="up_box_input"><tbody><tr><td class="btitle">لینک تصویر کوچک</td><td class="all_box_link"><textarea readonly="readonly" rows="2" cols="40" class="up_input" tabindex="1" onclick="this.select();">';
print "[url=$siteurl/][img]$imgt [/img][/url]</textarea></td></tr></tbody></table>";
//tbl2
print 'echo file detaid for user';
}//file upload she
else{
echo '<div class="site_error_msg">cant up</div>';
}
}//age allow bood un file
else{
echo '<div class="site_error_msg">extention not allowed</div>';
}
}//if noghte vasatesh nabood
else{
echo '<div class="site_error_msg">you not must have . in file name</div>';
}
}//if sizesh mojaz bood
else{
echo '<div class="site_error_msg">uploaded file is more than 5 MB</div>';
}//end my code
but
its run else in first IF
i mean
if(in_array($t,$allow)){
and run this else
else{
echo '<div class="site_error_msg">uploaded file is more than 5 MB</div>';
}//end my code
so its must something wrong with
these lines and its set file name size incorect
foreach($_FILES as $file) {
$n = $file['name'];
$s = $file['size'];
$t = $file['type'];
$tmp = $file['tmp_name'];
if (is_array($n)) {
$c = count($n);
for ($i=0; $i < $c; $i++) {
ok find my nooblish problem ! i must inter my file size and name under For like this
foreach($_FILES as $file) {
$n = $file['name'];
$s = $file['size'];
$t = $file['type'];
$tmp = $file['tmp_name'];
if (is_array($n)) {
$c = count($n);
for ($i=0; $i < $c; $i++) {
$ss = $s[$i];
$tmpp = $tmp[$i];
$nn = $n[$i];
$tt = $t[$i];
if($ss <= $allowsize){
$filename = explode('.',$nn);
$filetype = $filename[1];
if(!isset($filename[2])){
$glast = mysql_query("select id from up_guest order by id desc limit 1");
$flast = mysql_fetch_array($glast);
if($flast['id'] == '' or $flast['id'] <= 0){
$flast = 1;
}
else{
$flast = $flast['id'] + 1;
}
$time = time();
$filename = $flast.'.'.$filename[1];
if(in_array($tt,$allow)){
thank you all :D

Categories