Php read directory with absolute path - php

I have this php script which reads mp3 files from the directory:
// Set your return content type
header('Content-type: text/xml');
//directory to read
$dir = ($_REQUEST['dir']);
$sub_dirs = isBoolean(($_REQUEST['sub_dirs']));
if(file_exists($dir)==false){
//echo $_SERVER['DOCUMENT_ROOT'];
//echo "current working directory is -> ". getcwd();
echo 'Directory \'', $dir, '\' not found!';
}else{
$temp = getFileList($dir, $sub_dirs);
echo json_encode($temp);
}
function isBoolean($value) {
if ($value && strtolower($value) !== "false") {
return true;
} else {
return false;
}
}
function getFileList($dir, $recurse){
$retval = array(); // array to hold return value
if(substr($dir, -1) != "/") // add trailing slash if missing
$dir .= "/"; // open pointer to directory and read list of files
$d = #dir($dir) or die("getFileList: Failed opening directory $dir for reading");
while(false !== ($entry = $d->read())) { // skip hidden files
if($entry[0] == "." || $entry[0] == "..") continue;
if(is_dir("$dir$entry")) {
if($recurse && is_readable("$dir$entry/")) {
$retval = array_merge($retval, getFileList("$dir$entry/", true));
}
}else if(is_readable("$dir$entry")) {
$path_info = pathinfo("$dir$entry");
if(strtolower($path_info['extension'])=='mp3'){
$retval[] = array(
"path" => "$dir$entry",
"type" => $path_info['extension'],
"size" => filesize("$dir$entry"),
"lastmod" => filemtime("$dir$entry")
);
}
}
}
$d->close();
return $retval;
}
This file sits in the same directory as the html page which executes the script. For example, I pass the relative path 'audio/mp3' or '../audio/mp3' and it all works well.
Is it possible to make this read directory with absolute path?
For example, if I would pass this: http://www.mydomain.com/someFolder/audio/mp3, and html page which executes the script and the php file would be placed in this location: http://www.mydomain.com/someFolder/
Thank you!

Web root is always just /. You'd never need the hostname or protocol part, and root can be only root of the server, not some folder or file.
If you need some path, like /testthesis/ - there are ways, but it has nothing common with web root.
If you need a filesystem directory for the webroot - it's in the $_SERVER['DOCUMENT_ROOT'] variable.

Related

PHP File count inside a folder

