please help me
May Describe This Code ?
part One :
if(isset($_GET['dir'])){
$currDir = $_GET['dir'];
}else {
$currDir = 'files';
}
if(substr($currDir, strlen($currDir) - 1) != "/") {
$currDir .= '/';
}
please this one too......................
Part Two............................
foreach (glob($currDir . '*') as $filename){
$fileFormat = '';
if (is_dir($filename)) {
$type = 'folder';
} else {
$type = 'file';
$dotPosition = strrpos($filename, ".");
if ($dotPosition !== false) {
$fileFormat = substr($filename, $dotPosition + 1);
}
}
Part 1:
It is checking and setting the variable for directory path. If path is not provided then default is set to "files". Last line makes sure that directory's path ends with "/".
Part 2:
This section is basically checking file extension and storing it in $fileFormat variable. This code could have been better.
Related
Let's say I have a starting point folder called scan_inside. In the folder there are lots of sub-folders and in those sub-folders there might be even more folders with some content.
I would like to scan through all the folders and insert a file uploadme.xml if there is an index.htm file found in the current destination. How can I achieve this?
Illustration:
Scanning...
scan_inside:
subfolder1
style.css
logo.png
folder
homepage.htm
index.htm
uploadme.xml (must be uploaded because an index.htm file was found)
subfolder2
about.htm
logo.png
subfolder3
index.html
uploadme.xml (must be uploaded because an index.htm file was found)
First, you need recursion, then you can go through all of the files and try to capture the extension. After that, you can add a file to the array.
function scanThroughDir($dir) {
$result = [];
foreach(scandir($dir) as $filename) {
if ($filename[0] === '.') continue;
$filePath = $dir . '/' . $filename;
if (is_dir($filePath)) {
foreach (scanThroughDir($filePath) as $childFilename) {
$fileNameParts = explode('.', $childFilename);
if(end($fileNameParts) == "xml"){
echo end($fileNameParts);
$result[] = $childFilename;
}
}
} else {
$fileNameParts = explode('.', $filename);
if(end($fileNameParts) == "xml"){
$result[] = $filename;
}
}
}
return $result;
}
Usage
print_r(scanThroughDir("./"));
I have updated the code a bit. It seeks for .php files and uploads an uploadme.xml to the same path. Seems to work quite alright but there might be some mistakes, though.
function scanThroughDir($dir) {
$result = [];
foreach(scandir($dir) as $filename) {
if ($filename[0] === '.') continue;
$filePath = $dir . '/' . $filename;
if (is_dir($filePath)) {
foreach (scanThroughDir($filePath) as $childFilename) {
$fileNameParts = explode('.', $childFilename);
if(end($fileNameParts) == "php"){
copy('uploadme.xml', pathinfo($filePath, PATHINFO_DIRNAME).'/uploadme.xml');
$result[] = $childFilename;
}
}
} else {
$fileNameParts = explode('.', $filename);
if(end($fileNameParts) == "php"){
copy('uploadme.xml', pathinfo($filePath, PATHINFO_DIRNAME).'/uploadme.xml');
}
}
}
return $result;
}
scanThroughDir("mainfolder");
I know, there are many solutions for this question, but unfortunately I couldn't solve it, Here is my upload code:
public static function upload(&$file, $destinationDir = "", $destinationName = "", $secure = true)
{
$ret = false;
if (isset($file['tmp_name']) && isset($file['name']))
{
if ($destinationName == '')
{
$destinationName = $file['name'];
}
$destinationFile = $destinationDir . '/' . $destinationName;
if (move_uploaded_file($file['tmp_name'], $destinationFile))
{
if ($secure)
{
chmod($destinationFile, 0644); // without execution permissions if it is possible
}
$ret = true;
}
}
return $ret;
}
1: How can I rename file while uploading to server ?
2: If file name is exist then how to rename it automatically?
Thanks in advance
Use file_exists for this case :
public static function upload(&$file, $destinationDir = "", $destinationName = "", $secure = true){
$ret = false;
if(isset($file['tmp_name']) && isset($file['name'])){
if ($destinationName == ''){
$destinationName = md5($file['name']);
}
$destinationFile = $destinationDir.'/'.$destinationName;
if(file_exists($destinationFile)){
// Change the destination file name if it exists
$destinationFile = $destinationDir.'/'.md5($destinationName.rand());
}
if (move_uploaded_file($file['tmp_name'], $destinationFile)){
if($secure){
chmod($destinationFile, 0644); // without execution permissions if it is possible
}
$ret = true;
}
}
Note:
move_uploaded_file — Moves an uploaded file to a new location
structured like this
bool move_uploaded_file ( string $filename , string $destination )
in $destination parameter you give the name of your new uploaded file. Name your file to something that unique. Whatever !, so don't worry about this
Need to remove user requested string from file name. This below is my function.
$directory = $_SERVER['DOCUMENT_ROOT'].'/path/to/files/';
$strString = $objArray['frmName']; // Name to remove which comes from an array.
function doActionOnRemoveStringFromFileName($strString, $directory) {
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(!strstr($file,$strString)) {
continue;
}
$newfilename = str_replace($strString,"",$file);
rename($directory . $file,$directory . $newfilename);
}
}
closedir($handle);
}
}
It works partially good. But the mistake what in this routine is, renaming action also takes on file's extensions. What i need is, Only to rename the file and it should not to be affect its file extensions. Any suggestions please. Thanks in advance :).
I have libraries written by myself that have some of those functions. Look:
//Returns the filename but ignores its extension
function getFileNameWithOutExtension($filename) {
$exploded = explode(".", $filename);
array_pop($exploded);
//Included a DOT as parameter in implode so, in case the
//filename contains DOT
return implode(".", $exploded);
}
//Returns the extension
function getFileExtension($file) {
$exploded = explode(".", $file);
$ext = end($exploded);
return $ext;
}
So you use
$replacedname = str_replace($strString,"", getFileNameWithOutExtension($file));
$newfilename = $replacedname.".".getFileExtension($file);
Check it working here:
http://codepad.org/CAKdCAA0
I'm new to SO and new to PHP. I found a script online to zip a directory and I've edited it so that it sends the zip to the browser for download and then deletes the file from the server.
It works fine, however I would like to zip multiple directories instead of just one.
How would I need to alter my script to accomplish this?
$date = date('Y-m-d');
$dirToBackup = "content";
$dest = "backups/"; // make sure this directory exists!
$filename = "backup-$date.zip";
$archive = $dest.$filename;
function folderToZip($folder, &$zipFile, $subfolder = null) {
if ($zipFile == null) {
// no resource given, exit
return false;
}
// we check if $folder has a slash at its end, if not, we append one
$folder .= end(str_split($folder)) == "/" ? "" : "/";
$subfolder .= end(str_split($subfolder)) == "/" ? "" : "/";
// we start by going through all files in $folder
$handle = opendir($folder);
while ($f = readdir($handle)) {
if ($f != "." && $f != "..") {
if (is_file($folder . $f)) {
// if we find a file, store it
// if we have a subfolder, store it there
if ($subfolder != null)
$zipFile->addFile($folder . $f, $subfolder . $f);
else
$zipFile->addFile($folder . $f);
} elseif (is_dir($folder . $f)) {
// if we find a folder, create a folder in the zip
$zipFile->addEmptyDir($f);
// and call the function again
folderToZip($folder . $f, $zipFile, $f);
}
}
}
}
// create the zip
$z = new ZipArchive();
$z->open($archive, ZIPARCHIVE::CREATE);
folderToZip($dirToBackup, $z);
$z->close();
// download the zip file
$file_name = basename($archive);
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=$file_name");
header("Content-Length: " . filesize($archive));
readfile($archive);
// delete the file from the server
unlink($archive);
exit;
Thanks for any help!
Irma
set $dirToBackup to
$dirToBackup = array("restricted","ci");
and then :
foreach($dirToBackup as $d){
folderToZip($d, $z, $d);
}
Thats all.
Regards,
myFolderi have thousands of image files that have keyword text for the name. i am trying to read from the list of images and upload the text into a dB field. the problem is that some of the text has utf8 characters like l’Été that show up like this ��t�
how can i read foreign characters so that the accents will insert into the dB field?
this is how im handling it now
function ListFiles($dir) {
if($dh = opendir($dir)) {
$files = Array();
$inner_files = Array();
while($file = readdir($dh)) {
if($file != "." && $file != ".." && $file[0] != '.') {
if(is_dir($dir . "/" . $file)) {
$inner_files = ListFiles($dir . "/" . $file);
if(is_array($inner_files)) $files = array_merge($files, $inner_files);
} else {
array_push($files, $dir . "/" . $file);//$dir = directory name
//array_push($files, $dir);
}
}
}
closedir($dh);
return $files;
}
}
foreach (ListFiles('../../myDirectory') as $key=>$file){
//$file = preg_replace( '#[^\0-\x80]#u',"", $file );
echo $file ."<br />";
}
this is producing the same result
$str = "l’Été";
utf8_decode($str);
echo $str;
This solution may work for you, it will loop through all files in a directoy and then recursivly through any directories found until it ends up with a massive array of files.
Ive added some points you may wish to change, eg either mutli or single dimension arrays ( all depend on if you may want to maintain the folder structure.
and also if you want the file extention to be saved when you save the file name to db.
Code
function recursive_search_dir($dir) {
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (in_array($file,array(".","..")))
continue; // We dont want to do anything with parent / current directory.
if (is_dir($file)) {
$result[] = recursive_search_dir($file); // Multi-dimension
# OR
array_merge($result,recursive_search_dir($file));// Single-dimension if you dont care about folder structure.
} else {
$result[] = utf8_decode($file); // full file name ( includes extention )
# OR
$result[] = utf8_decode(filename($file,PATHINFO_FILENAME)); // if you only want to capture the name and not the extention.
}
}
closedir($handle);
}
return $result;
}
$files = recursive_search_dir("."); // recursively searcht the current directory.