php move_file | php move file from One Folder to Another Example

php move file Moves an uploaded file to a new location using The move_uploaded_file() function and use “rename()” function of php.

php move_file | php move file Examples

If you need to move file from one folder to another using php code then we can use “rename()” function of php

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

php move file Use the rename() function. I will learn you how simply you can move a file from one directory to another in PHP

Example – php move file from one folder to another

<?php
  
/* Store the path of source file */
$filePath = 'media/mainexample.jpeg';
  
/* Store the path of destination file */
$finalstepinationFilePath = 'blog/mainexample.jpeg';
  
/* Move File from images to blog folder */
if( !rename($filePath, $finalstepinationFilePath) ) {  
    echo "sorry, File can't be moved!";  
}  
else {  
    echo "Great, File has been moved!";  
} 
  
?>

Example

rename('media/demo_pakainfo_logo.jpg', 'images/demo_pakainfo_logo.jpg');

rename.php

NOTE: IF THERE IS AN EXISTING FRESH.TXT, IT WILL BE OVERRIDEN.

<?php
echo rename("antic.txt", "fresh.txt") ? "OK" : "ERROR";

BASIC MOVE FILE

<?php
$source = "antic.txt";
$finalstepination = "d:/temp/fresh.txt";
echo rename($source, $finalstepination) ? "OK" : "ERROR" ;

Don’t Miss : Php Rename Files

Read Also:  Vue.js Simple Login Script using PHP MySQLi Bootstrap

MOVE WITHOUT OVERRIDING

<?php
// (A) MOVE WITHOUT OVERRIDE
function safemove ($src, $finalstep) {
  if (file_exists($finalstep)) { return false; }
  return rename($src, $finalstep);
}
 
// (B) GO!
echo safemove("antic.txt", "fresh.txt") ? "OK" : "ERROR" ;

MOVE FILES OF CERTAIN EXTENSIONS

<?php
function movetype ($ext, $src, $finalstep) {
  // (A) Make DESTINATION FOLDER
  if (!file_exists($finalstep)) { 
    mkdir($finalstep); 
    echo "$finalstep created\r\n";
  }

  // (B) GET ALL FILES
  $files = glob($src."*.{".$ext."}", GLOB_BRACE);

  // (C) MOVE
  if (count($files)>0) { foreach ($files as $f) {
    $moveTo = $finalstep . 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/");

I hope you get an idea about php move_file | php move file.
I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.