I'm using bootstrap tables and rows to count how much files are in a folder, but the destination is pointing to a different server the code below does not work.
As i'm using localhost (xampp) trying to do this don't know if its possible.
<?php
// integer starts at 0 before counting
$i = 0;
$dir = 'uploads/'; <!--\\189.207.00.122\folder1\folder2\folder3\test-->
if ($handle = opendir($dir)) {
while (($file = readdir($handle)) !== false){
if (!in_array($file, array('.', '..')) && !is_dir($dir.$file))
$i++;
}
}
// prints out how many were in the directory
echo "There were $i files";
?>
Here is a handy little function you might want to try out. Just pass the path to the Directory as the first argument to it and you'd get your result.
NOTE: This Function is RECURSIVE, which means: it will traverse all sub-directories... to disable this behaviour, simply comment out or delete the following lines towards the end of the Funciton:
<?php
}else if(is_dir($temp_file_or_dir) && !preg_match('/^\..*/', $val) ){
getFilesInFolder($temp_file_or_dir);
}
THE CODE:
<?php
$folder = dirname(__FILE__).'/uploads'; // ASSUMES YOUR uploads DIRECTORY
// IS IN THE SAME DIRECTORY AS index.php
// (/htdocs/php/pages)
// OR
$folder = dirname(__FILE__).'/../uploads'; // ASSUMES YOUR uploads DIRECTORY
// IS ONE DIRECTORY ABOVE
// THE CURRENT DIRECTORY (/htdocs/php)
// THIS IS MOST LIKELY RIGHT
// OR
$folder = dirname(__FILE__).'/../../uploads';// ASSUMES YOUR uploads DIRECTORY
// IS TWO DIRECTORIES ABOVE
// THE CURRENT DIRECTORY (/htdocs)
// MAKE SURE THE FOLDER IN QUESTION HAS THE RIGHT PERMISSIONS
// OR RATHER CHANGE PERMISSIONS ON THE FOLDER TO BE ABLE TO WORK WITH IT
chmod($folder, 0777);
var_dump(getFilesInFolder($folder));
// IF YOU PASS false AS THE THE 2ND ARGUMENT TO THIS FUNCTION
// YOU'D GET AN ARRAY OF ALL FILES IN THE $path2Folder DIRECTORY
// AS WELL AS IN SUB-DIRECTORIES WITHIN IT...
function getFilesInFolder($path2Folder, $countOnly=true){
$files_in_dir = scandir($path2Folder);
$returnable = array();
foreach($files_in_dir as $key=>$val){
$temp_file_or_dir = $path2Folder . DIRECTORY_SEPARATOR . $val;
if(is_file($temp_file_or_dir) && !preg_match("#^\..*#", $temp_file_or_dir)){
$arrRX = array('#\.{2,4}$#', '#\.#');
$arrReplace = array("", "_");
$returnVal = preg_replace($arrRX, $arrReplace, $val);
$returnable[$returnVal] = $temp_file_or_dir;
}else if(is_dir($temp_file_or_dir) && !preg_match('/^\..*/', $val) ){
getFilesInFolder($temp_file_or_dir);
}
}
return ($countOnly) ? count($returnable) : $returnable;
}
Use $_SERVER['DOCUMENT_ROOT'] to get your root directory.
$dir = $_SERVER['DOCUMENT_ROOT'].'/uploads/';

Getting Videos from server directory to display in container on page using PHP

I have been trying to modify some PHP to allow my page to get to a directory and its sub-directories to get video files to display dynamically on my page, I'm using the scripts as follows
$imagetypes = array("video/ogv", "video/webm", "video/mp4");
$dir = "../uploadedVideo/*/";
function getImages($dir)
{
global $imagetypes;
// array to hold return value
$retval = array();
// add trailing slash if missing
if(substr($dir, -1) != "/") $dir .= "/";
// full server path to directory
$fulldir = "{$_SERVER['DOCUMENT_ROOT']}/$dir";
$d = #dir($fulldir) or die("getVideo: Failed opening directory $dir for reading");
while(false !== ($entry = $d->read())) {
// skip hidden files
if($entry[0] == ".") continue;
// check for image files
$f = escapeshellarg("$fulldir$entry");
$mimetype = trim(`file -bi $f`);
foreach($imagetypes as $valid_type) {
if(preg_match("#^{$valid_type}#", $mimetype)) {
$retval[] = array(
'file' => "/$dir$entry",
'size' => getimagesize("$fulldir$entry")
);
break;
}
}
}
$d->close();
return $retval;
}
This the top of my page before the HTML
This the div I'm looking to display static images or thumbnail, which when clicked on will be viewed in the page
<div class="vidSelect">
<?php
// fetch image details
$video = getImages("video");
// display on page
foreach($video as $vid) {
echo "<div class=\"vidContainer\" src=\"{$vid['file']}\"
{$vid['size'][3]}></div>\n";
} ?>
</div>
I haven't as yet sorted the video player, as I'm just looking to get the videos to show up first but have run out of ideas and skills to get any further.
It looks as if something is being seen as 3 div containers are being created although there are five sub directories within one main directory I want to access, Any help would be most gratefully received
So I see your Type is wrong from the comments. Also the Source is not correct.
function getImages($dir) {
global $imagetypes;
// array to hold return value
$retval = array();
// add trailing slash if missing
if (substr($dir, -1) != "/") $dir. = "/";
// full server path to directory
$fulldir = "{$_SERVER['DOCUMENT_ROOT']}/$dir";
$d = #dir($fulldir) or die("getVideo: Failed opening directory $dir for reading");
while (false !== ($entry = $d - > read())) {
// skip hidden files
if ($entry[0] == ".") continue;
// check for image files
$f = escapeshellarg("$fulldir$entry");
$mimetype = trim(`file - bi $f`);
foreach($imagetypes as $valid_type) {
if (preg_match("#^{$valid_type}#", $mimetype)) {
$retval[] = array(
'file' = > "$dir$entry",
'size' = > getimagesize("$fulldir$entry"));
break;
}
}
}
$d - > close();
return $retval;
}
Then in your HTML:
< div class = "vidSelect" >
<? php
// fetch image details
$video = getImages("video");
// display on page
foreach($video as $vid) {
echo "<div class='vidContainer' src='{$vid['file']}' type='{$vid['size']['mime']}'></div>\n";
} ?>
< /div>

