How to change name of every file in folder - php

I'm trying to change every file name in a folder, for e.g if file name is style.css than i want to rename it as style_[md5 value of style].css = style_a1b01e734b573fca08eb1a65e6df9a38.css
here is what I've tried
if ($handle = opendir("D:/web/htdocs/extra/css/")) {
while (false !== ($fileName = readdir($handle))) {
$path_parts = pathinfo($fileName);
$newName = md5($path_parts['filename']);
rename($fileName, $newName);
}
closedir($handle);
}
Where am i wrong?
errors are
Access is denied. (code: 5)
The system cannot find the file specified. (code: 2)

not sure the same happens on a windows, but on a GNU here …
if you printed out what you intend to do instead of trying bluntly you'd see some flaws:
rename( ., d41d8cd98f00b204e9800998ecf8427e)
rename( .., 5058f1af8388633f609cadb75a75dc9d)
when e.g. doing:
echo ("rename( ".$fileName.", ".$newName.")\n");
next thing to check maybe is rights to change files …

// DS to print \ the split between folder
define('DS',DIRECTORY_SEPARATOR);
// APP_PATH to get application path on the the server
define('APP_PATH',__DIR__.DS);
$oldname = APP_PATH.'css'.DS.'style.css';
/*
when you echo $oldname ,you will get the complete path of file
*/
// check the file is exists or No
if (file_exists($oldname)) {
$newName = md5($oldname);
/*add the extension of file that you will rename it */
rename($oldname, ($newName.'.css'));
}

Related

ajax php check how many folder i had in path src

<?php
header("content-type: application/json");
$files = array();
$dir = "Img/House"; //folder src path
$dirHandle = opendir($dir);
while(($file = readdir($dirHandle) !== false)){
if ($file !== "." && $file !== "..")
{
$files[] = $file;
}
}
echo($files);
//echo json_encode($directoryfiles);
?>
I am using ajax to php to return how many folder I had inside that src path , I can count the folder number on ajax , but something wrong with my php file , it seem wont check how many folder I have.
My intention is to use ajax and php check how many folder i have and push those name into the array $files. Can anyone help me take a look. I have no experience one this.
If you only want to return the number of directories in the given path, you can easily use count and glob, see below
// this is not needed unless you output json
// header("content-type: application/json");
$dir = "Img/House"; //folder src path
$dirs = glob($dir . "/*",GLOB_ONLYDIR);
print count($dirs);
// or directly
// print count(glob($dir . "/*",GLOB_ONLYDIR));
// if glob returns the current and parent dirs, "." and ".."
// just remove 2 from the count
// test by doing
print_r($dirs);
// then
print $count($dirs)-2;

Access files from path above root in PHP

