php copy file for each filename in array - php

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,

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 delete folder with images and mysql record news that does not exist

How to delete folder with images and mysql record news that does not exist?
Dont work. Why?
$resnotid = mysqli_query($db, "SELECT id FROM objects");
$idarray[] = array();
$namefolderarray[] = array();
while($rownotid = mysqli_fetch_array($resnotid)) {
$idarray[] = $rownotid['id'];
}
$dir = opendir('upload');
while($folder = readdir($dir)) {
if (is_dir('upload/'.$folder) && $folder != '.' && $folder != '..') {
$namefolderarray[] = $folder;
}
}
$delid = array_diff($namefolderarray, $idarray);
rmdir('upload/'.$delid.'/');
The method array_diff returns an array. So you have to iterate over that array.
$del_arr = array_diff($namefolderarray, $idarray);
foreach ($del_arr as $delid) {
rmdir('upload/'.$delid.'/');
}
Update 1
The previous solution only works for empty folders. If you have any content in the folders you must first delete the content. This can be done with an recursive function that iterates over the contents.
function rmdir_recursively($path) {
if (is_dir($path)){
$list = glob($path.'*', GLOB_MARK);
foreach($list as $item) {
rmdir_recursively($item);
}
rmdir($path);
} else if (is_file($path)) {
unlink($path);
}
}
$del_arr = array_diff($namefolderarray, $idarray);
foreach ($del_arr as $del_id) {
rmdir_recursively('upload/'.$del_id.'/');
}
Update 2
To also delete the database-records without a folder you can extend the code like this:
foreach ($del_arr as $del_id) {
rmdir_recursively('upload/'.$del_id.'/');
$del_id_escaped = mysqli_real_escape_string($del_id);
mysqli_query($db, "DELETE FROM objects WHERE id='$del_id_escaped'");
}

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.

why array_push don't work inside foreach loop

i have this code for file update and i need to put the files path in response array. but my array is empty:
$response = array();
if (file_exists($directorSerie)) {
if(is_array($_FILES)) {
foreach ($_FILES['fileToUpload']['name'] as $name => $value){
if(is_uploaded_file($_FILES['fileToUpload']['tmp_name'][$name])) {
$sourcePath = $_FILES['fileToUpload']['tmp_name'][$name];
$targetPath = $directorSerieString.$_FILES['fileToUpload']['name'][$name];
array_push($response, $targetPath);
if(move_uploaded_file($sourcePath,$targetPath)) {
$success = "success";
}
}
}
}
}
exit(json_encode($response));
array_push() works on foreach.
I sugest you to put dubug to found where is the mistakes.
You could put var_dump($var) after level of your code, like this:
if (file_exists($directorSerie)) {
var_dump($directorSerie);
Next...
if(is_array($_FILES)) {
var_dump($_FILES)
Next
foreach ($_FILES['fileToUpload']['name'] as $name => $value){
var_dump( $name ,$value);
up until you discover...

PHP ZipArchive stopped working

I have a script which takes a zipped CSV file, unzips it, and removes duplicate entries. It was mostly working, until I moved the unzip code into a function. Now it fails to unzip the .zip file, but doesn't show an error.
Checked file/folder permissions, everything is 777 on dev machine.
<?php
//
//huge memory limit for large files
$old = ini_set('memory_limit', '8192M');
//
//create a string like the filename
$base_filename = 'csv-zip-file'.date('m').'_'.date('d').'_'.date('Y');
//
//if the file exists ...
//unzip it
//read it to an array
//remove duplicates
//save it as a new csv
if (file_exists($base_filename.'.zip')) {
$zip_filename = $base_filename.'.zip';
echo "The file <strong>$zip_filename</strong> exists<br>";
unzip($zip_filename);
$csv = csv_to_array();
$csv = unique_multidim_array($csv,"Project Id");
var_dump($csv);
} else {
echo "The file <strong>$base_filename.zip</strong> does not exist";
}
function unzip($file_to_unzip) {
$zip=new ZipArchive();
if($zip->open($file_to_unzip)==TRUE) {
$address=__DIR__;
$zip->extractTo($address);
$res=$zip->close();
echo 'ok';
}
else{
echo 'failed';
}
}
function unique_multidim_array($array, $key) {
$temp_array = array();
$i = 0;
$key_array = array();
foreach($array as $val) {
if (!in_array($val[$key], $key_array)) {
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}
$i++;
}
return $temp_array;
}
function csv_to_array () {
// global $filename;
global $base_filename;
$rows = array_map('str_getcsv', file($base_filename.'.csv'));
//using array_pop to remove the copyright on final row
array_pop($rows);
$header = array_shift($rows);
$csv = array();
foreach ($rows as $row) {
$csv[] = array_combine($header, $row);
}
return $csv;
}
Interesting problem you have here.
Output $file_to_unzip right inside the function.
Does $zip->* have an last_error or last_response method? See
what the ZipArchive class IS returning.
Do you have access to the php error logs? Let's look there for any output.

Categories