php duplicate a file in other folders

Is there a way I could use php to make root file to look like its also in other folders too.
For example I have index.php in root folder and I want it to be like that when I access index.php then it could also behave as its in all the folders and subfolders too
When I execute index.php then it will also execute in all folders and subfolders too
Please understand my question by the example below
index.php is in root and I have different folders in root as well so when I access the index.php through browser then it will also execute in other folders
http://mysite.com/index.php will also behave as if its in sub folder too
http://mysite.com/folder1/index.php
http://mysite.com/folder2/index.php
http://mysite.com/folder3/index.php
index.php is not in these folders but it must execute in these folders too at the same time
I think its not difficult to understand through above examples.please answer accordingly
Update 2
Here is the index.php code
It scans the folders "files" "images" "txt" "related" and get the files in each folder and then it writes to the includes.php (in root)
$path = array("./files/","./images/","./txt/","./related/");
$path2= array("http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["PHP_SELF"])."/files/","http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["PHP_SELF"])."/images/","http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["PHP_SELF"])."/txt/","http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["PHP_SELF"])."/related/");
$start="";
$Fnm = "./include.php";
$inF = fopen($Fnm,"w");
fwrite($inF,$start."\n");
$folder = opendir($path[0]);
while( $file = readdir($folder) ) {
if (($file != '.')&&($file != '..')&&($file != 'index.htm')) {
$folder2 = opendir($path[1]);
$folder3 = opendir($path[2]);
$folder4 = opendir($path[3]);
$imagename ='';
$txtname ='';
$related ='';
while( $file2 = readdir($folder2) ) {
if (substr($file2,0,strpos($file2,'.')) == substr($file,0,strpos($file,'.'))){
$imagename = $file2;
}
}
while( $file4 = readdir($folder4) ) {
if (substr($file4,0,strpos($file4,'.')) == substr($file,0,strpos($file,'.'))){
$related = $file4;
}
}
while( $file3 = readdir($folder3) ) {
if (substr($file3,0,strpos($file3,'.')) == substr($file,0,strpos($file,'.'))){
$txtname = $file3;
$fh = fopen("/home3/socialb8/public_html/mysite.info/player/txt/$txtname", 'r');
$theData = fread($fh, filesize("/home3/socialb8/public_html/mysite.info/player/txt/$txtname"));
fclose($fh);
}
}
closedir($folder2);
closedir($folder3);
closedir($folder4);
$result="{\nlevels: [\n{ file: \"$path2[0]$file\" }\n],\nimage: \"$path2[1]$imagename\",\ntitle: \"$file\",\ndescription: \"$theData\",\n 'related.file':'$path2[3]$related'\n},\n";
fwrite($inF,$result);
}
}
fwrite($inF,"");
closedir($folder);
fclose($inF);
If you need to cycle through the directories and see if each of those directories contains one of the directories listed in the $path array you could use something like:
function readDirs()
{
$path=array('images','etc...');
$dirHandle = opendir('./');
while($file = readdir($dirHandle))
{
if(is_dir($file) && $file != '.' && $file != '..')
{
$dirHandle2 = opendir($file);
while($file2 = readdir($dirHandle2))
{
if(in_array($file2,$path))
{
// do what you need to do
}
}
}
}
}
readDirs();
That will cycle through all the directories in the root folder and see if they contain a directory listed in the $path array, if so you can pop your code in the // do what you need to do statement.
Hope that helps!

