Moving local files php

PHP: Copy, Rename or Move a File

PHP can only copy, rename or move files that are of the same owner with who is running the PHP script. After making sure of this, you can proceed to:

Copy a file to another place in PHP:

$old = '/tmp/yesterday.txt'; $new = '/tmp/today.txt'; copy($old, $new) or die("Unable to copy $old to $new.");

Rename a file and give it a new name:

$old = '/tmp/today.txt'; $new = '/tmp/tomorrow.txt'; rename($old, $new) or die("Unable to rename $old to $new."); 

Move a file to a new place in PHP:

if (copy("/tmp/code.c","/usr/local/src/code.c")) < unlink("/tmp/code.c"); >

Apparently you must make sure the copying is successful before doing the deletion.

Читайте также:  Удалить квадратные скобки php

Of course you can always execute a native Linux shell command such as ‘cp’ and ‘mv’ to do the dirty work for you instead of resorting to a PHP function. In this situation, you need the php function exec() to execute an external command.

What is PHP framework & Who are the Best PHP Frameworks?

Cron jobs (Crontab jobs) tricks and tips on DreamHost

17 thoughts on “PHP: Copy, Rename or Move a File”

Hi, maybe you could help me with a problem i’m having, i need ti rename a file, with a specific name, how can i create a function that let do the following, if the file exist, rename the file with a new name like, document.php, document_2.php, document_3.php, document_4.php. i need to create a function to do that, when it renames a file rename it with the next number. thank you

Two and half years overdue but maybe it can help someone else. Amazing that I was just using this code. Maybe there’s a better way but I’ve used something similar so here’s a function to achieve that. $file = “/files/docs/document.php”;
$file = rename_existing($file); returns full path with /document_1.php if it exists, or /document_2.php if document_1.php exists.
Returns same filename if file doesn’t exist, Simple really //add _# to file name if exists
function rename_existing($file) $ext = strtolower(end(explode(“.”, basename( $file ))));
$filename = basename($file, “.$ext”)
$dir = str_replace(“$filename.$ext”, “”, $file); if(file_exists($dir . “$filename.$ext”)) for ($i = 1; ; $i++) < //I don’t know why I used for instead of while
$new_name = $dir . $filename . ‘_’ . $i . $ext;
if (!file_exists($new_name)) return $new_name;
break;
>
>
>
else< return $file; >
> Sorry, it’s untested but I’m sure it can be fixed or improved easily

Читайте также:  Sub pages in php

Источник

6 Ways To Move Files In PHP (Simple Examples)

Welcome to a quick tutorial on how to move files in PHP. Need to move a file from one folder into another?

Moving files in PHP is as simple as using a single function – rename(«SOURCE.FILE», «FOLDER/TARGET.FILE») . Yes, there is no move file function in PHP, and we literally “rename” a file into another folder.

That should cover the basics, but things are different when it comes to “advanced file moving” – Read on for more examples!

TLDR – QUICK SLIDES

Common Ways To Move Files In PHP

TABLE OF CONTENTS

WAYS TO MOVE FILES IN PHP

All right, let us now get into the various ways and examples of how to move files in PHP.

1) BASIC RENAME FILE

As in the introduction, changing a file name is as easy as using the rename() function. But please take note that if there is an existing new.txt , it will be overridden without any warning.

2) BASIC MOVE FILE

As in the introduction again, there is no move() function in PHP – We literally just use rename() to move a file from one directory to another.

3) MOVE WITHOUT OVERRIDING

 return rename($src, $dest); > // (B) GO! echo safemove("old.txt", "new.txt") ? "OK" : "ERROR" ;

To prevent overriding on moving files, we can do a simple file_exists() check – Then, you decide. Either don’t move the file or choose a different file name.

4) MOVE FILES OF CERTAIN EXTENSIONS

 // (B) GET ALL FILES $files = glob($src."*.", GLOB_BRACE); // (C) MOVE if (count($files)>0) < foreach ($files as $f) < $moveTo = $dest . basename($f); echo rename($f, $moveTo) ? "$f moved to $moveTo\r\n" : "Error moving $f to $moveTo\r\n"; >> > movetype("jpg,png,gif", "d:/from/", "d:/to/");

Only want to move certain types of files in a folder? Use the glob() function to help filter out those files first, then move them one-by-one.

5) MOVE FILES TO ANOTHER SERVER

 curl_file_create($file), // NOTE: PHP 5.5+ ONLY "key" => "value" // OPTIONAL EXTRA FIELDS ]); // (B) SEND FILE $results = curl_exec($curl); curl_close($curl); // (C) DELETE LOCAL FILE AFTER SUCCESSFUL SEND if ($results == "OK")

There are actually quite a number of ways to move files from one server to another. This is a “PHP way” if you don’t want to set up an FTP server, shared drive, or anything of that sort.

On the “source server”, we will use CURL (client URL) to send the file to the “destination server”. Thereafter, we delete the file after a successful transfer.

 */ // (B) WORKS THE SAME AS REGULAR FILE UPLOAD // move_uploaded_file(SOURCE, DESTINATION) echo move_uploaded_file($_FILES["up"]["tmp_name"], $_FILES["up"]["name"]) ? "OK" : "ERROR" ; // (C) FOR DEBUGGING // print_r($_SERVER); // print_r($_POST); // print_r($_FILES);

