I've been trying to change the file extension of all the picture files in a folder using the following snippet:
$dh = opendir('JS2C');
$files = array();
while (($file = readdir($dh)) !== false) {
if($file !== '.' && $file !== '..') {
$file = pathinfo($file);
rename($file, $new . '.jpg');
}
}
I get the following warning messages:
SCREAM: Error suppression ignored for
Warning: rename(ANAZODO.gif,ANAZODO.jpg):
The system cannot find the file specified. (code: 2) in C:\wamp2\www\ckcportal\batch2.php on ...
The folder that contains the files is in the same folder with the PHP script.
you are missing directory for rename
$d = 'JS2C/'
$dh = opendir($d);
while (($file = readdir($dh)) !== false) {
if($file !== '.' && $file !== '..') {
//$file_no_ext = substr($file, 0,strrpos($file,'.'));// before php 5.2
$path_parts = pathinfo($file); // php 5.2
$file_no_ext = $path_parts['filename']; // php 5.2
rename($d.$file, $d.$file_no_ext . '.jpg');
}
}
You have to supply the full path, from the error you are receiving, it looks like you are just giving the file name.
rename('/path/to/old/file', '/path/to/new/file');
And why are you using $file = pathinfo($file);? pathinfo creates an assoc. array from information of $file which should be giving you the full path. If you take this out, it should work.
Unless you need to following:
$info = pathinfo($file);
$path = $info['dirname']
$new_file = $path . '/' . 'newfile.ext';
rename($file, $new_file);
Related
I'm having a problem with a function I've gotten for displaying all of the Files and sub-directory files of a given directory. It works locally, but when I upload it, the page just gives a 500 Error.
I have tried chmod'ing to 777, even the entire directory that it searches, but nothing seems to work. Any help is appreciated!
<?php
$directory = '../..';
$files = listFiles($directory, 'start.js');
echo json_encode($files);
function listFiles($dir, $origin) {
$directory = scandir($dir);
$files = [];
foreach($directory as $file){
if($file != '.' && $file != '..') {
$thisFile = $dir . '/' . $file;
if(is_dir($thisFile)) {
$files = array_merge($files, listFiles($thisFile, $origin));
}else{
$tempDir = str_replace('../..', '/game', $thisFile);
$extension = substr(strrchr($thisFile, '.'), 1);
if($extension == 'js' && strpos($thisFile, $origin) === false) $files[] = $tempDir;
}
}
}
return $files;
}
The syntax:
$files = [];
Is only available from a certain PHP version (5.4 I think). Check that the server has the same version as your development environment.
First enable error reporting using the following PHP code:
ini_set('display_errors','On');
error_reporting(E_ALL);
Second, check for syntax errors or something else.
Like previous commenters said the syntax..
$files = [];
..is only available from a certain PHP version (5.4 I think). Check that the server has the same version as your development environment.
Tested on my localhost:
<?php
$directory = '../..';
$files = listFiles($directory, 'start.js');
echo json_encode($files);
function listFiles($dir, $origin) {
$directory = scandir($dir);
$files = array();
foreach($directory as $file){
if($file != '.' && $file != '..') {
$thisFile = $dir . '/' . $file;
if(is_dir($thisFile)) {
$files = array_merge($files, listFiles($thisFile, $origin));
}else{
$tempDir = str_replace('../..', '/game', $thisFile);
$extension = substr(strrchr($thisFile, '.'), 1);
if($extension == 'js' && strpos($thisFile, $origin) === false) $files[] = $tempDir;
}
}
}
return $files;
}
PS: First the code fives me an error on $files var...i change that and it works.
$path = '/home/username/www/;
if($zip = new ZipArchive){
if($zip->open('backup_'. time() .'.zip', ZipArchive::CREATE)){
if(false !== ($dir = opendir($path))){
while (false !== ($file = readdir($dir))){
if ($file != '.' && $file != '..' && $file != 'aaa'){
$zip->addFile($path . $file);
echo 'Adding '. $file .' to path '. $path . $file .' <br>';
}
}
}
else
{
echo 'Can not read dir';
}
$zip->close();
}
else
{
echo 'Could not create backup file';
}
}
else
{
echo 'Could not launch the ZIP libary. Did you install it?';
}
Hello again Stackoverflow! I want to backup a folder with all its content including (empty) subfolders and every file in them, whilst excluding a single folder (and ofcourse . and ..). The folder that needs to be excluded is aaa.
So when I run this script (every folder does have chmod 0777) it runs without errors, but the ZIP file doesn't show up. Why? And how can I solve this?
Thanks in advance!
have you tried to access the zip folder via PHP rather than looking in FTP as to whether it exists or not - as it might not appear immediately to view in FTP
function addFolderToZip($dir, $zipArchive, $zipdir = ''){
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
//Add the directory
if(!empty($zipdir)) $zipArchive->addEmptyDir($zipdir);
// Loop through all the files
while (($file = readdir($dh)) !== false) {
//If it's a folder, run the function again!
if(!is_file($dir . $file)){
// Skip parent and root directories, and any other directories you want
if( ($file !== ".") && ($file !== "..") && ($file !== "aa")){
addFolderToZip($dir . $file . "/", $zipArchive, $zipdir . $file . "/");
}
}else{
// Add the files
$zipArchive->addFile($dir . $file, $zipdir . $file);
}
}
}
}
}
After a while of fooling around this is what I found working. Use it as seen below.
$zipArchive = new ZipArchive;
$name = 'backups\backup_'. time() .'.zip';
$zipArchive->open($name, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE);
addFolderToZip($path, $zipArchive);
Here's my answer, checks if the modification time is greater then something as well.
<?php
$zip = new ZipArchive;
$zip_name = md5("backup".time()).".zip";
$res = $zip->open($zip_name, ZipArchive::CREATE);
$realpath = str_replace('filelist.php','',__FILE__);
$path = realpath('.');
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
foreach($objects as $name => $object){
if (is_file($object)) {
$file_count ++;
$epoch = $object->getMTime();
if($epoch>='1374809360'){ // Whatever date you want to start at
$array[] = str_replace($realpath,'',$object->getPathname());
}
}
}
foreach($array as $files) {
$zip->addFile($files);
}
$zip->close();
echo $zip_name.'-'.$file_count.'-'.$count_files;
?>
I'm trying to write a bulk rename in this way:
if ($handle = opendir('../../upload_files')) {
while (false !== ($fileName = readdir($handle))) {
$newName = str_replace(", ","_",$fileName);
rename($fileName, $newName);
$count++;
}
closedir($handle);
echo $count." files renamed";
}
But when I run the script, I get a warning:
Warning: rename(..,..) [function.rename]: No error in E:\WEBS\rename.php on line 6
What is causing the error?
If the target file already exists, PHP is known for such error under Windows environment.
There's a known bug for PHP 5.3 https://bugs.php.net/bug.php?id=48771 with similar error message.
I recommend trying out following modification of your code (it's based on your code, just with some corrections)
$dir = "../../upload_files";
if ($handle = opendir($dir))
{
while (false !== ($fileName = readdir($handle)))
{
if (!isset($count)) $count = 0;
if ($fileName == ".." || $fileName == ".") continue;
$newName = str_replace(", ","_",$fileName);
copy($dir.$fileName, $dir.$newName);
$count++;
}
closedir($handle);
echo $count." files renamed";
}
So I am trying to build a script that scans a directory and returns random images to be used as backgrounds.
The php looks like this:
$dir = "views/img/bg/";
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
$files[] = $filename;
}
$random_key = array_rand($files, 1);
$random = $files[$random_key];
Then I am just using some simple jquery to attach the images as backgrounds:
<script>
$(document).ready(function(){
$("body").css( "background" , "url(http://'.$url_root.'/views/img/bg/'.$random.'), center center" );
});
</script>
Everything works fine but the array of all the images in the background folder seems to be returning stuff like '.' or '..' instead of image names every once in a while. Im not sure what is going on - any ideas?
Use glob() so you can filter the files.
$files = glob('views/img/bg/*.jpg');
$random = $files[array_rand($files)];
Since you're specifying *.jpg, $files contains only JPG files and you don't need to remove the . and .. items.
'.' and '..' are returned for current and parent directory. You can filter them:
while (false !== ($filename = readdir($dh))) {
if ($filename != '.' && $filename != '..')
$files[] = $filename;
}
Why not use regex? That way it captures any amount of periods. (i.e. ".", "..", "..." etc..)
while (false !== ($filename = readdir($dh))) {
if(!preg_match('/^\.*$/',$filename)){
$files[] = $filename;
}
$dh = opendir("c:\");
while (false !== ($filename = readdir($dh))) {
if ($filename != '.' && $filename != '..')
$files[] = $filename;
}
This is the starting portion of my code to list files in a directory:
$files = scandir($dir);
$array = array();
foreach($files as $file)
{
if($file != '.' && $file != '..' && !is_dir($file)){
....
I'm trying to list all files in a directory without listing subfolders. The code is working, but showing both files and folders. I added !is_dir($file) as you see in my code above, but the results are still the same.
It should be like this, I think:
$files = scandir($dir);
foreach($files as $file)
{
if(is_file($dir.$file)){
....
Just use is_file.
Example:
foreach($files as $file)
{
if( is_file($file) )
{
// Something
}
}
This will scan the files then check if . or .. is in an array. Then push the files excluding . and .. in the new files[] array.
Try this:
$scannedFiles = scandir($fullPath);
$files = [];
foreach ($scannedFiles as $file) {
if (!in_array(trim($file), ['.', '..'])) {
$files[] = $file;
}
}
What a pain for something so seemingly simple! Nothing worked for me...
To get a result I assumed the file name had an extension which it must in my case.
if ($handle = opendir($opendir)) {
while (false !== ($entry = readdir($handle))) {
$pos = strpos( $entry, '.' );
if ($entry != "." && $entry != ".." && is_numeric($pos) ) {
............ good entry
Use the DIRECTORY_SEPARATOR constant to append the file to its directory path too.
function getFileNames($directoryPath) {
$fileNames = [];
$contents = scandir($directoryPath);
foreach($contents as $content) {
if(is_file($directoryPath . DIRECTORY_SEPARATOR . $content)) {
array_push($fileNames, $content);
}
}
return $fileNames;
}
This is a quick and simple one liner to list ONLY files. Since the user wants to list only files, there is no need to scan the directory and return all the contents and exclude the directories. Just get the files of any type or specific type. Use * to return all files regardless of extension or get files with a specific extension by replacing the * with the extension.
Get all files regardless of extension:
$files = glob($dir . DIRECTORY_SEPARATOR . "*");
Get all files with the php extension:
$files = glob($dir . DIRECTORY_SEPARATOR . "*.php");
Get all files with the js extension:
$files = glob($dir . DIRECTORY_SEPARATOR . "*.js");
I use the following for my sites:
function fileList(string $directory, string $extension="") :array
{
$filetype = '*';
if(!empty($extension) && mb_substr($extension, 0, 1, "UTF-8") != '.'):
$filetype .= '.' . $extension;
else:
$filetype .= $extension;
endif;
return glob($directory . DIRECTORY_SEPARATOR . $filetype);
}
Usage :
$files = fileList($configData->includesDirectory, '');
With my custom function, I can include an extension or leave it empty. Additionally, I can forget to place the . before the extension and it will succeed.