php array keyword counter - php

I am pushing image file information into an array.
It is pretty simple except the keywords are sometimes an array also.
This works great for what I am doing now.
Here is a sample of my array
$list[]=array(filename=>$file,width=>$w,height=>$h,caption=>$iptc["2#120"],keywords=>$iptc["2#025"]);
I can use this array to output the html needed for a javascript slideshow.
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){
//if this file is a valid image
$path = $dirname . "" . $file ;
$path2 = $dirname ."JPEG/" . $file ;
$size = getimagesize($path, $info);
$w = $size[0]; $h = $size[1];
$iptc = iptcparse($info['APP13']);
if(in_array($key,$iptc["2#025"])){
$list[]=array(
filename=>$file,
width=>$w,
height=>$h,
caption=>$iptc["2#120"],
keyw‌​ords=>$iptc["2#025"]
);
}
}
}
closedir($handle); }
I would like to be able to have another variable in the array which would count up one number as each unique keyword is added. This will allow me to go directly to the middle of a slideshow as the js plugin I am using a js slideshow only have direct links if referenced by a number
I imagine I would need to create a unique array of all the keywords and then have some type of complicated if statement to count for each of the unique variables.....
however I have no Idea how to do this
Help Please
thanks
Jeremy

Im not sure if I understand what you're looking for but it sounds like:
while(loop_conditions){
$list[]=array(filename=>$file,width=>$w,height=>$h,caption=>$iptc["2#120"],keywords=>$iptc["2#025"]);
foreach($iptc["2#025"] as $keyword){
$list_map[$keyword]++;
}
}

Related

Javascript slideshow from PHP array

My goal is to pull the images from a file into a PHP array, then convert that array to a Javascript array that I could then use for my slideshow. That way I don't have to manually update my code when I add a new image to a file.
I am struggling with the Javascript part. I know that I can somehow use JSON function to convert the PHP array to Javascript array but I don't know how to use that function properly.
This is my PHP code that displays all pictures from a file called "slike":
<?php
$dir = 'slike';
$file_display = array('jpg','jpeg','png');
if (file_exists($dir) === false){
echo "Directory ".$dir." doesn't exist!";
}
else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file){
$file_typeExplode = explode('.', $file);
$file_type = strtolower(end($file_typeExplode));
if($file !== '.' && $file !== '..' && in_array($file_type, $file_display) === true){
echo '<img src = "', $dir, '/', $file, '" alt ="', $file, '" />';
}
}
}
?>
Not sure what that "converting to javascript array" part really means but I think you want to construct an array in javascript starting from what you have in the html page (DOM).
First of allyou have to identify the element of your page containing all the images, say it is an id of name foo :
<div id="foo">
<img src....>
</div>
then in javascript you iterate on all the child elements of your div (that are your images) and construct an array with them.
var arry = [];
var images = document.getElementById('foo').childNodes;
for(i=0; i<nodes.length; i++) {
arry.push(nodes[i]);
}
You could also give a class to all your images and iterate on all document.getElementsByClassName

get all file names from a directory in php

