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;
}
Related
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;
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.
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.
$ols_produk = $this->db->query("SELECT files FROM galeri_files WHERE id_galeri = '$id'");
$file = $ols_produk->result();
echo "<pre>";
print_r($file);
echo "</pre>";
if($file != ''){
foreach ($file as $key=>$value) {
unlink('gambar/galeri/'.$key);
}
}
when i look in print_r($file);the result is
Array
(
[0] => stdClass Object
(
[files] => g+.png
)
[1] => stdClass Object
(
[files] => andbook.pdf
)
)
and i cant unlink the file because it select the number of array,
how to get the file?
you $files is an array of objects, foreach will get the value as object, and use -> to access the member as this:
foreach ($file as $v) {
unlink('gambar/galeri/'.$v->files);
}
Try this:
foreach ($file as $key=>$value) {
unlink('gambar/galeri/'.$value['files']);
}
Like this.Use codeigniter's result_array() result set to get the values in array format from database.
$ols_produk = $this->db->query("SELECT files FROM galeri_files WHERE id_galeri = '$id'");
$file = $ols_produk->result_array();
echo "<pre>";
print_r($file);
echo "</pre>";
if(count($file)>0){
foreach ($file as $key=>$value) {
unlink('gambar/galeri/'.$value['files']);
}
}
For more see Codeigniter Result Sets
I am trying to move all the files in my array from one directory to another.
I have done some research and are using the php Copy() function.
here is my code so far:
$filenameArray = "img1.png,img2.png,img3.png";
$sourcePath = "/source/";
$savePath = "/newDir/";
$myArray = explode(',', $filenameArray);
$finalArray = print_r($myArray);
function copyFiles($finalArray,$sourcePath,$savePath) {
for($i = 0;$i < count($finalArray);$i++){
copy($sourcePath.$finalArray[$i],$savePath.$finalArray[$i]);}
}
Anyone see where I'm going wrong?
Thanks in advance!
This is the unlink ive been attempting to use.
function copyFiles($finalArray,$sourcePath,$savePath) {
foreach ($finalArray as $file){
if (!copy($sourcePath.$file,$savePath.$file)) {
echo "Failed to move image";
}
$delete[] = $sourcePath.$file;
}
}
// Delete all successfully-copied files
foreach ( $delete as $file ) {
unlink( $sourcePath.$file );
}
My Final Working Code
the code below moves images in comma seperated array to new folder and removes them from current folder
$finalArray = explode(',', $filenameArray);
function copyFiles($finalArray,$sourcePath,$savePath) {
foreach ($finalArray as $file){
if (!copy($sourcePath.$file,$savePath.$file)) {
echo "Failed to move image";
}
}
}
copyFiles( $finalArray, $sourcePath, $savePath);
function removeFiles($finalArray,$sourcePath) {
foreach ($finalArray as $file){
if (!unlink($sourcePath.$file)) {
echo "Failed to remove image";
}
}
}
removeFiles( $finalArray, $sourcePath);
In your code you are not calling the copyFile function. Try this:
$filenameArray = "img1.png,img2.png,img3.png";
$sourcePath = "/source/";
$savePath = "/newDir/";
$finalArray = explode(',', $filenameArray);
function mvFiles($finalArray,$sourcePath,$savePath) {
foreach ($finalArray as $file){
if (!rename($sourcePath.$file,$savePath.$file)) {
echo "failed to copy $file...\n";
}
}
}
mvFiles( $finalArray, $sourcePath, $savePath);
A simple solution :
$filenameArray = "img1.png,img2.png,img3.png";
$sourcePath = "/source/";
$savePath = "/newDir/";
$myArray = explode(',', $filenameArray);
$finalArray = $myArray; //corrected this line
function copyFiles($finalArray, $sourcePath, $savePath)
{
for ($i = 0; $i < count($finalArray); $i++)
{
copy($sourcePath.$finalArray[$i],$savePath.$finalArray[$i]);
}
}
Hope you have right call to function copyFiles().
UPDATE for unlink() :
Let me try to throw some light on your work (written code):
foreach ($finalArray as $file)
{
if (!copy($sourcePath.$file,$savePath.$file))
{
echo "Failed to move image";
}
$delete[] = $sourcePath.$file;
}
Contents of $delete :
a. /source/img1.png
b. /source/img2.png
c. /source/img3.png
Now,
foreach ( $delete as $file )
{
unlink( $sourcePath.$file );
}
unlink() will be called with the following parameters:
$sourcePath.$file : /source/./source/img1.png : /source//source/img1.png => No such path exists
$sourcePath.$file : /source/./source/img2.png : /source//source/img2.png => No such path exists
$sourcePath.$file : /source/./source/img3.png : /source//source/img3.png => No such path exists
$sourcePath.$file : /source/./source/img4.png : /source//source/img4.png => No such path exists
I think for this reason, unlink is not working.
The code to be written should be like the following:
foreach ( $delete as $file )
{
unlink( $file );
}
Now, unlink() will be called with the following parameters:
a. /source/img1.png => path do exists
b. /source/img2.png => path do exists
c. /source/img3.png => path do exists
Do tell me if this does not solves the issue.
Update as per Dave Lynch's code:
$filenameArray = "img1.png,img2.png,img3.png";
$sourcePath = "/source/";
$savePath = "/newDir/";
$finalArray = explode(',', $filenameArray);
foreach ($finalArray as $file)
{
$delete[] = $sourcePath.$file;
}
foreach ( $delete as $file )
{
echo $sourcePath.$file . "</br>";
}
Output:
/source//source/img1.png
/source//source/img2.png
/source//source/img3.png
Please check.
Thanks and Regards,