Foreach loop not displaying the 0 element in codeignter - php

Goodday,
I need some assistant with my foreach loop.
I am uploading multiple images/files to my server and then i am trying to send the images as attachments in an email.
I get the data to the email function and can git it in the loop but for some reason i only see the last item in the array and con see why tjis is happing.
Please see attached the output and code of the function.
function forwardCallEmail($emaildetails)
{
$data = $emaildetails;
pre($data['files']);
echo('<br/>');
//die;
$CI = setProtocol();
$CI->email->from('');
$CI->email->subject("");
$CI->email->message($CI->load->view('calls/forwardCallEmail', $data, TRUE));
$path = base_url() . "uploads/Calls/";
foreach ((array) $data['files'] as $files){
echo($files);
echo('<br/>');
$images = explode(',', $files);
var_dump($images);
foreach($images as $files);
echo('<br/>');
echo $files;
die;
$CI->email->attach($path . $files);
pre($CI);
die;
}
$CI->email->to($data['email']);
$status = $CI->email->send();
return $status;

You can try something like this
Replace this part
foreach ((array) $data['files'] as $files){
echo($files);
echo('<br/>');
$images = explode(',', $files);
var_dump($images);
foreach($images as $files);
echo('<br/>');
echo $files;
die;
$CI->email->attach($path . $files);
pre($CI);
die;
}
To this one
foreach ((array) $data['files'] as $files){
echo($files);
echo('<br/>');
$images = explode(',', $files);
var_dump($images);
foreach($images as $files) {
echo('<br/>');
echo $files;
$CI->email->attach($path . $files);
pre($CI);
}
}
Anyway this example to explain a logic of foreach
Ok, just as example
$data = [
'files' => [
"image1, image2, image3",
"image4, image5, image6",
]
];
foreach ($data['files'] as $fileKey => $file){
echo($file);
$images = explode(',', $file);
foreach($images as $imageKey => $imageValue) {
$out[$fileKey][$imageKey] = $imageValue;
}
}
print_r($out);
And result will be
(
[0] => Array
(
[0] => image1
[1] => image2
[2] => image3
)
[1] => Array
(
[0] => image4
[1] => image5
[2] => image6
)
)

I got it to work, not sure if it is the right way it is working.
Email sending code
CI = setProtocol();
$CI->email->from('helpdesk#ziec.co.za', 'HTCC Helpdesk');
$CI->email->subject("HTCC Call Assistants");
$CI->email->message($CI->load->view('calls/forwardCallEmail', $data, TRUE));
$path = 'c:/xampp/htdocs/Helpdeskv2.1/uploads/Calls/';
$images = explode(',', $data['files']);
foreach($images as $file){
$path = 'c:/xampp/htdocs/Helpdeskv2.1/uploads/Calls/'. $file;
$CI->email->attach($path);
}
$CI->email->to($data['email']);
$status = $CI->email->send();
return $status;

Related

PHP: fetch file without check case sensitive

I have a image named Dark-Green.jpg but the output of function is DARK-GREEN.jpg so the image is not displaying due to case-sensitive.
So how can I fetch the image?
UPDATE
Below is my output of the array.
$output = Array
(
[WE05-5040*L] => Array
(
[qty] => 1
[stitching_category] => 2
[sku_image] => skuimages/WE05/DARK-GREEN.jpg
)
)
Then I am using this array in foreach loop like below.
foreach ($output as $ok => $op) {
$itemQty = $op['qty'];
$itemImagePath = $op['sku_image'];
echo "{$ok} has qty: {$itemQty} and the image as below.";
echo "<img src='{$itemImagePath}' width='50%' />"
}
Try this:
function getFile ($filename){
$files = glob($dir . '/*');
$filename = strtolower($filename);
foreach($files as $file) {
if (strtolower($file) == $filename){
return $file;
}
}
return false;
}

How to display images(.jpg) only?

Array ( [0] => assets/image/man.jpg [1] => assets/image/violin.jpg [2] => assets/image/test.txt )
The data from data base is like above.It contain images and txt.how can i display only images.
$ar = ['assets/image/man.jpg','assets/image/violin.jpg','assets/image/test.txt'];
$allowed = ['jpg']; //your image extensions
$img_ar = [];
foreach($ar as $img){
$ext = pathinfo($img,PATHINFO_EXTENSION);
if(in_array($ext,$allowed)){
$img_ar[] = $img;
}
}
print_r($img_ar);
$array= Array ( [0] => assets/image/man.jpg [1] => assets/image/violin.jpg [2] => assets/image/test.txt )
$m_array = preg_grep('/^.jpg\s.*/', $array);
$m_array contains matched elements of array.
For more detail have look at this thread search a php array for partial string match
For this you can directly filter it when you are querying like
field like '%.jpg'
If you don't want to do that and manipulate the array you can use array_filter like,
$array= Array ('assets/image/man.jpg', 'assets/image/violin.jpg', 'assets/image/test.txt');
$output = array_filter($array, function($arr) {
if (strpos($arr, '.jpg') == true){
return $arr;
}
});
$output array contains only the entries which having the .jpg string.
Here am using strpos to check .jpg exists or not.
you maybe use substr($str, -4) == '.jpg' to check the last 4characters.
If you are using PHP 5+ (which I hope you are on 7.0+), use SplFileInfo() class
$spl = new SplFileInfo($fileName);
if ($spl->getExtension() == 'jpg') {
//image
}
Use foreach loop and get an extension of the file and display.
foreach($array_result as $result){
//$array_result is array data
//condition is checking the file that if it is an image or not
$allowed = array('gif','png' ,'jpg');
$filename = $result;
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(in_array($ext, $allowed) ) {
echo '<img src="'.$result.'" alt="" /> ';
}
}
This should do the trick:
$images = array();
$images_exts = array('.jpg','.png');
foreach($db_array as $key => $value)
{
foreach($images_exts as $ext)
{
if (strpos($value,$ext))
{
$images[] = $value;
}
}
}
Here is an example https://3v4l.org/8W3Be
And here is another way, whatever you like the most:
$images = array();
$images_exts = array('jpg','png');
foreach($input as $value)
{
if(in_array(#end(explode('.', $value)), $images_exts))
{
$images[] = $value;
}
}
Here is an example https://3v4l.org/b0njd
Why do you check it when you want write it on page?
You can:
1. split assets/image/man.jpg with '/'
2. get last one,
3. split last one with '.'
4. get extension and if it was 'jpg' write it to page.
<?php
$error = array();
$file_extArr = explode(".", $file_name);
$file_extEnd = end($file_extArr);
$file_ext = strtolower($file_extEnd);
$validateImage = array("png", "jpg", "jpeg", "gif");
if (!in_array($file_ext, $validateImage)) {
$error[] = "wrong format image";
}
if (!empty($error)) {
return;
}
?>
<?php
$data = Array (
'assets/image/man.jpg ',
'assets/image/violin.jpg ',
'assets/image/test.txt ',
);
$arrDara = array();
foreach ($data as $value) {
$fileName = explode('/', $value);
$arrDara[] = end($fileName);
}
print_r($arrDara);
?>
Just loop your array and explode every sting. the last index is what all you need.

get entire folders/files tree and rename

I have a folders/files tree inside admin folder (windows, localhost).
All files are .html.
Each of them (files and folders) is starting with some numbers and middle dash, for example
32-somefolder
624-somefile.html
I need to list all of them and remove all prefixes from their names.
So the result should be:
somefolder
somefile.html
foreach(glob("admin/*") as $el) {
echo $el . '.' . filetype($el) . '<br>';
}
First problem - only folders are listed:
admin/32-somefolder.dir
How to get files too, and how to rename i.e. remove prefixes from all the names?
You can use the second choice to list files : scandir, and recursive function :
function removePrefixFiles($dir, &$results = array()){
$files = scandir($dir);
foreach ($files as $key => $value){
$path = realpath($dir . DIRECTORY_SEPARATOR . $value);
if (! is_dir($path)) {
// treat the filename
$file = pathinfo($path);
$filename = explode('-', $file['filename']);
if (count($filename) > 0) {
// '-' is found, rename file
rename($path, $file['dirname'] .'/'. $filename[1] .'.'. $file['extension'];
}
$results[] = $path;
} else if ($value != '.' && $value != '..') {
removePrefixFiles($path, $results);
$results[] = $path;
}
}
// no real need to return something here, but can log the files
return $results;
}
$dir = '/admin';
removePrefixFiles($dir);
I have created two folder inside admin/ name as
1-files and 2-abc
then inside folder 1-files i have two files
11-java.html
11-text.html
then inside folder 2-abc i have two files
22-php.html
22-sql.html
<?php
$dir = "admin/";
// Sort in ascending order - this is default
$a = scandir($dir);
echo "<pre>";
if(count($a)>0){
$newArr = array();
for($i=2;$i<count($a);$i++){
$test = array();
$folderArr = array();
$folderName = explode('-',$a[$i]);
$test['folder'] = $folderName[1];
$b = scandir($dir.'/'.$a[$i]);
for($j=2;$j<count($b);$j++){
$fileName = explode('-',$b[$j]);
$folderArr[] = substr($fileName[1], 0, strpos($fileName[1], "."));;
}
$test['files'] = $folderArr;
$newArr[] = $test;
}
}
print_r($newArr);
?>
This will be the output
Array
(
[0] => Array
(
[folder] => files
[files] => Array
(
[0] => java
[1] => text
)
)
[1] => Array
(
[folder] => abc
[files] => Array
(
[0] => php
[1] => sql
)
)
)
Hope this willl hellp you.

Sort Images by Date Modified

I have a small script that puts images from a folder into a web page.
I would like to sort by DATE MODIFIED anyone know how to do this?
function php_thumbnails($imagefolder,$thumbfolder,$lightbox)
{
//Get image and thumbnail folder from function
$images = "portfolio/" . $imagefolder; //The folder that contains your images. This folder must contain ONLY ".jpg files"!
$thumbnails = "portfolio/" . $thumbfolder; // the folder that contains all created thumbnails.
//Load Images
//load images into an array and sort them alphabeticall:
$files = array();
if ($handle = opendir($images))
{
while (false !== ($file = readdir($handle)))
{
//Only do JPG's
if(eregi("((.jpeg|.jpg)$)", $file))
{
$files[] = array("name" => $file);
}
}
closedir($handle);
}
//Obtain a list of columns
foreach ($files as $key => $row)
{
$name[$key] = $row['name'];
}
//Put images in order:
array_multisort($name, SORT_ASC, $files);
//set the GET variable name
$pic = $imagefolder;
You need to use filemtime function to retrieve the files modification time, and then use it to build your multisort help array.
...
if(eregi("((.jpeg|.jpg)$)", $file))
{
$datem = filemtime($images . '/' . $file);
$files[] = array("name" => $file, "date" => $datem);
}
}
...
...
...
foreach ($files as $key => $row)
{
$date[$key] = $row['date'];
}
//Put images in order:
array_multisort($date, SORT_ASC, $files);

PHP get file listing including sub directories

I am trying to retrieve all images in a directory, including all subdirectories. I am currently using
$images = glob("{images/portfolio/*.jpg,images/portfolio/*/*.jpg,images/portfolio/*/*/*.jpg,images/portfolio/*/*/*/*.jpg}",GLOB_BRACE);
This works, however the results are:
images/portfolio/1.jpg
images/portfolio/2.jpg
images/portfolio/subdirectory1/1.jpg
images/portfolio/subdirectory1/2.jpg
images/portfolio/subdirectory2/1.jpg
images/portfolio/subdirectory2/2.jpg
images/portfolio/subdirectory1/subdirectory1/1.jpg
images/portfolio/subdirectory1/subdirectory1/2.jpg
I want it to do a whole directory branch at a time so the results are:
images/portfolio/1.jpg
images/portfolio/2.jpg
images/portfolio/subdirectory1/1.jpg
images/portfolio/subdirectory1/2.jpg
images/portfolio/subdirectory1/subdirectory1/1.jpg
images/portfolio/subdirectory1/subdirectory1/2.jpg
images/portfolio/subdirectory2/1.jpg
images/portfolio/subdirectory2/2.jpg
Greatly appreciate any help, cheers!
P.S It would also be great if I could just get all subdirectories under portfolio without having to specifically state each directory with a wild card.
from glob example
if ( ! function_exists('glob_recursive'))
{
// Does not support flag GLOB_BRACE
function glob_recursive($pattern, $flags = 0)
{
$files = glob($pattern, $flags);
foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir)
{
$files = array_merge($files, glob_recursive($dir.'/'.basename($pattern), $flags));
}
return $files;
}
}
Solution:
<?php
$path = realpath('yourfolder/examplefolder');
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $filename)
{
echo "$filename</br>";
}
?>
Here's a simpler approach:
Instead of using:
$path = realpath('yourfolder/examplefolder/*');
glob($path);
You'll have to use:
$path = realpath('yourfolder/examplefolder').'/{**/*,*}';
glob($path, GLOB_BRACE);
This last one will use bracing, and it is, in fact, a shorthand for this code:
$path = realpath('yourfolder/examplefolder');
$self_files = glob($path . '/*');
$recursive_files = glob($path . '/**/*');
$all_files = $self_files + $recursive_files; // That's the result you want
You may also want to filter directories from your result. glob() function has GLOB_ONLYDIR flag. Let's use it to diff out our result.
$path = realpath('yourfolder/examplefolder/') . '{**/*,*}';
$all_files = array_diff(
glob($path, GLOB_BRACE),
glob($path, GLOB_BRACE | GLOB_ONLYDIR)
);
This function supports GLOB_BRACE:
function rglob($pattern_in, $flags = 0) {
$patterns = array ();
if ($flags & GLOB_BRACE) {
$matches;
if (preg_match_all ( '#\{[^.\}]*\}#i', $pattern_in, $matches )) {
// Get all GLOB_BRACE entries.
$brace_entries = array ();
foreach ( $matches [0] as $index => $match ) {
$brace_entries [$index] = explode ( ',', substr ( $match, 1, - 1 ) );
}
// Create cartesian product.
// #source: https://stackoverflow.com/questions/6311779/finding-cartesian-product-with-php-associative-arrays
$cart = array (
array ()
);
foreach ( $brace_entries as $key => $values ) {
$append = array ();
foreach ( $cart as $product ) {
foreach ( $values as $item ) {
$product [$key] = $item;
$append [] = $product;
}
}
$cart = $append;
}
// Create multiple glob patterns based on the cartesian product.
foreach ( $cart as $vals ) {
$c_pattern = $pattern_in;
foreach ( $vals as $index => $val ) {
$c_pattern = preg_replace ( '/' . $matches [0] [$index] . '/', $val, $c_pattern, 1 );
}
$patterns [] = $c_pattern;
}
} else
$patterns [] = $pattern_in;
} else
$patterns [] = $pattern_in;
// #source: http://php.net/manual/en/function.glob.php#106595
$result = array ();
foreach ( $patterns as $pattern ) {
$files = glob ( $pattern, $flags );
foreach ( glob ( dirname ( $pattern ) . '/*', GLOB_ONLYDIR | GLOB_NOSORT ) as $dir ) {
$files = array_merge ( $files, rglob ( $dir . '/' . basename ( $pattern ), $flags ) );
}
$result = array_merge ( $result, $files );
}
return $result;
}
Simple class:
<?php
class AllFiles {
public $files = [];
function __construct($folder) {
$this->read($folder);
}
function read($folder) {
$folders = glob("$folder/*", GLOB_ONLYDIR);
foreach ($folders as $folder) {
$this->files[] = $folder . "/";
$this->read( $folder );
}
$files = array_filter(glob("$folder/*"), 'is_file');
foreach ($files as $file) {
$this->files[] = $file;
}
}
function __toString() {
return implode( "\n", $this->files );
}
};
$allfiles = new AllFiles("baseq3");
echo $allfiles;
Example output:
baseq3/gfx/
baseq3/gfx/2d/
baseq3/gfx/2d/numbers/
baseq3/gfx/2d/numbers/eight_32b.tga
baseq3/gfx/2d/numbers/five_32b.tga
baseq3/gfx/2d/numbers/four_32b.tga
baseq3/gfx/2d/numbers/minus_32b.tga
baseq3/gfx/2d/numbers/nine_32b.tga
If you don't want the folders in the list, just comment this line out:
$this->files[] = $folder . "/";

Categories