[function.rename]: No error in - php

I do want to decrease the first part of the folders which are contained on the server when I delete a field in a database.
my folders are like : 1-Guerlain, 2-Chanel, 3-Diesel. So when the first folder is deleted I want for the other folders to be like 1-Chanel, 2-Diesel.
This is my code :
foreach (new DirectoryIterator($path) as $file)
{
if($file->isDot()) continue;
if($file->isDir())
{
$parts = explode('-', $file->getFilename());
if ($parts[0] > $_GET['id_folder']) {
$old = "./" . $parts[0] . "-" . $parts[1] . "";
$new = "./" . ($parts[0] - 1) . "-" . $parts[1] . "";
rename($old, $new);
}
}
}
But this gives me the following error : Warning: rename(./2-Chanel,./1-Chanel) [function.rename]: No error in C:\wamp\www\pcqsp-scratch\admin.php on line 196 and the folder doesn't be renamed.
How can I achieve this ? Thank you.

You need the full path for rename()
$parts = explode('-', $file->getFilename());
$path = $file->getPath();
$old = $path . DIRECTORY_SEPARATOR . $parts[0] . "-" . $parts[1] . "";
$new = $path . DIRECTORY_SEPARATOR . ($parts[0] - 1) . "-" . $parts[1] . "";
rename($old, $new);

Related

Copy folder tree-recursively with depth control

I want to copy a whole folders/files tree from one location to another, but for a particular depth I want to perform a transliteration of the destination folder from one language to another.
So for /src/depth1/depth2/depth3/depth4/file I want to transliterate all depth3 folders to another language before copying them over to the destination path.
So I found this little, robust recursive function, which should help me in my task, and then I tried to add a depth control feature so that the transliteration replacement takes place only on depth3 folders. But at first, what I did only added to the depth. Then I thought I found the correct place to add the $depth--;, but unfortunately I can't figure out where to subtract from it in order to start over a new branch...
Could someone help figure this out please?
recurse_copy('TOCOPY/', 'TEST/');
function recurse_copy($src,$dst,$depth = 0) {
echo $src . ' ' . $depth.'<br>';
$dir = opendir($src);
#mkdir($dst);
while(false !== ( $file = readdir($dir)) ) {
$depth++;
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
recurse_copy($src . '/' . $file,$dst . '/' . $file, $depth);
} else {
$depth--;
// copy($src . '/' . $file,$dst . '/' . $file); //I commented this line to save time from copying files again and again while I'm experimenting with the depth control...
}
}
}
closedir($dir);
}
Not tested, but if my understanding is right this should work, plus minus 1 depth.
recurse_copy('TOCOPY/', 'TEST/', 3);
function recurse_copy($src, $dst, $depth = 0) {
echo $src . ' ' . $depth . '<br>';
if ($depth <= 0) {
return;
}
$dir = opendir($src);
#mkdir($dst);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
recurse_copy($src . '/' . $file,$dst . '/' . $file, $depth - 1);
} else {
// copy($src . '/' . $file,$dst . '/' . $file); //I commented this line to save time from copying files again and again while I'm experimenting with the depth control...
}
}
}
closedir($dir);
}
Addition:
This version will rename some directories according to their depth.
recurse_copy_special('TOCOPY/', 'TEST/');
function recurse_copy_special($src, $dst, $depth = 0)
{
echo $src . ' ' . $depth . '<br>';
$base = basename($dst);
$dir = dirname($dst);
if ($depth == 1) {
$dst = $dir . '/' . 'changed1-' . $base;
}
if ($depth == 2) {
$dst = $dir . '/' . 'changed2-' . $base;
}
if ($depth == 3) {
$dst = $dir . '/' . 'changed3-' . $base;
}
$dir = opendir($src);
if (!file_exists($dst)) {
mkdir($dst);
}
while (false !== ($file = readdir($dir))) {
if (($file != '.') && ($file != '..')) {
if (is_dir($src . '/' . $file)) {
recurse_copy_special($src . '/' . $file, $dst . '/' . $file, $depth + 1);
} else {
copy($src . '/' . $file, $dst . '/' . $file);
}
}
}
closedir($dir);
}
recurse_copy('TOCOPY/', 'TEST/', 3);
function recurse_copy($source, $destination, $depth = 0) {
echo "copy $depth from $source to $destination" . PHP_EOL;
if ($depth < 0) {
return;
}
$directory = opendir($source);
if (!$directory) {
return;
}
#mkdir($destination);
while(false !== ($file = readdir($directory))) {
if (in_array($file, ['.', '..'])) {
continue;
}
$currentSourcePath = $source . '/' . $file;
$currentDestinationPath = $destination . '/' . $file;
if (is_dir($currentSourcePath)) {
recurse_copy($currentSourcePath, $currentDestinationPath, $depth - 1);
continue;
}
copy($currentSourcePath, $currentDestinationPath);
}
closedir($directory);
}