On the “destination server”, we handle the file transfer just like a “normal file upload”. But you might want to protect this script a little more – Verify the identity of the client, restrict by IP address, or maybe set a “secret key”.

6) MOVE FILES WITH COMMAND PROMPT

Finally, this is not exactly using PHP to move files… But we are running a shell command to move files from PHP.

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

SUPPORT

600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

THE SUMMARY

TUTORIAL VIDEO

INFOGRAPHIC CHEAT SHEET

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Источник

PHP Move and Copy File From One Folder to Another

PHP move and copy all files from one folder or directory to another folder. In this tutorial, you will learn How to move a file into a different folder or directory on the server using PHP and as well as How to copy a files into a different folder on the server using PHP?

Move and Copy File From One Folder to Another in PHP

PHP Move File From One Folder to Another

If you need to move file from one folder/directory to another using php code then you can use “rename()” function of php. php provide rename function to move your file from one place to another.

First of all, you need to see syntax of rename() function.

bool rename( string $source, string $destination, resource $context )

See the explanation of rename() function parameters are followings:

$source: you need to give file path that you want to rename.

$destination: you need to give file path for destination source.

$context: this is optional, It specifies the context resource created with stream_context_create() function.

In this example, you first define the source path of the file you want to move ( $source ) and the destination folder where you want to move the file to ( $destination ).

Then, you use the rename() function to actually move the file. The rename() function takes two parameters – the current file location and the new file location. In this case, you pass the $source variable as the current file location, and concatenate the $destination variable with the basename of $source (i.e. just the filename without the folder path) to create the new file location.

Finally, you use an if statement to check whether the file was moved successfully or not, and echo an appropriate message to the user.

Note that you will need to have the appropriate file permissions in order to move files on your server. If you encounter any errors while trying to move files, it’s possible that you don’t have the correct permissions to do so.

PHP Copy File From One Folder to Another

If you need to copy file from one folder/directory to another using php code then you can use “copy()” function of php. php provide copy function to move your file from one place to another.

First of all, you need to see syntax of copy() function.

bool copy( string $source, string $destination, resource $context )

See the explanation of copy() function parameters are followings:

$source: you need to give file path that you want to copy.

$destination: you need to give file path for destination source.

$context: this is optional, It specifies the context resource created with stream_context_create() function.

$source_file = ‘/path/to/source/file.jpg’; $destination_file = ‘/path/to/destination/file.jpg’; if (copy($source_file, $destination_file)) < echo "File copied successfully."; >else

In this example, you first define the source file and destination file paths using variables $source_file and $destination_file , respectively.

Then you use the copy() function in PHP to copy the file. The copy() function takes two parameters: the first parameter is the path to the source file, and the second parameter is the path to the destination file.

If the file is successfully copied, the copy() function returns true and the message “File copied successfully” is echoed. Otherwise, if there is an error copying the file, the copy() function returns false and the message “Error copying file” is echoed.

Note that in order to copy a file, the PHP script needs to have the necessary permissions to read the source file and write to the destination file. If you encounter any errors copying a file, make sure to check the file permissions on both the source and destination files.

Conclusion

In this tutorial, you have learned how to move and copy a file into a different folder or directory on the server using PHP functions.

Источник

Move a file with PHP.

In this tutorial, we will show you how to move a file using PHP.

To do this, we will be using PHP’s native rename function. As the name suggests, this function renames a given file or directory.

Don’t let the name of the function confuse you. By renaming the path to the file, we are essentially moving it.

For this tutorial, we will create two directories called directory_a and directory_b.

In directory_a, we have a text file called sample-file.txt.

Using PHP, we are going to move sample-file.txt from directory_a to directory_b.

Take a look at the following example.

//The file path of the file that we want to move. //In this case, we have a txt file called sample-file.txt $currentFilePath = ‘directory_a/sample-file.txt’; //Where we want to move the file to. In this example, we //are moving the .txt file from directory_a to directory_b $newFilePath = ‘directory_b/sample-file.txt’; //Move the file using PHP’s rename function. $fileMoved = rename($currentFilePath, $newFilePath); if($fileMoved)

  1. We specified the file path of the current file. This is the file that we want to move.
  2. After that, we specified the new file path. This is the path and filename that we want our new file to have. In other words, this is where we want to move it to. Note that if you want to give it a different filename, then you can simply change the “sample-file” segment of the $newFilePath variable to something else.
  3. In order to move the file, we used PHP’s rename function. PHP’s rename function takes in $currentFilePath as the first parameter ($oldname) and $newFilePath as the second parameter ($newname).
  4. If the move is successful, then the rename will return a boolean TRUE value.

The rename function will overwrite existing files!

It is important to note that the rename function will overwrite existing files. In other words, if $newFilePath is the name of an existing file, then that file will be overwritten.

As a result, you might need to be careful about blindly moving files.

The file that you want to move must exist.

If $currentFilePath does not exist, then the following PHP warning will be thrown.

“Warning: The system cannot find the file specified.”

To guard against these kind of issues, you can use PHP’s is_file function to see if the files exist or not before you attempt to move it.

A code sample showing what this might look like.

In the PHP above, we checked to see if the file already exists before we called the rename function. This way, we can be sure that we’re not overwriting something by mistake.

Источник

Оцените статью