I'm writing a simple upload/download page in PHP. With the following code I can see files being the content of folder above the root but it's impossible to access those files. What could be the reason?
$targetdir="/../cat/";
if ($dir = #opendir($targetdir))
{
while ($file = readdir($dir))
{
if ($file != "." && $file != "..")
echo "<td>".$file."</td>";
}
closedir($dir);
}
You cannot access files above the web root directory, instead you will need to write a script to do this for you.
downloadfile.php?file=somefile.txt
<?php
$file = $_GET['file'];
if (strpos($file, '..') !== false) {
throw new \Exception('Illegal path requested');
}
/**
* this will restrict files to this directory or above as
* to not allow reading of files which you do not want a user to access
*/
$basePath = __DIR __ . '/../cat';
$fullPath = sprintf('%s/%s', $basePath, $file);
/** check to see if the file exists and is readable **/
if (false === is_readable($fullPath)) {
throw \Exception('file does not exist or is not accessible');
}
echo file_get_contents($file);
exit;
You must be very cautious when doing this, as you could allow someone to access files you don't want them to, including your source code, so make sure you're sanitizing the input.
As well you should change $target dir to the following, as it stands you're trying to go to the absolute root of the file system instead relative to the file which started the execution.
/** relative to the file that started the execution **/
$targetdir = "../cat/"
/** relative to the file that contains this variable declaration**/
$target = __DIR__ . "/../cat/"

Retrieving contents of several files in directory PHP

I need to get the contents of several files within a directory but which is the best way of doing this?
I am using
$data = file_get_contents('./files/myfile.txt');
but I want every file without having to specify the file individually as above.
You can use glob to get particular file extention and file_get_contents to get the content
$content = implode(array_map(function ($v) {
return file_get_contents($v);
}, glob(__DIR__ . "/files/*.txt")));
/**
* Change the path to your folder.
* This must be the full path from the root of your
* web space. If you're not sure what it is, ask your host.
*
* Name this file index.php and place in the directory.
*/
// Define the full path to your folder from root
$path = "/home/content/s/h/a/shaileshr21/html/download";
// Open the folder
$dir_handle = #opendir($path) or die("Unable to open $path");
// Loop through the files
while ($file = readdir($dir_handle)) {
$data = file_get_contents('$filet');
}
// Close
closedir($dir_handle);
You can dir the directory and loop through it to get the contents of all files.
<?php
$path = './files';
$d = dir($path);
$contents = '';
while (false !== ($entry = $d->read())) {
if (!($entry == '..' || $entry == '.')) {
$contents .= file_get_contents($path.'/'.$entry);
}
}
$d->close();
?>
If you only want .txt files you can change the if statement of the code above from:
if (!($entry == '..' || $entry == '.')) {
to:
if (substr($entry, -4) == '.txt') {
This will result to a variable $contents that is type string and has all the contents of all the files (or only txt files if you select the 2nd solution) that are in the ./files dir.

Read only pdf files and get the filename of that pdf files in a directory

I need to read only pdf files in a directory and then read the filename of every files then I will use the filename to rename some txt files. I have tried using only eregi function. but it seems cannot read all I need. how to read them well?
here's my code :
$savePath ='D:/dir/';
$dir = opendir($savePath);
$filename = array();
while ($filename = readdir($dir)) {
if (eregi("\.pdf",$filename)){
$read = strtok ($filename,"."); //get the filenames
//to rename some txt files using the filenames that I get before
//$testfile is text files that I've read before
$testfile = "$read.txt";
$file = fopen($testfile,"r") or die ('cannot open file');
if (filesize($testfile)==0){}
else{
$text = fread($file,55024);
fclose($file);
echo "</br>"; echo "</br>";
}
}
More elegant:
foreach (glob("D:/dir/*.pdf") as $filename) {
// do something with $filename
}
To get the filename only:
foreach (glob("D:/dir/*.pdf") as $filename) {
$filename = basename($filename);
// do something with $filename
}
You can do this by filter file type.. following is sample code.
<?php
// directory path can be either absolute or relative
$dirPath = '.';
// open the specified directory and check if it's opened successfully
if ($handle = opendir($dirPath)) {
// keep reading the directory entries 'til the end
$i=0;
while (false !== ($file = readdir($handle))) {
$i++;
// just skip the reference to current and parent directory
if (eregi("\.jpg",$file) || eregi("\.gif",$file) || eregi("\.png",$file)){
if (is_dir("$dirPath/$file")) {
// found a directory, do something with it?
echo " [$file]<br>";
} else {
// found an ordinary file
echo $i."- $file<br>";
}
}
}
// ALWAYS remember to close what you opened
closedir($handle);
}
?>
Above is demonstrating for file type related to images you can do the same for .PDF files.
Better explained here

File renaming using php

Have the following script.
<?php
if ($handle = opendir('files/')) {
while (false !== ($fileName = readdir($handle))) {
$newName = str_replace("SKU#","",$fileName);
rename(fileName, $newName);
}
closedir($handle); } ?>
my script is in the root directory of iss.
inetpub/wwwroot
And I am trying to as a result access the folder files/, which is one level up to wwwroot. Where contains one image called:
"WV1716BNSKU#.zoom.1"
I am using a windows OS, any idea why this is not working, code looks file.
What error do you get? Make sure PHP is setup to display all errors.
Your script will also have to be in the same folder as your files you want to rename as all your paths are relative.
Try this:
if ($handle = opendir('./')){
while (false !== ($fileName = readdir($handle))){
$newName = str_replace("SKU#", "", $fileName);
rename($fileName, $newName);
}
closedir($handle);
}

Categories