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);
Related
I tried the following code but an error occurs when I run the project
$files = $request->file('files');
if($request->hasFile('files'))
{
foreach ($files as $file) {
$path = $file->store('public/gallery');
ProductGallery::create([
'products_id' => $product->id,
'url' => $path
]);
}
}
Upon using hasFile on an array it seems that it only checks the first element from the array. If the first element of your files array is empty, the result will always be false. A workaround to your problem is:
$files = $request->file('files');
if(count($request->file('files')) > 0)
{
foreach ($files as $file) {
if ($file->isValid()) {
/* Write your file upload code here */
}
}
}
I am trying to pass an array value into a function, but can't seem to get it to work. Here is what I am trying to do
I have a folder on my server called /Rpt
The /Rpt folder has a bunch of different folders inside of it (30 of them) - these folders contain a bunch of different files in them
I want to check most of the folders in /Rpt, and get the name and date of the latest file (based on last modified or created date) ... i want to store the results into an array, that has (folder path, file name of last file, file date of last file)
This query gets the folders that need to be checked
$sql = "my SQL here";
$stmt = $dbh->prepare($sql);
$stmt->execute();
$arrValues = $stmt->fetchAll(PDO::FETCH_ASSOC);
This is a function that checks the specified folder, and displays the info i need (folder path, file name, file date)
function GetFileNameDate($location, $file_name, $file_date) {
$files = scandir($location);
$path = $location;
foreach ($files as $file) {
if (strpos($file, " ") !== false) {
$filename = $file;
$last_updated = date ("F d Y H:i:s", filemtime($path.'\\'.$file));
$results = array($filename=>$last_updated);
$file_name = key($results);
$file_date = reset($results);
return array($location, $file_name, $file_date);
}
}
}
When i call the function - and enter a specific path link in this example, it works OK and i shows the values i want to see
$FileNameDate = GetFileNameDate('E:\Rpt\FolderA');
echo $FileNameDate[0];
echo $FileNameDate[1];
echo $FileNameDate[2];
echo "<br/><br/>";
This is where I am having problems
I am trying to pass an array (list of folders from my SQL query) into the function, so i can output the (folder path, name of latest file, date of latest file) for each of the folders from SQL query
When i echo $locations (it lists all the folders which i am trying to pass to the function)
foreach ($arrValues as $row){
$locations = array($row['Folder']);
$FileNameDate = GetFileNameDate($locations);
echo $FileNameDate[0];
echo $FileNameDate[1];
echo $FileNameDate[2];
}
As per suggestion from #lovelace I also tried the following, but again just a blank page.
foreach ($arrValues as $row){
$locations = array($row['Folder']);
foreach ($locations as $FolderPath) {
$FileNameDate = GetFileNameDate($FolderPath);
echo $FileNameDate[0];
echo $FileNameDate[1];
echo $FileNameDate[2];
}
}
SOLUTION
see comment below to how above was fixed ... however I ended up implementing what i wanted a different way, sharing it in case anyone else needs similar functionality
function GetFileNameDate($location) {
$files = scandir($location);
$path = $location;
foreach ($files as $file) {
$iterator = new DirectoryIterator($path);
$mtime = 0;
$file = "";
foreach ($iterator as $fileinfo) {
if ($fileinfo->isFile()) {
if ($fileinfo->getMTime() > $mtime) {
$file = $fileinfo->getFilename();
$mtime = $fileinfo->getMTime();
}
}
}
return array($path, $file, $mtime);
}
}
foreach ($arrValues as $row){
$locations = array(rtrim($row['Folder']));
foreach ($locations as $FolderPath) {
$FileNameDate = GetFileNameDate($FolderPath);
echo $FileNameDate[0]; #folder
echo $FileNameDate[1]; #file
echo $FileNameDate[2]; #date
}
}
I would like to output the jason data which looks like a jasondata below on PHP. folder is the name of the folder, and title is located at the firstline of info.txt. info.txt is located under the folder. There are three lines in each info.txt, and those lines are separated just by making new lines (not commas). folder books, and my php file is located under the same folder. How can I write a PHP code? Thanks.
MY PHP code is here;
function books(){
$array = [];
$story = glob("books/" . "*");
foreach($story as $each){
$title = file($each ."/info/txt", FILE_IGNORE_NEW_LINES);
$output = array (
"title" => $title[0],
"folder" => $each #i would like to put the name of the folder here
);
array_push($array,$review);
}
print(json_encode($array));
}
Json data should look like;
{
"books" : [
{
"title": "Harry Potter and the Prisoner of Azkaban",
"folder": "harrypotter"
},
{
"title": "The Hobbit",
"folder": "hobbit"
},
... (one entry like this for each folder inside books/)
]
}
Use DirectoryIterator or scandir functions ,try this code bellow
$dirs = '/directory/';
$dir = new DirectoryIterator($dirs);
$array = array();
foreach ($dir as $key => $fileinfo) {
if ($fileinfo->isDir()) {
//remove hidden files or dot files
if ( $fileinfo->getBasename() === '.' || $fileinfo->getBasename() === '..' ) continue);
//foldername
$array[$key]['folder'] = $fileinfo->getBasename();
//title
$array[$key]['title'] = file($array[$key]['folder'].'/info.txt' , FILE_IGNORE_NEW_LINES);
}
}
$json = json_encode($array);
print_r($json);
let me know if it's worked or not.
edited
I try in my localhost and it's worked
$dirs = 'books/';
$dir = new DirectoryIterator($dirs);
$array = array();
foreach ($dir as $key => $fileinfo) {
if ($fileinfo->isDir()) {
//remove hidden files or dot files
if ( $fileinfo->getBasename() === '.' || $fileinfo->getBasename() === '..' ) continue;
//foldername
$array[$key]['folder'] = $fileinfo->getBasename();
//title
$array[$key]['title'] = file($dirs.'/'.$array[$key]['folder'].'/info.txt' , FILE_IGNORE_NEW_LINES);
}
}
$json = json_encode($array);
echo '<pre>'.print_r($json, true).'</pre>';
Screenshot
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,
I am trying to get the name and size index of all uploaded files but I can't get it work. it works like this:
foreach ($_FILES['file']['name'] as $key => $file){
echo $file;
}
but if I want to echo multiple indexes in the same loop, i tries this, but I get "undefined index 'name' and 'size'" warnings. What am I doing wrong? thanks
foreach ($_FILES['file'] as $key => $file){
echo $file['name'].
$file['size'];
}
<input name ="file[]" type = "file" multiple />
function handle_image_upload($frmFilesID = false, $thisFile = false) {
$tmpName = $_FILES["$frmFilesID"]['tmp_name'][$thisFile];
if (!is_uploaded_file($tmpName)) { return false; }
$fileName = $_FILES["$frmFilesID"]['name'][$thisFile];
$fileSize = $_FILES["$frmFilesID"]['size'][$thisFile];
$fileType = $_FILES["$frmFilesID"]['type'][$thisFile];
...