(Well what I gone through a lot of posts here on stackoverflow and other sites. I need a simple task, )
I want to provide my user facility to click on upload file from his account, then select a directory and get the list of all the files names inside that directory.
According to the posts here what I got is I have to pre-define the directory name, which I want to avoid.
Is there a simple way to click a directory and get all the files names in an array in PHP? many thanks in advance!
$dir = isset($_POST['uploadFile']) ? _SERVER['DOCUMENT_ROOT'].'/'.$_POST['uploadFile'] : null;
if ($_POST['uploadFile'] == true)
{
foreach (glob($dir."/*.mp3") as $filename) {
echo $filename;
}
}
I will go ahead and post a sample of code I am currently using, with a few changes, although I would normally tell you to look it up on google and try it first.
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
echo $file;
}
closedir($handle);
}
This will display the entire contents of a directory... including: ".", "..", any sub-directories, and any hidden files. I am sure you can figure out a way to hide those if it is not desirable.
<?php
$files=glob("somefolder/*.*");
print_r($files);
?>
Take a look at the Directory class (here) and readdir()
I'm confused what do you want, all files or only some files?
But if you want array of folders and files, do this
$folders = array();
$files = array();
$dir = opendir("path");
for($i=0;false !== ($file = readdir($dir));$i++){
if($file != "." and $file != ".."){
if(is_file($file)
$files[] = $file;
else
$folders[] = $file;
}
}
And if only some folders you want, later you can delete them from array
I always use this amazing code to get file lists:
$THE_PATTERN=$_SERVER["DOCUMENT_ROOT"]."/foldername/*.jpg";
$TheFilesList = #glob($THE_PATTERN);
$TheFilesTotal = #count($TheFilesList);
$TheFilesTotal = $TheFilesTotal - 1;
$TheFileTemp = "";
for ($TheFilex=0; $TheFilex<=$TheFilesTotal; $TheFilex++)
{
$TheFileTemp = $TheFilesList[$TheFilex];
echo $TheFileTemp . "<br>"; // here you can get full address of files (one by one)
}

Iterate through a folder?

I'm looking for the best way to iterate through a folder and put all the file names inside it into an array and in another one the count of the files.
I have found glob() as a good solution, but also a lot of alternatives for it on php.net. I'm not sure which I should use, so I'm asking here. If you're wondering for what I want to use it, it's to get all the .sql files inside a backup folder and display them as <li>thesqlfile.sql</li> and have a count of all of them too.
So I thought of having two arrays, one with their names, and one with the count of all of them. So in this case which method would be best fit to iterate ?
Method I:
<?php
$files = array();
foreach (glob("backup/*.txt") as $filename) {
$files[]= $filename;
}
$count = sizeof($files);
?>
Method II:
function getfoldercontents($dir, $file_display = array(), $exclusions = array()) {
if(!file_exists($dir)){
return FALSE;
}
$dir_contents = scandir($dir);
$contents = array();
foreach ($dir_contents as $file){
$file_parts = explode('.', $file);
$file_type = strtolower(end($file_parts));
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) && !in_array($file, $exclusions)) {
$contents[] = $dir. '/'. $file;
}
}
return $contents;
}
Since glob() already returns an array, you don't need to iterate over it to append to an array at all. Your first method is a little over-complicated. This accomplishes the same thing:
// Just assign the array output of glob() to a variable
$files = glob("backup/*.txt");
$num_files = count($files);
I would say the second is probably better in terms of file-control (through $file_display and $file_exclude), but maybe you should add a check to ensure the current file is not a directory named something.typeyouwishtodisplay

PHP, reading a folder - listing all items with checkboxes and delete them?

i wonder if theres a tutorial out there or you could give me a quick and simple approach how i could do the following task.
i have a folder on my server. i want to build a kind of cms where i can easily delete files from a folder. i know how to upload them, i already found a tutorial.
i think of simply running through all files, creating a list of them with a checkbox in front, selecting the checkbox and pressing a DELETE button.
is this a rather difficult task to get done? do you maybe kno any tutorial or something.
thank you very much!
Start with
List all files
<?php
// file_array() by Jamon Holmgren. Exclude files by putting them in the $exclude
// string separated by pipes. Returns an array with filenames as strings.
function file_array($path, $exclude = ".|..", $recursive = false) {
$path = rtrim($path, "/") . "/";
$folder_handle = opendir($path);
$exclude_array = explode("|", $exclude);
$result = array();
while(false !== ($filename = readdir($folder_handle))) {
if(!in_array(strtolower($filename), $exclude_array)) {
if(is_dir($path . $filename . "/")) {
if($recursive) $result[] = file_array($path, $exclude, true);
} else {
$result[] = $filename;
}
}
}
return $result;
}
?>
then create hyperlinks to the above files to a delete function like;
unlink('filename.jpg');

auto display filename in a directory and auto fill it as value

