PHP

COMMON WAYS TO MOVE FILES IN PHP

(quick guide & examples)

THERE IS NO "MOVE" FUNCTION IN PHP. USE RENAME TO MOVE FILES.

BASIC FILE MOVE

01

echo rename(   "OLD/old.txt", "NEW/new.txt" ) ? "OK" : "ERROR";

RENAME WILL OVERRIDE BY DEFAULT. DO A MANUAL CHECK IF YOU DON'T WANT TO.

MOVE WITHOUT OVERRIDE

02

function safemove ($src, $dest) {   if (file_exists($dest)) { return false; }   return rename($src, $dest); }

echo safemove(   "OLD/old.txt", "NEW/new.txt" ) ? "OK" : "ERROR";

function movetype ($ext, $src, $dest) {   CREATE DESTINATION FOLDER   if (!file_exists($dest)) { mkdir($dest); }

MOVE CERTAIN EXTENSIONS ONLY

03

  GET & MOVE FILES   $all = glob($src."*.{".$ext."}",    GLOB_BRACE);   if (count($all)>0) { foreach ($all as $f) {     $moveTo = $dest . basename($f);     echo rename($f, $moveTo)       ? "$f moved" : "$f error";   }} }

movetype("jpg,png,gif", "OLD/", "NEW/");

WINDOWS echo exec("move OLD/old.txt NEW/new.txt");

COMMAND LINE MOVE FILE

04

LINUX echo exec("mv OLD/old.txt NEW/new.txt");