Php random order for imported .php pages [solved] - php

Version with 1 result
<?php
srand();
$files = array("folder/content1.php", "folder/content2.php", "folder/content3.php", "folder/content4.php", "folder/content5.php", "folder/content6.php");
$rand = array_rand($files);
include ($files[$rand]);
?>
Version with 5 results (provided by Code Spirit)
<?php
$files = array("folder/content1.php", "folder/content2.php", "folder/content3.php", "folder/content4.php", "folder/content5.php", "folder/content6.php");
foreach (array_rand($files, 5) as $file) {
include($files[$file]);
}
?>

You need a loop.
foreach (array_rand($files, 3) as $file) {
include($files[$file]);
}

Related

Passing Array values into Function

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
}
}

php copy file for each filename in array

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,

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);

How to remove duplicate values from array in foreach loop?

I want to remove duplicate values from array. I know to use array_unique(array) function but faced problem in foreach loop. This is not a duplicate question because I have read several questions regarding this and most of them force to use array_unique(array) function but I have no idea to use it in foreach loop. Here is my php function.
$images = scandir($dir);
$listImages=array();
foreach($images as $image){
$listImages=$image;
echo substr($listImages, 0, -25) ."<br>"; //remove last 25 chracters
}
How to do this?
It is very complicated to remove duplicate values from array within foreach loop. Simply you can push all elements to one array and then remove the duplicates and then get values as you need. Try with following code.
$listImages=array();
$images = scandir($dir);
foreach($images as $image){
$editedImage = substr($image, 0, -25);
array_push($listImages, $editedImage);
}
$filteredList = array_unique($listImages);
foreach($filteredList as $oneitem){
echo $oneitem;
}
The example you provided could be modified as follows:
$images = scandir($dir);
$listImages=array();
foreach($images as $image) {
if (!in_array($image, $listImages)) {
$listImages[] = $image;
}
echo substr($image, 0, -25) ."<br>"; //remove last 25 chracters
}
Now $listImages will contain no duplicates, and it will echo every image (including duplicates).
Based on #mistermartins answer:
$images = scandir($dir);
$listImages=array();
foreach($images as $image) {
//if already echo'd continue to next iteration
if (in_array($image, $listImages)) {
continue;
}
//else, add image to array and echo.
$listImages[] = $image;
echo substr($image, 0, -25) ."<br>"; //remove last 25 chracters
}
It should be faster to use hashmaps:
$images = scandir($dir);
$listImages = array();
foreach($images as $image) {
if (!isset($listImages[$image])) {
$listImages[$image] = true;
echo substr($image, 0, -25) ."<br>"; //remove last 25 chracters
}
}
I'm not sure if I have understood you completely. Subsequent approach worked for me in order to remove duplicate indizes from array using a foreeach loop.
$list = array("hans", "peter", "hans", "lara", "peter", "lara", "lara");
sort($list);
foreach ($list as $k => $v) {
if (isset($check)) {
if ($check === $v) {
unset($list[$k]);
}
}
$check = $v;
}
$noDuplicate = array_values($list);
print_r($noDuplicate);
gives following result:
Array ( [0] => hans [1] => lara [2] => peter )

Same code with different variable name not working in PHP?

I am using this code to list all files inside a directory which works perfectly
<?php
$exclude = array("index.php","cssheadertop.php","cssheaderbottom.php");
$cssfiles = array_diff(glob("*.php"), $exclude);
foreach ($cssfiles as $cssfile) {
$filename = "http://example.com/lessons/css/".$cssfiles[$cssfile];
outputtags($filename,true,true);
}
?>
However, with this code nothing is shown on the webpage. I can't figure out why
<?php
$exclude = array("index.php","htmlheadertop.php","htmlheaderbottom.php");
$htmlfiles = array_diff(glob("*.php"), $exclude);
foreach ($htmlfiles as $htmlfile) {
$filename = "http://example.com/lessons/html/".$htmlfiles[$htmlfile];
outputtags($filename,true,true);
}
?>
Try this:
<?php
$exclude = array("index.php","htmlheadertop.php","htmlheaderbottom.php");
$htmlfiles = array_diff(glob("*.php"), $exclude);
foreach ($htmlfiles as $htmlfile) {
$filename = "http://example.com/lessons/html/".$htmlfile;
outputtags($filename,true,true);
}
?>
$htmlfiles[$htmlfile] should not be set and should not work.
You need to use $htmlfile inside foreach loop instead of $htmlfiles[$htmlfile], and it works with any other variable's name
<?php
$exclude = array("index.php","htmlheadertop.php","htmlheaderbottom.php");
$htmlfiles = array_diff(glob("*.php"), $exclude);
foreach ($htmlfiles as $htmlfile) {
$filename = "http://example.com/lessons/html/".$htmlfile;
outputtags($filename,true,true);
}
?>

Categories