The following code generates a new php file playlist.php which contains the code as in $start $result variable
$path = "./files/";
$path2="http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["PHP_SELF"])."/files/";
//echo $path2;
$folder = opendir($path);
$start="<asx version='3.0'>\n<title>Example ASX playlist</title>";
$Fnm = "./playlist.php";
$inF = fopen($Fnm,"w");
fwrite($inF,$start."\n");
while( $file = readdir($folder) ) {
if (($file != '.')&&($file != '..')&&($file != 'index.htm')){
$result="<entry>\n<title>$file</title>\n<ref href='$path2$file'/>\n<param name='image' value='preview.jpg'/>\n</entry>\n";
fwrite($inF,$result);
}
}
fwrite($inF,"</asx>");
closedir($folder);
fclose($inF);
I want to generate the same code in the same file which contains this code on a specified line number
is this possible ?
The above php script generates the following code on a new file
http://tinypaste.com/ff242cd6
Here's how to append:
$path = "./files/";
$path2="http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["PHP_SELF"])."/files/";
//echo $path2;
$folder = opendir($path);
$start="<asx version='3.0'>\n<title>Example ASX playlist</title>";
$Fnm = "./playlist.php";
// build content
$fileContent=$start.'/n';
while( $file = readdir($folder) ) {
if (($file != '.')&&($file != '..')&&($file != 'index.htm')){
$result="<entry>\n<title>$file</title>\n<ref href='$path2$file'/>\n<param name='image' value='preview.jpg'/>\n</entry>\n";
//append to content
$fileContent .= $result;
}
}
//append to content
$fileContent .= "</asx>";
// append to file and check status
if ( file_put_contents(__FILE__ , $fileContent , FILE_APPEND) === false )
{
echo "failed to put contents in ".__FILE__."<br>";
}
That should do it...
EDIT:
Okay, before I get into it, you should first take a look at some basic PHP tutorials which can be found all over the net.
SO, instead of writing the content to the file, just echo it, and add your dynamic stuff while you echo:
$title='the title of your playlist';
$start="<asx version='3.0'>\n<title>".$title."</title>/n";
while( $file = readdir($folder) ) {
if (($file != '.')&&($file != '..')&&($file != 'index.htm')){
$result="<entry>\n<title>$file</title>\n<ref href='$path2.$file'/>\n<param name='image' value='preview.jpg'/>\n</entry>\n";
}
}
$endCont = $start.$result."</asx>";
echo $endCont;
I created a new variable called $title. The value of that will be the title generated in the output. You can do this with other tags too like you've done with <entry>\n<title>$file</title>.
echo highlight_file(__FILE__,true);
http://www.php.net/manual/en/function.show-source.php
This gets you back the source code of the current file.
Related
I want to display the links separately. One list would include all the .html links and the other all the .jpg links.
right now it displays this and I understand why it is doing it, but when i do another foreach outside or even right before the echo, its like nothing is passing into it.
.jpg
.html
.jpg
.html
I need it to display like this
HTML-Backup HTML
.jpg .html
.jpg .html
php Code
$array = array();
$html= "";
$htmlBackup= "";
if(file_exists("uploads/" . $_POST["prefix"] .'/'))
{
$dir = 'uploads/' . $_POST["prefix"] . '/';
$files = preg_grep('~\.(jpeg|jpg|png)$~', scandir($dir));
$prefixDir = scandir($dir);
foreach($prefixDir as $dir_files)
{
$secondDir = $dir . $dir_files;
//$finalDir=scandir($secondDir);
if((is_dir($secondDir)))
{
$finalDir=preg_grep('~\.(html|jpg)$~', scandir($secondDir));
$i = 0;
foreach($finalDir as $lastDir)
{
if(strpos($lastDir, "HTML5.jpg") !== false)
{
echo''.$lastDir.' </br>';
//variable to store list of dir
$html=$lastDir;
} else if(strpos($lastDir, "HTML5.html") !== false )
{
echo''.$lastDir.' </br>';
//variable to store the list of dir
$htmlBackup=$lastDir;
}
}
}
}
}
Don't put <br> at the end of each echo. Do it after the inner loop so all links from the same directory will be on the same line.
foreach($prefixDir as $dir_files)
{
$secondDir = $dir . $dir_files;
//$finalDir=scandir($secondDir);
if((is_dir($secondDir)))
{
$finalDir=preg_grep('~\.(html|jpg)$~', scandir($secondDir));
$i = 0;
foreach($finalDir as $lastDir)
{
if(strpos($lastDir, "HTML5.jpg") !== false)
{
echo''.$lastDir.'';
//variable to store list of dir
$html=$lastDir;
} else if(strpos($lastDir, "HTML5.html") !== false )
{
echo''.$lastDir.'';
//variable to store the list of dir
$htmlBackup=$lastDir;
}
}
echo "<br>";
}
}
I found a solution by including arrays.
foreach($prefixDir as $dir_files)
{
$secondDir = $dir . $dir_files;
//$finalDir=scandir($secondDir);
if((is_dir($secondDir)))
{
$finalDir=preg_grep('~\.(html|jpg)$~', scandir($secondDir));
$i = 0;
foreach($finalDir as $lastDir)
{
if(strpos($lastDir, "HTML5.html") !== false || strpos($lastDir, "H5.html") !== false)
{
//variable to store the list of dir
array_push($html_array, $lastDir);
array_push($html_dir,$secondDir.'/'.$lastDir);
}
else if(strpos($lastDir, "HTML5.jpg") !== false || strpos($lastDir, "H5.jpg")!== false )
{
//variable to store list of dir
array_push($html_backup_array, $lastDir);
array_push($html_backup_dir,$secondDir.'/'.$lastDir);
}
}
}
}
and then display them under in another foreach as I want
if(!empty($html_array))
{
echo "<p>";
echo ("<p><span class='heading'>HTML5 Units</span></p>");
foreach (array_combine($html_dir, $html_array) as $html_dirr => $html_arrays)
{
echo (''.$html_arrays.'');
echo "<br>";
}
echo "</p>";
}
How may i able to retrieve different file extensions in a certain directory. Let say i have a folder named "downloads/", where inside that folder are different types of files like PDFs, JPEGs, DOC files etc. So in my PHP code i wanted those files be retrieved and listed with there file names and file extensions. Example: Inside "downloads/" folder are different files
downloads/
- My Poem.doc
- My Photographs.jpg
- My Research.pdf
So i wanted to view those files where i can get there file names, file extensions, and file directories. So in view will be something like this
Title: My Poem
Type: Document
Link: [url here]
Title: My Photographs
Type: Image
Link: [url here]
Title: My Research
Type: PDF
Link: [url here]
Anyone knows how to do it in php? Thanks a lot!
It's pretty simple. To be honest i don't know why didn't you searched on a php.net. They got whole lots of examples for this. Check it in here: click
Example:
<?php
function process_dir($dir,$recursive = FALSE) {
if (is_dir($dir)) {
for ($list = array(),$handle = opendir($dir); (FALSE !== ($file = readdir($handle)));) {
if (($file != '.' && $file != '..') && (file_exists($path = $dir.'/'.$file))) {
if (is_dir($path) && ($recursive)) {
$list = array_merge($list, process_dir($path, TRUE));
} else {
$entry = array('filename' => $file, 'dirpath' => $dir);
//---------------------------------------------------------//
// - SECTION 1 - //
// Actions to be performed on ALL ITEMS //
//----------------- Begin Editable ------------------//
$entry['modtime'] = filemtime($path);
//----------------- End Editable ------------------//
do if (!is_dir($path)) {
//---------------------------------------------------------//
// - SECTION 2 - //
// Actions to be performed on FILES ONLY //
//----------------- Begin Editable ------------------//
$entry['size'] = filesize($path);
if (strstr(pathinfo($path,PATHINFO_BASENAME),'log')) {
if (!$entry['handle'] = fopen($path,r)) $entry['handle'] = "FAIL";
}
//----------------- End Editable ------------------//
break;
} else {
//---------------------------------------------------------//
// - SECTION 3 - //
// Actions to be performed on DIRECTORIES ONLY //
//----------------- Begin Editable ------------------//
//----------------- End Editable ------------------//
break;
} while (FALSE);
$list[] = $entry;
}
}
}
closedir($handle);
return $list;
} else return FALSE;
}
$result = process_dir('C:/webserver/Apache2/httpdocs/processdir',TRUE);
// Output each opened file and then close
foreach ($result as $file) {
if (is_resource($file['handle'])) {
echo "\n\nFILE (" . $file['dirpath'].'/'.$file['filename'] . "):\n\n" . fread($file['handle'], filesize($file['dirpath'].'/'.$file['filename']));
fclose($file['handle']);
}
}
?>
You could use glob & pathinfo:
<?php
foreach (glob(__DIR__.'/*') as $filename) {
print_r(pathinfo($filename));
}
?>
You will try this code :
$Name = array();
$ext = array();
$downloadlink = array();
$dir = 'downloads'
while ($file= readdir($dir))
{
if ($file!= "." && $file!= "..")
{
$temp = explode(".",$file);
if (count($temp) > 1)
{
$Name[count($Name)] = $temp[0];
swich($ext)
{
case "doc" :
{
$ext[count($ext)] = "Document";
break;
}
[...]
default :
{
$ext[count($ext)] = "Error";
break;
}
}
$downloadlink[count($downloadlink)] = "http://yourdomain.com/".$dir."/".$file;
}
}
}
closedir($dir);
for($aux = 0; $aux < count($Name); $aux++)
{
echo "Name = " . $Name[$aux]."<br />
Type = " . $ext[$aux]."<br/>
Link = " . $downloadlink[$aux]."<br/>
";
}
I used the following code to display the contents of a Folder say images (Both Directories as well as Files in that folder)
<?php
$dir="images/"; // Directory where files are stored
if ($dir_list = opendir($dir))
{
while(($filename = readdir($dir_list)) !== false)
{
$newvar1="$dir$filename";// For Hyperlink Path
?>
<p><a href="<?php echo $newvar1; ?>"><?php echo $filename;
?></a></p>
<?php
}
closedir($dir_list);
}
?>
But the PHP file shows an output with two additional Links
A link to the folder 'images' and
A Link to the 'Homepage'.
I tried to filter those two links with "filesize" function but getting some error.
How can I resolve this?
Skip current dir and parent dir with a check.
while(...) {
if($filename == ".." || $filename == ".") continue;
...
}
Modify your code to something like this:
while(($filename = readdir($dir_list)) !== false)
{
if($filename != '.' || $filename != '..') // This part to check and ignore
$newvar1="$dir$filename";// For Hyperlink Path
else
continue; //while loop will no further be processed!
//...
}
This is a more in-depth answer and I'm so fed up with such things... This is absolutely an horrible piece of code, even though Php does permit such horrible things.
Something like this is easier to read, easier to maintain, and easier to debug:
<?php
$tab = array();
$dir="images/"; // Directory to parse
if ($dir_list = opendir($dir))
{
while(($filename = readdir($dir_list)) !== false)
{
if($filename != ".." && $filename != ".")
{
$tab[$filename] = $dir.$filename; // Hyperlink Path
}
}
closedir($dir_list);
}
/* Display separated from logic */
foreach ($tab as $filename => $hyperlink)
{
echo '<p>'.$filename.'</p>';
}
?>
More compact but a bit less easy to read:
<?php
$tab = array();
$dir="images/"; // Directory to parse
if ($dir_list = opendir($dir)) {
while(($filename = readdir($dir_list)) !== false) {
if($filename != ".." && $filename != ".") {
$tab[$filename] = $dir.$filename; // Hyperlink Path
}
}
closedir($dir_list);
}
/* Display separated from logic */
foreach ($tab as $filename => $hyperlink) {
echo '<p>'.$filename.'</p>';
}
?>
And some people (including my old teachers) tell that "if there's one line of code, don't use {}" (which I strongly disagree because it may lead to errors later on) but here's the "optimized" version:
<?php
$tab = array();
$dir="images/";
if ($dir_list = opendir($dir)) {
while(($filename = readdir($dir_list)) !== false)
if($filename != ".." && $filename != ".")
$tab[$filename] = $dir.$filename; // Hyperlink Path
closedir($dir_list);
}
foreach ($tab as $filename => $hyperlink)
echo '<p>'.$filename.'</p>';
?>
I have a code to check if directory is empty, so that i will be able to perform actions, but this simple code gives an error:
Warning: opendir(/Site/images/countries/abc/a/2.swf,/Site/images/countries/abc/a/2.swf) [function.opendir]: The system cannot find the path specified. (code: 3) in C:\wamp\www\Site\index.PHP on line 374
There is no such file
function IsNotEmpty($folder){
$files = array ();
if ( $handle = opendir ( $folder ) )
{
while ( false !== ( $file = readdir ( $handle ) ) )
{
if ( $file != "." && $file != ".." )
{
$files [] = $file;
}
}
closedir ( $handle );
}
return ( count ( $files ) > 0 ) ? TRUE: FALSE; }
$dir ="/Site/images/countries/abc/a/2.swf";
if (IsNotEmpty($dir)==true)
{
echo "There is no such file";
}
else
{
echo "The file exists!";
};
I don't understand what is wrong here. The file exits in the specified directory.
opendir is for opening directories, not files :-)
You can also try temporarily putting in debug stuff so that you can see what's happening:
function IsNotEmpty ($folder) {
$files = array ();
if ($handle = opendir ($folder)) {
echo "DEBUG opened okay ";
while (false !== ($file = readdir ($handle))) {
if ( $file != "." && $file != ".." ) {
$files [] = $file;
echo "DEBUG got a file ";
}
}
closedir ($handle);
} else {
echo "DEBUG cannot open ";
}
return (count($files) > 0 ) ? TRUE : FALSE;
}
$dir ="/Site/images/countries/abc/a";
if (IsNotEmpty($dir)) {
echo "There is no such file";
} else {
echo "The file exists!";
}
If that's still not working and you're sure the directory exists (remember, case is important for UNIX), you may want to look into the permissions on that directory to ensure that the user ID trying to access it is allowed.
You chould use the following snippet as body for your function:
$aFiles = glob($sFolder);
return (sizeof($aFiles) < 1) true : false;
This will get the contents of the folder as an array, when empty - your directory is empty.
Try for instance this:
function IsNotEmpty($dir) {
$dir = rtrim($dir, '/').'/';
return is_dir($dir) && count(glob($dir.'*.*') > 2);
}
Christine, try removing the trailing slash:
$dir ="/Site/images/countries/abc/a/"
Becomes
$dir ="/Site/images/countries/abc/a"
i have the following function when i try and return the vaule its only shows 1 folder but when i echo the function it show the correct informaion.
PHP Code:
$FolderList = "";
function ListFolder($path) {
$path = str_replace("//","/",$path);
//using the opendir function
$dir_handle = #opendir($path) or die("Unable to open $path");
//Leave only the lastest folder name
$dirname = end(explode("/", $path));
//display the target folder.
$FolderList .= ('<option value="">'.$path.'</option>');
while(false !== ($file = readdir($dir_handle))) {
if($file!="." && $file!="..") {
if(is_dir($path."/".$file)) {
//Display a list of sub folders.
ListFolder($path."/".$file);
}
}
}
//closing the directory
closedir($dir_handle);
return $FolderList; //ERROR: Only Shows 1 Folder
echo $FolderList; //WORKS: Show All The Folders Correctly
}
Thanks
Give this a shot:
function ListFolder($path)
{
$path = str_replace("//","/",$path);
//using the opendir function
$dir_handle = #opendir($path) or die("Unable to open $path");
//Leave only the lastest folder name
$dirname = end(explode("/", $path));
//display the target folder.
$FolderList = ('<option value="">'.$path.'</option>');
while (false !== ($file = readdir($dir_handle)))
{
if($file!="." && $file!="..")
{
if (is_dir($path."/".$file))
{
//Display a list of sub folders.
$FolderList .= ListFolder($path."/".$file);
}
}
}
//closing the directory
closedir($dir_handle);
return $FolderList;
}
echo ListFolder('/path/to/folder/');
I simply changed the $FolderList to be assigned to the return value of the ListFolder function.
Inside your while loop, you're calling ListFolder again. This is okay to do but you're not storing the result anywhere and just echoing the result every time ListFolder is called.
That correct format you're seeing on the page is not that 1 string being echoed at the end. its a single directory being echoed every time ListFolder is being called.
Below is the code that works.
function ListFolder($path)
{
$FolderList = "";
$path = str_replace("//","/",$path);
//using the opendir function
$dir_handle = #opendir($path) or die("Unable to open $path");
//Leave only the lastest folder name
$dirname = end(explode("/", $path));
//display the target folder.
$FolderList .= ('<option value="">'.$path.'</option>');
while (false !== ($file = readdir($dir_handle)))
{
if($file!="." && $file!="..")
{
if (is_dir($path."/".$file))
{
//Display a list of sub folders.
$FolderList .= ListFolder($path."/".$file);
}
}
}
//closing the directory
closedir($dir_handle);
return $FolderList;
}
Each function call has its own variable scope. You need to union the returned value from your recursive call with the one that you’ve gathered in the while loop:
while(false !== ($file = readdir($dir_handle))) {
if($file!="." && $file!="..") {
if(is_dir($path."/".$file)) {
$FolderList .= ListFolder($path."/".$file);
}
}
}
You forgot to catch the return value of the function calls
$FolderList .= ListFolder($path."/".$file);
You just add one folder to the string, than call the function, but do nothing with the return value. Then you return $FolderList, which only contains the one entry you add before the while-loop
When *echo*ing it, its just send directly to the browser independently on which level of recursion you are, so you think, that $FolderList is full, but in fact its just every sungle $FolderList from each recursion step.
Alternative Method
function ListFolder($path, &$FolderList = array()) {
$path = str_replace("//","/",$path);
//using the opendir function
$dir_handle = #opendir($path) or die("Unable to open $path");
//Leave only the lastest folder name
$dirname = end(explode("/", $path));
//display the target folder.
$FolderList[] = '<option value="">'.$path.'</option>';
while(false !== ($file = readdir($dir_handle))) {
if($file!="." && $file!="..") {
if(is_dir($path."/".$file)) {
//Display a list of sub folders.
ListFolder($path."/".$file, $FolderList);
}
}
}
//closing the directory
closedir($dir_handle);
return $FolderList;
}
$paths = ListFolder(getcwd());
echo "<select>".implode("", $paths)."</select>";