I would like to move a file from one directory to another. However, the trick is, I want to move file with entire path to it.
Say I have file at
/my/current/directory/file.jpg
and I would like to move it to
/newfolder/my/current/directory/file.jpg
So as you can see I want to retain the relative path so in the future I can move it back to /my/current/directory/ if I so require. One more thing is that /newfolder is empty - I can copy anything in there so there is no pre-made structure (another file may be copied to /newfolder/my/another/folder/anotherfile.gif. Ideally I would like to be able to create a method that will do the magic when I pass original path to file to it. Destination is always the same - /newfolder/...
You may try something like this if you're in an unix/linux environment :
$original_file = '/my/current/directory/file.jpg';
$new_file = "/newfolder{$original_file}";
// create new diretory stricture (note the "-p" option of mkdir)
$new_dir = dirname($new_file);
if (!is_dir($new_dir)) {
$command = 'mkdir -p ' . escapeshellarg($new_dir);
exec($command);
}
echo rename($original_file, $new_file) ? 'success' : 'failed';
you can simply use the following
<?php
$output = `mv "/my/current/directory/file.jpg" "/newfolder/my/current/directory/file.jpg"`;
if ($output == 0) {
echo "success";
} else {
echo "fail";
}
?>
please note I'm using backtick ` to execute instead of using function like exec
Related
I searched everywhere for this problem and can't find the solution. I have this:
<?php
$file_name = $_GET['name'];
$file_delete = '../u/' . $file_name;
unlink($file_delete);
//header("location: $file_delete");
?>
unlink returns the error: No such file or directory, but if I try header("location: $file_delete"); it opens the file (picture in this case).
Where may I be wrong?
Get Absolute path first for the file to be deleted and check file exist before delete:
$file_name = $_GET['name'];
$base_dir = realpath($_SERVER["DOCUMENT_ROOT"]);
$file_delete = "$base_dir/your_inner_directories_path/$file_name";
if (file_exists($file_delete)) {unlink($file_delete);}
After some research, unlink() doesn't seem to allow you to use relative paths (with "../").
Here's an alternative:
<?php
$file_name = $_GET['name'];
$file_delete = dirname(__FILE__, 2) . '\\u\\' . $file_name;
unlink($file_delete);
?>
$file_delete here is the absolute path to the file you want to delete.
Reminder: / is used for Unix systems, \ for Windows.
PHP doc:
- http://php.net/manual/en/function.unlink.php
- http://php.net/manual/en/function.dirname.php
I also had same issue with my code. What I did to solve the issue is:
First execute:
var_dump($image_variable) // var_dump($file_delete) in your case.
It outputs: string(23)(my-image-path )
When I started counting string I just found 22 characters. I wondered where is the 23rd?
I checked and count carefully, at the end I found that there is space at the end of my image path. So I used php trim() function to remove white spaces. Like,
$trimed_path = trim($image_variable) // trim($file_delete) in your case.
Second: Now execute,
unlink($trimed_path).
OR CHECK LIKE
if(unlink($trimed_path))
{
echo "File Deleted";
}
else
{
echo "Error Deleting File";
}
Took me a couple of hours to figure out. As mentioned above unlink() is picky when it comes to paths.
Solution is:
1st) Define the path (this is how Wordpress does it btw):
define( 'ROOTPATH', dirname(dirname(__FILE__)) . '/' );
2) Do:
unlink(ROOTPATH.'public_html/file.jpg');
so the title is not full clear, my question , I'm using the code to rename the file from directory present in the server the problem is i have to use the HTML form and php to update the file name, i want to do this : there will be an option on every file for renaming it when i click on the option the box pops up and i have to type the new name for file and save it , any help will be appreciated. (before down voting think about the question.)
The code that I'm using to update the file name
<?php
include("configuration.php");
$target = $_POST['filename'];
$newName = $_POST['newfilename'];
$actfoler = $_REQUEST['folder'];
$file = "files/users/";
$new ="files/users/";
$renameResult = rename($file, $new);
// Evaluate the value returned from the function if needed
if ($renameResult == true) {
echo $file . " is now named " . $new;
} else {
echo "Could not rename that file";
}
header("Location:".$_SERVER["HTTP_REFERER"]);
?>
Try changing these lines:
$file = "uploads/$loggedInUser->username$actfolder/$target";
$new ="uploads/$loggedInUser->username$actfolder/$newName";
To:
$file = "uploads/{$loggedInUser->username}{$actfolder}/{$target}";
$new ="uploads/{$loggedInUser->username}{$actfolder}/{$newName}";
To explain why:
You are using variables inside a string, which means you will want to tell PHP where the variable ends. Especially when referencing objects or arrays, but also when you are placing variables right next to each other. I'm guessing PHP evaluated your original line to uploads/[Object]->usernamePizza/newname
I don't think you can call object properties in a string as you do.
try replace these lines :
$file = "uploads/".$loggedInUser->username."$actfolder/$target";
$new ="uploads/".$loggedInUser->username."$actfolder/$newName";
You may think about echoing $file and $new to confirm the path is nicely built.
On a side note, I'd recommend to really check the entries because this code can obviously lead to major security issues.
So I have a URL which contains &title=blabla
I know how to extract the title, and return it. But I've been searching my ass off to get the full path to the filename when I only have the filename.
So what I must have is an way to search in all directories for an html file called 'blabla' when the only thing it has is blabla. After finding it, it must return the full path.
Anyone who does have an solution for me?
<?php
$file = $_GET['title'];
if ($title = '') {
echo "information.html";
} else {
//here it must search for the filepath and echo it.
echo "$filepath";
}
?>
You can use the solution provided here.
It allows you to recurse through a directory and list all files in the directory and sub-directories. You can then compare to see if it matches the files you are looking for.
$root = '/'; // directory from where to start search
$toSearch = 'file.blah'; // basename of the file you wish to search
$it = new RecursiveDirectoryIterator($root);
foreach(new RecursiveIteratorIterator($it) as $file){
if($file->getBasename() === $toSearch){
printf("Found it! It's %s", $file->getRealPath());
// stop at the first match
break;
}
}
Keep in mind that depending on the number of files you have, this can be slow as hell
For a start this line is at fault
if ($title = '') {
See http://www.php.net/manual/en/reserved.variables.files.php
I am a beginner to PHP so please forgive any ignorance...
I am using the exec() command as following to get the list of files in my media directory..
<?php // exec.php
$cmd = "dir"; // Windows
exec(escapeshellcmd($cmd), $output, $status);
if ($status) echo "Exec command failed";
else
{
echo "<pre>";
foreach($output as $line) echo "<a href='$line'>$line</a> \n";
}
?>
The problem is it gives the list of files along with the various timestamps of the filenames-
Volume in drive F is Movies
Volume Serial Number is 172B-1DE0
06/17/2011 01:11 AM 6,318 bck.gif
Hence, here it creates clickable link to each line for the output which needless to say does not work.
What I want is that it will only create clickable links for the filenames and not the extra meta information, which the user can then click to launch his native program like this-
video1.mpg
video2.mpg
bck.gif
You're far better off using PHP's directory manipulation functions instead. The scandir() function should be of particular interest to you.
http://uk.php.net/manual/en/book.dir.php
http://uk.php.net/manual/en/function.scandir.php
Don't forget that the scandir listing will include . and .. ao you'll need to remove them from the results set unless you plan to use them for navigation.
There is no need to use exec(); to list files in the directory, PHP has many build in functions for dealing with the file system:
From the readdir() manual page:
<?php
if ($dirHandle = opendir('.')) {
while (false !== ($nodeHandle = readdir($dirHandle ))) {
if ($nodeHandle == '.' || $nodeHandle == '..') {
continue;
}
echo "$nodeHandle \n";
}
closedir($dirHandle);
}
?>
I need to change the folder that "relative include paths" are based on.
I might currently be "in" this folder:
C:\ABC\XYZ\123\ZZZ
And in this case, the path "../../Source/SomeCode.php" would actually be in this folder:
C:\ABC\XYZ\Source
And realpath('.') would = 'C:\ABC\XYZ\123\ZZZ';
If however, realpath('.') were "C:\Some\Other\Folder"
Then in this case, the path "../../Source/SomeCode.php" would actually be in this folder:
C:\Some\Source
How do I change what folder is represented by '.' in realpath()?
Like this:
echo ('BEFORE = '.realpath('.')); // BEFORE = C:\ABC\XYZ\123\ZZZ
// Some PHP code here...
echo ('AFTER = '.realpath('.')); // AFTER = C:\Some\Other\Folder
How can I change the folder represented by '.', as seen by realpath()?
The function chdir() does this.
For example:
echo ('BEFORE = '.realpath('.')); // BEFORE = C:\ABC\XYZ\123\ZZZ
chdir('C:/Some/Other/Folder');
echo ('AFTER = '.realpath('.')); // AFTER = C:\Some\Other\Folder
Use the chdir() function.
Change your current working directory with chdir()
http://us.php.net/chdir