Wrap Output in Properly Nested Lists - PHP Directory Listing

Okay, I've been searching for a way to list directories and files, which I've figured out and am utilizing code I found here on StackOverflow (Listing all the folders subfolders and files in a directory using php).
So far I've altered code found in one of the answers. I've been able to remove file extensions from both the path and the file name using preg_replace, capitalize the file names using ucwords, and switch out dashes for spaces using str_replace.
What I'm having trouble with now is wrapping the whole thing in a properly nested HTML list. I've managed to set it up so it's wrapped in a list, but it doesn't use nested lists where needed and I can't, for the life of me, figure out how to capitalize the directory names or replace any dashes within the directory name.
So, the questions are, if anyone would be so kind:
How do I wrap the output in properly nested lists?
How do I capitalize directory names while removing the preceding slash and replace dashes or underscores with spaces?
I've left the | within the $ss variable intentionally. I use it as a marker of sorts when I want to throw in characters that will identify where it shows up during trial and error (example $ss = $ss . "<li>workingOrNot").
I'm using:
<?php
$pathLen = 0;
function prePad($level) {
$ss = "";
for ($ii = 0; $ii < $level; $ii++) {
$ss = $ss . "| ";
}
return $ss;
}
function dirScanner($dir, $level, $rootLen) {
global $pathLen;
$filesHidden = array(".", "..", '.htaccess', 'resources', 'browserconfig.xml', 'scripts', 'articles');
if ($handle = opendir($dir)) {
$fileList = array();
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." && !in_array($entry, $filesHidden)) {
if (is_dir($dir . "/" . $entry)) {
$fileList[] = "F: " . $dir . "/" . $entry;
}
else {
$fileList[] = "D: " . $dir . "/" . $entry;
}
}
}
closedir($handle);
natsort($fileList);
foreach($fileList as $value) {
$displayName = ucwords ( str_replace("-", " ", substr(preg_replace('/\\.[^.\\s]{3,5}$/', '', $value), $rootLen + 4)));
$filePath = substr($value, 3);
$linkPath = str_replace(" ", "%20", substr(preg_replace('/\\.[^.\\s]{3,5}$/', '', $value), $pathLen + 3));
if (is_dir($filePath)) {
echo prePad($level) . "<li>" . $linkPath . "</li>\n";
dirScanner($filePath, $level + 1, strlen($filePath));
} else {
echo "<li>" . prePad($level) . "" . $displayName . "</li>\n";
}
}
}
}
I feel like these answers should be simple, so maybe I've been staring at it too much the last two days or maybe it has become Frankenstein code.
I'm about out of trial and error and I need help.
foreach($fileList as $value) {
$displayName = ucwords ( str_replace("-", " ", substr(preg_replace('/\\.[^.\\s]{3,5}$/', '', $value), $rootLen + 4)));
$filePath = substr($value, 3);
$linkPath = str_replace(" ", "%20", substr(preg_replace('/\\.[^.\\s]{3,5}$/', '', $value), $pathLen + 3));
if (is_dir($filePath)) {
// Do not close <li> yet, instead, open an <ul>
echo prePad($level) . "<li>" . $linkPath; . "<ul>\n";
dirScanner($filePath, $level + 1, strlen($filePath));
// Close <li> and <ul>
echo "</li></ul>\n";
} else {
echo "<li>" . prePad($level) . "" . $displayName . "</li>\n";
}
}
I guess you're opening the main before call the function and closing it at the end.

No error when creating zip, but it doesn't get created inside directory

