Can I stick a php readdir script in a Javascript? - php

I would like to stick a php code (readdir and print links to page) into a Dynamic Ajax Content script like below. Is this even possible as I am getting errors? Any help would be very appreciated.
TEXT HERE DOES NOT MATTER
This is the PHP script I want to use to scan the directory and print links to page.
<?php
// These files will be ignored
$excludedFiles = array (
'excludeMe.file',
'excludeMeAs.well'
);
// These file extensions will be ignored
$excludedExtensions = array (
'html',
'xslt',
'htm',
);
// Make sure we ignore . and ..
$excludedFiles = array_merge($excludedFiles,array('.','..'));
// Convert to lower case so we are not case-sensitive
for ($i = 0; isset($excludedFiles[$i]); $i++) $excludedFiles[$i] =
strtolower(ltrim($excludedFiles[$i],'.'));
for ($i = 0; isset($excludedExtensions[$i]); $i++) $excludedExtensions[$i] =
strtolower($excludedExtensions[$i]);
// Loop through directory
$dir = 'dir_1/dir_2/';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
$extn = explode('.',$file);
$extn = array_pop($extn);
// Only echo links for files that don't match our rules
if (!in_array(strtolower($file),$excludedFiles) &&
!in_array(strtolower($extn),$excludedExtensions)) {
$count++;
print("".$file."<br />\n");
}
}
echo '<br />';
closedir($handle);
}
?>

I think you might be missing a html element with the id of rightcolumn?
You need to add a div or some other container on the page with the id of rightcolumn. The script will then populate this container with the output of your php script.

Related

How to search/filter node content inside of xml file with SimpleXMLElement - php

I need to filter/search all links (png,jpg,mp3) from an XXML file but I got stuck there. I did for example to get all mp3 but I did it knowing that was there, but for example if I put other file where the path is different, then it won't detect it.
foreach($xml->BODY->GENERAL->SOUNDS->SOUND as $a){
echo ''.$a->PATH.'<br>';
}
Example XML
You could get the extension of each file and compare it to an array of "accepted extensions". Then use, continue to skip to write link:
$accepted_exts = ['png','jpg','mp3'];
foreach($xml->BODY->GENERAL->SOUNDS->SOUND as $a) {
$path = $a->PATH;
$ext = strtolower(substr($path, strrpos($path, '.') + 1));
if (!in_array($ext, $accepted_exts)) continue ; // continue to next iteration
echo ''.$path.'<br>'; // write the link
}
To get other links:
$accepted_exts = ['png','jpg','mp3'];
$links = [] ;
foreach($xml->HEAD as $items) {
foreach ($items as $item) {
$path = (string)$item;
if (!in_array(get_ext($path), $accepted_exts)) continue ; // continue to next iteration
$links[] = $path ;
}
}
foreach($xml->BODY->GENERAL->SOUNDS->SOUND as $a) {
$path = $a->PATH;
if (!in_array(get_ext($path), $accepted_exts)) continue ; // continue to next iteration
$links[] = $path ;
}
foreach ($links as $path) {
echo ''.$path.'<br>'; // write the link
}
function get_ext($path) {
return strtolower(substr($path, strrpos($path, '.') + 1));
}
Will outputs:
http://player.glifing.com/img/Player/blue.png<br>
http://player.glifing.com/img/Player/blue_intro.png<br>
http://player.glifing.com/upload/fondoinstrucciones2.jpg<br>
http://player.glifing.com/upload/stopbet2.png<br>
http://player.glifing.com/upload/goglif2.png<br>
http://player.glifing.com/img/Player/Glif 3 OK.png<br>
http://player.glifing.com/img/Player/BetPensant.png<br>
http://player.glifing.com/audio/Player/si.mp3<br>
http://player.glifing.com/audio/Player/no.mp3<br>
To save having to know which individual tags may contain a URL, you can use XPath to search for any text content that starts with "http://" or "https://". Then process each part to check the extension.
$xml = simplexml_load_file("data.xml");
$extensions = ['png', 'jpg', 'mp3'];
$links = $xml->xpath('//text()[starts-with(normalize-space(), "http://")
or starts-with(normalize-space(), "https://")]');
foreach ( $links as $link ) {
$link = trim(trim($link),"_");
$path = parse_url($link, PHP_URL_PATH);
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
if ( in_array($extension, $extensions)) {
// Do something
echo $link.PHP_EOL;
}
else {
echo "Rejected:".$link.PHP_EOL;
}
}
I found that using trim() helped clean up URL's which had blank lines after them (or at least some extra whitespace). And convert them all to lower to make checking easier.
You may not need the rejected bit, but I put it in to test my code.
You would have to repeat the above

php loop through files in subfolders in folder and get file paths