I want something (final) like this :
<?php
//named as config.php
$fn[0]["long"] = "file name"; $fn[0]["short"] = "file-name.txt";
$fn[1]["long"] = "file name 1"; $fn[1]["short"] = "file-name_1.txt";
?>
What that I want to?:
1. $fn[0], $fn[1], etc.., as auto increasing
2. "file-name.txt", "file-name_1.txt", etc.., as file name from a directory, i want it auto insert.
3. "file name", "file name 1", etc.., is auto split from "file-name.txt", "file-name_1.txt", etc..,
and config.php above needed in another file e.g.
<? //named as form.php
include "config.php";
for($tint = 0;isset($text_index[$tint]);$tint++)
{
if($allok === TRUE && $tint === $index) echo("<option VALUE=\"" . $text_index[$tint]["short"] . "\" SELECTED>" . $text_index[$tint]["long"] . "</option>\n");
else echo("<option VALUE=\"" . $text_index[$tint]["short"] . "\">" . $text_index[$tint]["long"] . "</option>\n");
} ?>
so i try to search and put php code and hope it can handling at all :
e.g.
<?php
$path = ".";
$dh = opendir($path);
//$i=0;
$i= 1;
while (($file = readdir($dh)) !== false) {
if($file != "." && $file != "..") {
echo "\$fn[$i]['short'] = '$file'; $fn[$i]['long'] = '$file(splited)';<br />"; // Test
$i++;
}
}
closedir($dh);
?>
but i'm wrong, the output is not similar to what i want, e.g.
$fn[0]['short'] = 'file-name.txt'; ['long'] = 'file-name.txt'; //<--not splitted
$fn[1]['short'] = 'file-name_1.txt'; ['long'] = 'file-name_1.txt'; //<--not splitted
because i am little known with php so i don't know how to improve code more, there are any good tips of you guys could help me, Please
New answer after OP edited his question
From your edited question, I understand you want to dynamically populate a SelectBox element on an HTML webpage with the files found in a certain directory for option value. The values are supposed to be split by dash, underscore and number to provide the option name, e.g.
Directory with Files > SelectBox Options
filename1.txt > value: filename1.txt, text: Filename 1
file_name2.txt > value: filename1.txt, text: File Name 2
file-name3.txt > value: filename1.txt, text: File Name 3
Based from the code I gave in my other answer, you could achieve this with the DirectoryIterator like this:
$config = array();
$dir = new DirectoryIterator('.');
foreach($dir as $item) {
if($item->isFile()) {
$fileName = $item->getFilename();
// turn dashes and underscores to spaces
$longFileName = str_replace(array('-', '_'), ' ', $fileName);
// prefix numbers with space
$longFileName = preg_replace('/(\d+)/', ' $1', $fileName);
// add to array
$config[] = array('short' => $filename,
'long' => $longFilename);
}
}
However, since filenames in a directory are unique, you could also use this as an array:
$config[$filename] => $longFilename;
when building the config array. The short filename will form the key of the array then and then you can build your selectbox like this:
foreach($config as $short => $long)
{
printf( '<option value="%s">%s</option>' , $short, $long);
}
Alternatively, use the Iterator to just create an array of filenames and do the conversion to long file names when creating the Selectbox options, e.g. in the foreach loop above. In fact, you could build the entire SelectBox right from the iterator instead of building the array first, e.g.
$dir = new DirectoryIterator('.');
foreach($dir as $item) {
if($item->isFile()) {
$fileName = $item->getFilename();
$longFileName = str_replace(array('-', '_'), ' ', $fileName);
$longFileName = preg_replace('/(\d+)/', ' $1', $fileName);
printf( '<option value="%s">%s</option>' , $fileName, $longFileName);
}
}
Hope that's what your're looking for. I strongly suggest having a look at the chapter titled Language Reference in the PHP Manual if you got no or very little experience with PHP so far. There is also a free online book at http://www.tuxradar.com/practicalphp
Use this as the if condition to avoid the '..' from appearing in the result.
if($file != "." && $file != "..")
Change
if($file != "." ) {
to
if($file != "." and $file !== "..") {
and you get the behaviour you want.
If you read all the files from a linux environment you always get . and .. as files, which represent the current directory (.) and the parent directory (..). In your code you only ignore '.', while you also want to ignore '..'.
Edit:
If you want to print out what you wrote change the code in the inner loop to this:
if($file != "." ) {
echo "\$fn[\$i]['long'] = '$file'<br />"; // Test
$i++;
}
If you want to fill an array called $fn:
if($file != "." ) {
$fn[]['long'] = $file;
}
(You can remove the $i, because php auto increments arrays). Make sure you initialize $fn before the while loop:
$fn = array();
Have a look at the following functions:
glob — Find pathnames matching a pattern
scandir — List files and directories inside the specified path
DirectoryIterator — provides a simple interface for viewing the contents of filesystem directories
So, with the DirectoryIterator you simply would do:
$dir = new DirectoryIterator('.');
foreach($dir as $item) {
if($item->isFile()) {
echo $file;
}
}
Notice how every $item in $dir is an SplFileInfo instance and provides access to a number of useful other functions, e.g. isFile().
Doing a recursive directory traversal is equally easy. Just use a RecursiveDirectoryIterator with a RecursiveIteratorIterator and do:
$dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.'));
foreach($dir as $item) {
echo $file;
}
NOTE I am afraid I do not understand what the following line from your question is supposed to mean:
echo "$fn[$i]['long'] = '$file'<br />"; // Test
But with the functions and example code given above, you should be able to do everything you ever wanted to do with files inside directories.
I've had the same thing happen. I've just used array_shift() to trim off the top of the array
check out the documentation. http://ca.php.net/manual/en/function.array-shift.php

Categories