Hi i have problem with this code
with the code i can change whole my folder file to number like 1.mp4 2.mp4 ect...
i test the code and i print the name of the file from it and every thing is right
but rename function is not working
this is my code
$dir = opendir('.');
$i = 1;
// loop through all the files in the directory
while (false !== ($file = readdir($dir)))
{
// if the extension is '.mp4'
if (strtolower(pathinfo($file, PATHINFO_EXTENSION)) == 'mp4')
{
echo $file ;
// do the rename based on the current iteration
$newName = $i . '.mp4';
rename($file, $newName);
// increase for the next loop
$i++;
}
}
// close the directory handle
closedir($dir);
?>
what is the problem now ?
NEW iNFO
i tried the code inside my localhost and it's work but it's not working inside the server
It's more efficient to use glob()
foreach(glob(__DIR__ . '/*.mp4') as $key => $file) {
if(!rename($file, __DIR__ . '/' . ($key + 1) . '.mp4')) {
throw new Exception('Unable to write to '. $file);
}
}
I'll hazard a guess it's a write permissions issue though - I don't see anything directly wrong with the script.
Getting the real path can help:
$file = realpath($filename);
but it sounds like it could be a permissions issue or an SELinux issue also. You will need apache to be the group on the files in question, and the files should be writeable by the group.
Also, if you have SELinux enabled, you will need to use
semanage fcontext -a -t httpd_sys_rw_content_t "/path/to/images/folder(/.*)?"
and
restorecon -R -v /path/to/images/folder
Related
I'm trying to turn the files in my 'objects' directory into an array, then use them to load the objects. But, for some reason, I continue to get this error
Warning: opendir(C:\xampp\htdocs/objects,C:\xampp\htdocs/objects): The system cannot find the file specified. (code: 2)
here is the code:
public function loadObjects(){
$files = array();
if ($handle = opendir(APP_PATH . 'objects'))
{
while (false !== ($entry = readdir($handle)))
{
if ($entry != "." && $entry != "..")
{
$files[] = $entry;
}
}
}
closedir($handle);
if(is_array($files) && count($files) > 0)
{
foreach($files as $value)
{
require_once(APP_PATH . 'objects/' . $value);
$value = stristr($value, '.', true);
self::$objects[$value] = new $object(self::$instance);
}
}
}
I know this is an old question but for any future viewers I will post an anwser just in case.
This type of error usually comes from a simple oversight. When developing most aplication the developer usualy uses a path like
http://localhost/myAppHome
or
http://96.82.102.233/myAppHome(if on remote server)
In this perticular case the APP_PATH is probably defined somethig like that:
define('APP_PATH',$_SERVER['DOCUMENT_ROOT']);
This will be wrong in every case when the app is being developed outside of a domain name.
$_SERVER['DOCUMENT_ROOT'] will resolve to the root of domain which in this case will be
http://localhost or http://96.82.102.233
The main directory for localhost or the IP address is going to be the diretory root of the server itself => drive:/xampp/htdocs (for example)
Basically to avoid this issue you should always mind not to ask for 'DOCUMENT_ROOT' when developing without a domain pointing to you app.
If you dont require reqular deploys you can just add the missing folder to the definition like so :
define('APP_PATH',$_SERVER['DOCUMENT_ROOT'].'/myAppHome');
In case you deploy on reqular basis and you are afraid you will forget to rever this change before depoying you can always insert an IF when defing APP_PATH like:
if($_SERVER['SERVER_NAME']=='localhost'){
define('APP_PATH', $_SERVER['DOCUMENT_ROOT'].'/myAppHome');
}else{
define('APP_PATH', $_SERVER['DOCUMENT_ROOT']);
}
You are trying to open that directory with a "/".
Try to replace:
C:\xampp\htdocs/objects
to
C:\xampp\htdocs\objects
Please be sure APP_PATH variable is not null and correct values. There is no scandir function usage on your codes.
After that, i suggest you to use DirectoryIterator.
http://www.php.net/manual/en/class.directoryiterator.php
Complete example:
http://fabien.potencier.org/article/43/find-your-files
APP_HOST = DIR folder;
APP_PATH = APP_PATH + DIR folder;
Example = "C:/xampp/htdocs" + "/parent/child/index.php"
if ($_SERVER['SERVER_NAME'] == "localhost") {
define('APP_HOST', pathinfo($_SERVER['PHP_SELF'], PATHINFO_DIRNAME));
define('APP_PATH', $_SERVER['DOCUMENT_ROOT'] . APP_HOST);
} else {
define('APP_PATH', $_SERVER['DOCUMENT_ROOT']);
}
I am looking for a way to list the names of every folder in a directory and their path in PHP
Thank you
What you are referring to is not a page from WAMPP, it is a default setting to show files and folders on any (if not most) web servers... This is usually switched off by the web server config, or .htaccess files
You are looking for some PHP code to do a similar thing, the following PHP functions are what you will need to look into, read the pages and view the examples to understand how to use them... Do not ignore "Warning" or "Important" messages on these pages from php.net:
opendir - Creates a handle to a directory for reading
readdir - Reads files/folders inside a dir
rmdir - Deletes a folder (must be empty)
mkdir - Creates a folder
Here is an example:
<?php
$folder = "myfolder";
if ($dhandle = opendir($folder)) {
while ($file = readdir($dhandle)) {
// Ignore . and ..
if ($file<>'.' && $file<>'..')
// if it's a folder, echo [F]
if (is_dir("$folder/$file")) echo "[F] $file<br>"; else
echo "$file<br>";
}
closedir($dhandle);
}
?>
Important
Remember that on a linux OS, your Apache/PHP must have access to the folder in question before it can write/delete files and folders... Read up on chmod, chown and chgrp
use the following function to get the path of the files/folders
<?php
function getDirectory( $path = '.', $level = 0 ){
$ignore = array( 'cgi-bin', '.', '..' );
// Directories to ignore when listing output. Many hosts
// will deny PHP access to the cgi-bin.
$dh = #opendir( $path );
// Open the directory to the handle $dh
while( false !== ( $file = readdir( $dh ) ) ){
// Loop through the directory
if( !in_array( $file, $ignore ) ){
// Check that this file is not to be ignored
$spaces = str_repeat( ' ', ( $level * 4 ) );
// Just to add spacing to the list, to better
// show the directory tree.
if( is_dir( "$path/$file" ) ){
// Its a directory, so we need to keep reading down...
echo "<strong>$spaces $file</strong><br />";
getDirectory( "$path/$file", ($level+1) );
// Re-call this same function but on a new directory.
// this is what makes function recursive.
} else {
echo "$spaces $file<br />";
// Just print out the filename
}
}
}
closedir( $dh );
// Close the directory handle
}
getDirectory( "." );
?>
There is an simple solution to this problem :(if you are using linux only )
you want list the names of every folder in a directory and their path in PHP .
you can use
find
command in conjuction with PHP's
exec();
function
the following snippet shows this
<?php
$startdir = "Some Directory" ; // the start directory whose sub directories along with path is needed
exec("find " . $startdir . " -type d " , $directories); // executes the command and stores the result in array $directory line by line
while(list($index,$dir) = each($directories) ) {
echo $dir."<br/>"; //lists directories one by one
}
?>
foot notes:
command ,
find dirname -type d
lists all the directories and subdirectories under folder startdir
This is a php code save this as index.php and put it in your web root directory.
<?php
$pngFolder = <<< EOFILE
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAA3NCSVQICAjb4U/gAAABhlBMVEX//v7//v3///7//fr//fj+/v3//fb+/fT+/Pf//PX+/Pb+/PP+/PL+/PH+/PD+++/+++7++u/9+vL9+vH79+r79+n79uj89tj89Nf889D88sj78sz78sr58N3u7u7u7ev777j67bL67Kv46sHt6uP26cns6d356aP56aD56Jv45pT45pP45ZD45I324av344r344T14J734oT34YD13pD24Hv03af13pP233X025303JL23nX23nHz2pX23Gvn2a7122fz2I3122T12mLz14Xv1JPy1YD12Vz02Fvy1H7v04T011Py03j011b01k7v0n/x0nHz1Ejv0Hnuz3Xx0Gvz00buzofz00Pxz2juz3Hy0TrmznzmzoHy0Djqy2vtymnxzS3xzi/kyG3jyG7wyyXkwJjpwHLiw2Liw2HhwmDdvlXevVPduVThsX7btDrbsj/gq3DbsDzbrT7brDvaqzjapjrbpTraojnboTrbmzrbmjrbl0Tbljrakz3ajzzZjTfZijLZiTJdVmhqAAAAgnRSTlP///////////////////////////////////////8A////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////9XzUpQAAAAlwSFlzAAALEgAACxIB0t1+/AAAAB90RVh0U29mdHdhcmUATWFjcm9tZWRpYSBGaXJld29ya3MgOLVo0ngAAACqSURBVBiVY5BDAwxECGRlpgNBtpoKCMjLM8jnsYKASFJycnJ0tD1QRT6HromhHj8YMOcABYqEzc3d4uO9vIKCIkULgQIlYq5haao8YMBUDBQoZWIBAnFtAwsHD4kyoEA5l5SCkqa+qZ27X7hkBVCgUkhRXcvI2sk3MCpRugooUCOooWNs4+wdGpuQIlMDFKiWNbO0dXTx9AwICVGuBQqkFtQ1wEB9LhGeAwDSdzMEmZfC0wAAAABJRU5ErkJggg==
EOFILE;
if (isset($_GET['img']))
{
header("Content-type: image/png");
echo base64_decode($pngFolder);
exit();
}
$projectsListIgnore = array ('.','..');
$handle=opendir(".");
$projectContents = '';
while ($file = readdir($handle))
{
if (is_dir($file) && !in_array($file,$projectsListIgnore))
{
$projectContents .= '<li>'.$file.'</li>';
}
}
closedir($handle);
?>
<ul class="projects">
<?php $projectContents ?>
</ul>
I've been trying to get this done with no luck. I've got a php script that downloads and UNZIPS a file. No problem here.
After that, I need to get the unzipped files and replace all the files of the root directory with the files on this folder. Problem is, the folder is in the root directory.
Eg.: my directory is something like this
/
/folder 1
/folder 2
/folder 3
/file.php
/file2.php
etc...
After I run my download script I unzip the archive to a folder called update in the root of the dir
/update/--UNZIPED STUFF--
I need to delete virtually all files/dirs from the root DIR excluding the update folder I guess and a couple of other files and then move the files/folders inside the update folder to the root of the dir.
Any ideas?
UPDATE
Ok, so I've made a code that seems to be right but I get a lot of file permission to when using unlink or rename. How can I go about that?
Here is the bit of code I've made
echo '<table>';
$updateContents = scandir('./');
foreach($updateContents as $number=>$fileName){
if($fileName != 'update' && $fileName != 'config.ini' && $fileName != 'layout.php' && $fileName != '..' && $fileName != '.' && $fileName != '.git' && $fileName != '.gitignore'){
if(is_dir($fileName)){
moveDownload($fileName, 'old/'.$fileName);
} else {
if(rename($fileName, 'old/'.$fileName)){
echo '<tr><td>'.$fileName.' moved successfully </td><td><font color="green">OK</font></td></tr>';
} else {
echo '<tr><td>Could not move file '.$fileName.'</td><td><font color="red">ERROR</font></td></tr>';
}
}
}
}
echo '</table>';
and the moveDownload function is one I found here somewhere. It moves a non empty folder and it was slightly modified by me.
function moveDownload($src,$dst){
$dir = opendir($src);
while(false !== ($file = readdir($dir))){
if (($file != '.') && ($file != '..') && ($file != 'config.ini') && ($file != 'layout.php') && ($file != 'sbpcache') && ($file !='update')){
if (is_dir($src.'/'.$file)){
if(file_exists($dst.'/'.$file)){
rrmdir($dst.'/'.$file);
}
}
if(#rename($src . '/' . $file, $dst . '/' . $file)){
echo '<tr><td>'.$file.' moved successfully </td><td><font color="green">OK</font></td></tr>';
} else {
if(#chmod($src.'/'.$file, 0777)){
if(#rename($src . '/' . $file, $dst . '/' . $file)){
echo '<tr><td>'.$file.' moved successfully </td><td><font color="green">OK</font></td></tr>';
} else {
echo '<tr><td>Could not move file '.$file.'</td><td><font color="red">ERROR RENAME</font></td></tr>';
}
} else {
echo '<tr><td>Could not move file '.$file.'</td><td><font color="red">ERROR CHMOD</font></td></tr>';
}
}
}
}
closedir($dir);
}
I also do the same in the again but moving from the update folder.
So basically, first instead of deleting things I am just moving them to a folder called old and then I try to move the new things in, but I get permission problems everywhere. Some files move, some don't, even if I have ' sudo chmod 777 -R'. Any ideas?
PHP's opendir will allow you to iterate along all the files and directories inside the root directory. You can use unlink to delete the files or folders and add an if clause to check if the item is to be deleted or not.
Why don't you just get a list of all directories / files under root and then loop through them, delete them (using unlink) while ignoring the "backup" directory.
Next you can either run a php copy OR shell_exec mv * command to move the files from backup to root.
what for to use root folder. use /tmp
what the problem with unlink / rmdir
I'm trying to make a php script to connect to an afp server and get a directory listing (with each file size). The server is local in our office, but I'm unable to just make a script on the afp server side. On my machine, I use something like this:
$filesInDir = array();
$filesInMySQL = array();
if (is_dir($uploadDir)) {
$dh = opendir($uploadDir);
if ($dh) {
$file = readdir($dh);
while ($file != false) {
$path = $uploadDir . "/" . $file;
$type = filetype($path);
if ($type == "file" && $file != ".DS_Store" && $file != "index.php") {
$filesInDir[] = $file;
}
$file = readdir($dh);
}
closedir($dh);
} else {
echo "Can't open dir " . $uploadDir;
}
} else {
echo $uploadDir . " is not a folder";
}
But I can't connect to the afp server. I've looked into fopen it doesn't allow afp, and I don't think it'd allow directory listing:
opendir("afp://ServerName/path/to/dir/");
Warning: opendir() [function.opendir]: Unable to find the wrapper "afp" - did you forget to enable it when you configured PHP? in...
Warning: opendir(afp://ServerName/path/to/dir/) [function.opendir]: failed to open dir: No such file or directory in...`
I'm not looking to see if a file exists, but to get the entire directory listing. Eventually I'll also have to remotely copy files into an output directory.
eg.
mkdir afp://ServerName/output/output001/
cp afp://ServerName/path/to/dir/neededfile.txt afp://ServerName/output/output001/
Maybe use http://sourceforge.net/projects/afpfs-ng/ to mount it...
I'm developing on an Mac Mini, so I realised I could just mount the afp share, and use readdir. I had to mount the drive using the following:
sudo -u _www mkdir /Volumes/idisk
sudo -u _www mount_afp -i afp://<IP>/sharename/ /Volumes/idisk/
Further details here
Does anyone know a solution to this problem? I'm unable to open a subdirectory within a symboliclink'd directory. I've confirmed that the paths are correct (even copy & pasted the path into explorer, which parsed it fine). This is a strange, annoying, bug :|.
Example:
C:\folder\symbolic_link\dir1\dir2 - opening dir2 fails.
C:\folder\symbolic_link\dir1 - works
C:\folder\real_directory\dir1\dir2 - works
C:\folder\real_directory\dir1 - works
Alright, I finally found a hack to solve this bug in php's handling of symlinks on windows. The bug occurs when recursively iterating through files/directories using opendir(). If a symlink to a directory exists in the current directory, opendir() will fail to read the directories in the directory symlink. It is caused by something funky in php's statcache, and can be resolved by calling clearstatcache() before calling opendir() on the directory symlink (also, the parent directory's file-handle must be closed).
Here is an example of the fix:
<?php
class Filesystem
{
public static function files($path, $stats = FALSE)
{
clearstatcache();
$ret = array();
$handle = opendir($path);
$files = array();
// Store files in directory, subdirectories can't be read until current handle is closed & statcache cleared.
while (FALSE !== ($file = readdir($handle)))
{
if ($file != '.' && $file != '..')
{
$files[] = $file;
}
}
// Handle _must_ be closed before statcache is cleared, cache from open handles won't be cleared!
closedir($handle);
foreach ($files as $file)
{
clearstatcache($path);
if (is_dir($path . '/' . $file))
{
$dir_files = self::files($path . '/' . $file);
foreach ($dir_files as $dir_file)
{
$ret[] = $file . '/' . $dir_file;
}
}
else if (is_file($path . '/' . $file))
{
$ret[] = $file;
}
}
return $ret;
}
}
var_dump(filessystem::files('c:\\some_path'));
Edit: It seems that clearstatcache($path) must be called before any file-handling functions on the symlink'd dir. Php isn't caching symlink'd dirs properly.