Im really new to PHP i searched google to find a correct script that loops through all subfolders in a folder and get all files path in that subfolder
<?php
$di = new RecursiveDirectoryIterator('posts');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
echo $filename. '<br/>';
}
?>
So i have folder 'posts' in which i have subfolder 'post001' in which i have two files
controls.png
text.txt
And the code above echos this
posts\.
posts\..
posts\post001\.
posts\post001\..
posts\post001\controls.png
posts\post001\text.txt
But i want to echo only the file paths inside these subfolders like this
posts\post001\controls.png
posts\post001\text.txt
The whole point of this is that i want to dynamically create divs for each subfolder and inside this div i put img with src and some h3 and p html tags with text equal to the .txt file so is this proper way of doing that and how to remake my php script so that i get just the file paths
So I can see the answers and they are all correct but now my point was that i need something like that
foreach( glob( 'posts/*/*' ) as $filePath ){
//create div with javascript
foreach( glob( 'posts/$filePath/*' ) as $file ){
//append img and h3 and p html tags to the div via javascript
}
//append the created div somewhere in the html again via javascript
}
So whats the correct syntax of doing these two foreach loops in php im really getting the basics now
See if this works :)
$di = new RecursiveDirectoryIterator('posts');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
if ((substr($file, -1) != '.') && (substr($file, -2) != '..')) {
echo $file . '<br/>';
}
}
<h1>Directory Listing</h1>
<?php
/**
* Recursive function to append the full path of all files in a
* given directory $dirpath to an array $context
*/
function getFilelist($dirpath, &$context){
$fileArray = scandir($dirpath);
if (count($fileArray) > 2) {
/* Remove the . (current directory) and .. (parent directory) */
array_shift($fileArray);
array_shift($fileArray);
foreach ($fileArray as $f) {
$full_path = $dirpath . DIRECTORY_SEPARATOR . $f;
/* If the file is a directory, call the function recursively */
if (is_dir($full_path)) {
getFilelist($full_path, $context);
} else {
/* else, append the full path of the file to the context array */
$context[] = $full_path;
}
}
}
}
/* $d is the root directory that you want to list */
$d = '/Users/Shared';
/* Allocate the array to store of file paths of all children */
$result = array();
getFilelist($d, $result);
$display_length = false;
if ($display_length) {
echo 'length = ' . count($result) . '<br>';
}
function FormatArrayAsUnorderedList($context) {
$ul = '<ul>';
foreach ($context as $c) {
$ul .= '<li>' . $c . '</li>';
}
$ul .= '</ul>';
return $ul;
}
$html_list = FormatArrayAsUnorderedList($result);
echo $html_list;
?>
Take a look at this:
<?php
$filename[] = 'posts\.';
$filename[] = 'posts\..';
$filename[] = 'posts\post001\.';
$filename[] = 'posts\post001\..';
$filename[] = 'posts\post001\controls.png';
$filename[] = 'posts\post001\text.txt';
foreach ($filename as $file) {
if (substr($file, -4, 1) === ".") {
echo $file."<br>";
}
}
?>
Result:
posts\post001\controls.png
posts\post001\text.txt
What this does is checking if the 4th last digit is a dot. If so, its an extension of three letters and it should be a file. You could also check for specific extensions.
$ext = substr($file, -4, 4);
if ($ext === ".gif" || $ext === ".jpg" || $ext === ".png" || $ext === ".txt") {
echo $file."<br>";
}

How to get only email value from HTML files using DOM ? Only Email value not like link

http://www.frosher.com/schools/acme-academy-burdwan/contact
This is the page link which i saved in my folder and get the their address with their all contact information of the school. You also seen their is email and web link before the Google map block. I want to get email value.
Just save this html page in scraping folder. Here's my code:
<?php
include('simple_html_dom.php');//Required
$i = 0;
$dir = 'scraping/';//folder name in which your html file
if ($handle = opendir($dir)) {
while (($file = readdir($handle)) !== false){
if (!in_array($file, array('.', '..')) && !is_dir($dir.$file))
$i++;
}
}
$filenames = array();
foreach(glob('scraping/*.*') as $filename){
$filenames[] = $filename;//get all files name which are in my folder
}
$i = 1;
foreach($filenames as $val){
$doc = new DomDocument();
$doc = file_get_html($val);
$ret = $doc->find('div[class=span5]');
foreach($doc->find('.span7') as $element){
$contact = $element->plaintext;
if (preg_match("/\bEmail\b/i", $contact, $match)) {
$n = 0; // i have used $n for counting because in span7 div their are two a tag so i need only first time value.
foreach($doc->find('.span7 a') as $element){
if($n == 0){
$email = $element;
$n = $n+1;
}
}
}
else{
$email = 'Null';
}
echo $email;
}
echo '<br/>';
}
?>
This is php script code save it with a file name and place both the php file and scraping folder in common folder like leo is the folder in which php file placed and scraping folder also in it.
Now run the php file and you will see the output. If not then you have to include also "simple_html_dom.php" in leo folder.
If you are getting whole tag then try following
foreach($doc->find('.span7 a') as $element){
$email = $element;
$email = strip_tags($email);
//now you can check email
}