I wrote this code to create a ZIP file of my uploaded attachment, wp application has an option to uploads pdf , those upload pdf will stored under upload directory , i got the result success with no error's but still zip is not get created inside the directory server . Here's the code:
// Code for Getting links (Path)of Attachements
$list = array();
// $count = 1;
foreach($applicants as $key=>$val) {
$cat_id =explode("-", $key);
foreach($val as $appkey=>$appval) {
// if(($appval['name'])=='Navn') {
// $names = $count . '_' . $cat_id[1] . '_' . stripslashes($appval['value']) ;
// }
if(($appval['name']) == ' (PDF)') {
$attach = stripslashes($appval['value']) ;
$list[] = $cat_id[0].'-'. $cat_id[1].'/' . $attach; // Attaching ID and Category to attachement file name
}
}
// $count++;
}
$paths = array();
foreach ($list as $list) {
$data = explode('/',$list);
$pdfpath='../../' . $data[7] . '/' . $data[8] . '/' . $data[9] . '/' . $data[10];
$name=(string)$data[0] . '_' . $data[10];
$paths[] = $pdfpath."*".$name;
}
$zip = new ZipArchive;
$rand = rand(0,5000);
// Generating random file name for zipcode
if ($zip->open($rand . 'appl_attachments.zip', ZipArchive::CREATE)) {
// add files to zip from the path i.e uplaods(Folder) if file exists
foreach ($paths as $value ) {
$path=explode("*", $value);
if(file_exists($path[0])) {
$zip->addFile($path[0],$path[1]);
}
}
$zip->close();
Finally got a fix on the issue , update the changes on the pdf path .
Here is the changes on the code :
$paths = array();
foreach ($list as $list) {
$data = explode('/',$list);
$pdfpath='../../' . $data[6] . '/'. $data[7] . '/' . $data[8] . '/' . $data[9] ;
$name=$data[9];

PHP: How to create foreach loop (simple code)

I am new to PHP and have created a little code for a file upload on a form.
The code works fine but I was wondering if I could achieve the same using a foreach loop so that it could also handle more files and I dont have to write a separate line for each of them.
Can someone here help me with this and tell me how to write it properly.
My Code (working):
session_start();
$varUID = $_POST['UID'];
$varSender = $_SESSION['email'];
$varFile1 = $_FILES["file1"]["name"];
$varExt1 = pathinfo($varFile1, PATHINFO_EXTENSION);
$varFile2 = $_FILES["file2"]["name"];
$varExt2 = pathinfo($varFile2, PATHINFO_EXTENSION);
$varFile3 = $_FILES["file3"]["name"];
$varExt3 = pathinfo($varFile3, PATHINFO_EXTENSION);
move_uploaded_file($_FILES["file1"]["tmp_name"], "uploads/" . $varUID . "_1" . "." . $varExt1);
move_uploaded_file($_FILES["file2"]["tmp_name"], "uploads/" . $varUID . "_2" . "." . $varExt2);
move_uploaded_file($_FILES["file3"]["tmp_name"], "uploads/" . $varUID . "_3" . "." . $varExt3);
echo $varUID;
Thanks for any help with this,
Tim
foreach ($_FILES as $key => $file) {
$name = $file["name"];
$ext = pathinfo($name, PATHINFO_EXTENSION);
preg_match('/(\d+)$/', $key, $match); // get 2 out of "file2"
$nr = $match[1];
move_uploaded_file($file["tmp_name"], "uploads/" . $varUID . "_" . $nr . "." . $ext);
}
$varUID = $_POST['UID'];
$varSender = $_SESSION['email'];
$i = 1;
foreach ($_FILES as $key => $file) {
$varFile = $file[$key]["name"];
$varExt = pathinfo($varFile, PATHINFO_EXTENSION);
move_uploaded_file($file[$key]["tmp_name"], "uploads/" . $varUID . "_" . $i . "." . $varExt);
$i++;
}
echo $varUID;

Strange PHP issue

My function looks like that
protected function make_js_link($list, $folder, $parentdir = "js") {
$links = array();
$list = explode(',', $list);
foreach ($list as $name) {
$dir = $parentdir . "/";
if (is_string($folder))
echo $folder . "/";
$links[] = '<script src="' . $dir . trim($name) . '.js"></script>' . "\n";
}
echo implode(" ", $links);
}
So when js file located in $parentdir I'm calling like that
$this->make_js_link('ckeditor', 0, 'incl/editor');
If file located in parentdir/another_dir, then calling like that
$this->make_js_link('jquery', 'adapters', 'incl/editor');
The problem is, PHP escapes this part in both cases: even if I have folder variable with exact string value:
if (is_string($folder))
echo $folder . "/";
Where I did wrong?
You did echo instead of
$dir = $parentdir . "/";
if (is_string($folder))
$dir.= $folder . "/";

Categories