Create file and folders recursively

I got an array containing path names and file names
['css/demo/main.css', 'home.css', 'admin/main.css','account']
I want to create those files and folders if they are not existed yet. Overwrite them if they are already existed.
For each of this paths you'll have to specific whether it is a file or a directory. Or you could make your script assume, that the path is pointing to a file when the basename (the last part of the path) contains a dot.
To create a directory recursively is simple:
mkdir(dirname($path), 0755, true); // $path is a file
mkdir($path, 0755, true); // $path is a directory
0755 is the file permission expression, you can read about it here: http://ch.php.net/manual/en/function.chmod.php
<?php
function mkpath($path)
{
if(#mkdir($path) or file_exists($path)) return true;
return (mkpath(dirname($path)) and mkdir($path));
}
?>
This makes paths recursively.
I have just used a simple way to explode the string and rebuild and check if is a file or a directory
public function mkdirRecursive($path) {
$str = explode(DIRECTORY_SEPARATOR, $path);
$dir = '';
foreach ($str as $part) {
$dir .= DIRECTORY_SEPARATOR. $part ;
if (!is_dir($dir) && strlen($dir) > 0 && strpos($dir, ".") == false) {
mkdir($dir , 655);
}elseif(!file_exists($dir) && strpos($dir, ".") !== false){
touch($dir);
}
}
}
You can use is_dir
if (!is_dir($path))
{
#mkdir($path, 0777, true);
}

move all files in a folder to another?

when moving one file from one location to another i use
rename('path/filename', 'newpath/filename');
how do you move all files in a folder to another folder? tried this one without result:
rename('path/*', 'newpath/*');
A slightly verbose solution:
// Get array of all source files
$files = scandir("source");
// Identify directories
$source = "source/";
$destination = "destination/";
// Cycle through all source files
foreach ($files as $file) {
if (in_array($file, array(".",".."))) continue;
// If we copied this successfully, mark it for deletion
if (copy($source.$file, $destination.$file)) {
$delete[] = $source.$file;
}
}
// Delete all successfully-copied files
foreach ($delete as $file) {
unlink($file);
}
Please try this solution, it's tested successfully ::
<?php
$files = scandir("f1");
$oldfolder = "f1/";
$newfolder = "f2/";
foreach($files as $fname) {
if($fname != '.' && $fname != '..') {
rename($oldfolder.$fname, $newfolder.$fname);
}
}
?>
An alternate using rename() and with some error checking:
$srcDir = 'dir1';
$destDir = 'dir2';
if (file_exists($destDir)) {
if (is_dir($destDir)) {
if (is_writable($destDir)) {
if ($handle = opendir($srcDir)) {
while (false !== ($file = readdir($handle))) {
if (is_file($srcDir . '/' . $file)) {
rename($srcDir . '/' . $file, $destDir . '/' . $file);
}
}
closedir($handle);
} else {
echo "$srcDir could not be opened.\n";
}
} else {
echo "$destDir is not writable!\n";
}
} else {
echo "$destDir is not a directory!\n";
}
} else {
echo "$destDir does not exist\n";
}
tried this one?:
<?php
$oldfolderpath = "old/folder";
$newfolderpath = "new/folder";
rename($oldfolderpath,$newfolderpath);
?>
So I tried to use the rename() function as described and I kept getting the error back that there was no such file or directory. I placed the code within an if else statement in order to ensure that I really did have the directories created. It looked like this:
$tempDir = '/home/site/images/tmp/';
$permanentDir = '/home/site/images/' . $claimid; // this was stored above
mkdir($permanentDir,0775);
if(is_dir($permanentDir)){
echo $permanentDir . ' is a directory';
if(is_dir($tempDir)){
echo $tempDir . ' is a directory';
}else{
echo $tempDir . ' is not a directory';
}
}else{
echo $permanentDir . ' is not a directory';
}
rename($tempDir . "*", $permanentDir);
So when I ran the code again, it spit out that both paths were directories. I was stumped. I talked with a coworker and he suggested, "Why not just rename the temp directory to the new directory, since you want to move all the files anyway?"
Turns out, this is what I ended up doing. I gave up trying to use the wildcard with the rename() function and instead just use the rename() to rename the temp directory to the permanent one.
so it looks like this.
$tempDir = '/home/site/images/tmp/';
$permanentDir = '/home/site/images/' . $claimid; // this was stored above
mkdir($permanentDir,0775);
rename($tempDir, $permanentDir);
This worked beautifully for my purposes since I don't need the old tmp directory to remain there after the files have been uploaded and "moved".
Hope this helps. If anyone knows why the wildcard doesn't work in the rename() function and why I was getting the error stating above, please, let me know.
Move or copy the way I use it
function copyfiles($source_folder, $target_folder, $move=false) {
$source_folder=trim($source_folder, '/').'/';
$target_folder=trim($target_folder, '/').'/';
$files = scandir($source_folder);
foreach($files as $file) {
if($file != '.' && $file != '..') {
if ($move) {
rename($source_folder.$file, $target_folder.$file);
} else {
copy($source_folder.$file, $target_folder.$file);
}
}
}
}
function movefiles($source_folder, $target_folder) {
copyfiles($source_folder, $target_folder, $move=true);
}
try this:
rename('path/*', 'newpath/');
I do not see a point in having an asterisk in the destination
If the target directory doesn't exist, you'll need to create it first:
mkdir('newpath');
rename('path/*', 'newpath/');
As a side note; when you copy files to another folder, their last changed time becomes current timestamp. So you should touch() the new files.
... (some codes for directory looping) ...
if (copy($source.$file, $destination.$file)) {
$delete[] = $source.$file;
$filetimestamp = filemtime($source.$file);
touch($destination.$file,$filetimestamp);
}
... (some codes) ...
Not sure if this helps anyone or not, but thought I'd post anyway. Had a challenge where I has heaps of movies I'd purchased and downloaded through various online stores all stored in one folder, but all in their own subfolders and all with different naming conventions. I wanted to move all of them into the parent folder and rename them all to look pretty. all of the subfolders I'd managed to rename with a bulk renaming tool and conditional name formatting. the subfolders had other files in them i didn't want. so i wrote the following php script to, 1. rename/move all files with extension mp4 to their parent directory while giving them the same name as their containing folder, 2. delete contents of subfolders and look for directories inside them to empty and then rmdir, 3. rmdir the subfolders.
$handle = opendir("D:/Movies/");
while ($file = readdir($handle)) {
if ($file != "." && $file != ".." && is_dir($file)) {
$newhandle = opendir("D:/Movies/".$file);
while($newfile = readdir($newhandle)) {
if ($newfile != "." && $newfile != ".." && is_file("D:/Movies/".$file."/".$newfile)) {
$parts = explode(".",$newfile);
if (end($parts) == "mp4") {
if (!file_exists("D:/Movies/".$file.".mp4")) {
rename("D:/Movies/".$file."/".$newfile,"D:/Movies/".$file.".mp4");
}
else {
unlink("D:/Movies/".$file."/".$newfile);
}
}
else { unlink("D:/Movies/".$file."/".$newfile); }
}
else if ($newfile != "." && $newfile != ".." && is_dir("D:/Movies/".$file."/".$newfile)) {
$dirhandle = opendir("D:/Movies/".$file."/".$newfile);
while ($dirfile = readdir($dirhandle)){
if ($dirfile != "." && $dirfile != ".."){
unlink("D:/Movies/".$file."/".$newfile."/".$dirfile);
}
}
rmdir("D:/Movies/".$file."/".$newfile);
}
}
unlink("D:/Movies/".$file);
}
}
i move all my .json files from root folder to json folder with this
foreach (glob("*.json") as $filename) {
rename($filename,"json/".$filename);
}
pd: someone 2020?

Categories