php count files from multiple folders and echo total

I have a php code that will display the amount of files that i have in a folder.
Code: This will echo this on my page, "There are a total of 119 Articles"
$directory = "../health/";
if (glob($directory . "*.php") != false) /* change php to the file you require either html php jpg png. */ {
$filecount = count(glob($directory . "*.php")); /* change php to the file you require either html php jpg png. */
echo "<p>There are a total of";
echo " $filecount ";
echo "Articles</p>";
} else {
echo 0;
}
Question:
I am wanting to count the files from 27 or more folders and echo the total amount of files.
Is there away i can add a list of folders to open such as:
$directory = "../health/","../food/","../sport/";
then it will count all the files and display the total "There are a total of 394 Articles"
Thanks
Yes you can:
glob('../{health,food,sport}/*.php', GLOB_BRACE);
Undoubtedly, this is less efficient than clover's answer:
$count = 0;
$dirs = array("../health/","../food/","../sport/");
foreach($dirs as $dir){
if($files = glob($dir."*.php")){
$count += count($files);
}
}
echo "There are a total of $count Articles";
A simple answer is to just use an array and a loop. It is something you could have figured out yourself.
$directories = array('../health/', '../food/', '../sport/');
$count = 0;
foreach ($directories as $dir) {
$files = glob("{$dir}*.php") ?: array();
$count += count($files);
}
echo "<p>There are a total of {$count} articles</p>";
But #clover's answer is better.
As usual, it's often much better to divide your problem. E.g.:
Obtain the files (See glob).
Count the files of a glob result (Write a function that takes care of two the FALSE and Array cases.).
Do the output (don't do the output inside the other code, do it at the end, use variables (as you already do, just separate the output)).
Some Example Code:
/**
* #param array|FALSE $mixed
* #return int
* #throws InvalidArgumentException
*/
function array_count($mixed) {
if (false === $mixed) {
return 0;
}
if (!is_array($mixed)) {
throw new InvalidArgumentException('Parameter must be FALSE or an array.');
}
return count($mixed);
}
$directories = array("health", "food", "string");
$pattern = sprintf('../{%s}/*.php', implode(',', $directories));
$files = glob($pattern, GLOB_BRACE);
$filecount = array_count($files);
echo "<p>There are a total of ", $filecount, " Article(s)</p>";
You could use the opendir command explained here:
http://www.php.net/manual/en/function.opendir.php
combined with the example shown on previous link:
<?php
$dir = "/etc/php5/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
?>
Basically opening the folder you first go through and in a loop count every singel item that is not a folder.
Edit:
Seems like someone has given a simpler solution than this.

Getting word count for all files within a folder

I need to find word count for all of the files within a folder.
Here is the code I've come up with so far:
$f="../mts/sites/default/files/test.doc";
// count words
$numWords = str_word_count($str)/11;
echo "This file have ". $numWords . " words";
This will count the words within a single file, how would I go about counting the words for all files within a given folder?
how about
$array = array( 'file1.txt', 'file2.txt', 'file3.txt' );
$result = array();
foreach($array as $f ){
$result[$f] = str_word_count(file_get_contents($f));
}
and using the dir
if ($handle = opendir('/path/to/files')) {
$result = array();
echo "Directory handle: $handle\n";
echo "Files:\n";
/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle))) {
if($file == '.' || $file == '..')
continue;
$result[$file] = str_word_count(file_get_contents('/path/to/files/' . $file));
echo "This file {$file} have {$result[$file]} words";
}
closedir($handle);
}
Lavanya, you can consult the manual of readdir, file_get_contents.
Assuming the doc files are plaintext and don't contain additional markup, you can use the following script to count all of the words in all of the files:
<?php
$dirname = '/path/to/file/';
$files = glob($dirname.'*');
$total = 0;
foreach($files as $path) {
$count = str_word_count(file_get_contents($path));
print "\n$path has $count words\n";
$total += $count;
}
print "Total words: $total\n\n";
?>
If you are using *nux than you can use system('cat /tmp/* | wc -w')
You can use $words = str_word_count(file_get_contents($filepath)) to get the word count of a text file, however this won't work for word docs. You'll need to find a library or external program that can read the .doc file format.

Categories