0

I need to swap file names using php. For example I have two files, first file: image1.jpg and the second file: image2.jpg. I want to swap the file names. So that the first file will be names image2.jpg and the second file will be named image1.jpg;

my failed attempt at this:

function swap($name1, $name2)
{
    $tempName1 = "temporary1";
    $tempName2 = "temporary2";
    myRename($name1, $tempName1);
    myRename($name2, $tempName2);
    myRename($tempName1, $name2);
    myRename($tempName2, $name1);
}

function myRename($oldTitle, $newTitle)
{
    $oldDirectory = "images/".$oldTitle.".jpg";
    $newDirectory = "images/".$newTitle.".jpg";
    rename($oldDirectory, $newDirectory);
}

How can I successfully swap the names?

user906357
  • 4,575
  • 7
  • 28
  • 38
  • Thank you for the responses. I found the actual problem, renaming was working, but not as quick as I needed. The way I solved this problem was to copy the files delete the originals, then copy them back with the new names – user906357 Jan 05 '14 at 18:43

3 Answers3

0
<?php
rename('images/image1.jpg','images/tmp.jpg');
rename('images/image2.jpg','images/image1.jpg');
rename('images/tmp.jpg','images/image2.jpg');
Samuel Cook
  • 16,620
  • 7
  • 50
  • 62
0
function myRename($oldTitle, $newTitle)
{
$fullpath="C:\HD path to that file";//sth like that for full path
    $oldDirectory = $fullpath."images/".$oldTitle.".jpg";
    $newDirectory = $fullpath."images/".$newTitle.".jpg";
    rename($oldDirectory, $newDirectory);
}

Use absolute or relative path to rename

Community
  • 1
  • 1
Gun2sh
  • 870
  • 12
  • 22
0

Something like this will solve your problem:

swap($file1, $file2, 'test/');

function swap ($name1, $name2, $dir = '') {
    rename($name1, $name1 . '-tmp');
    rename($name2, $name2 . '-tmp');
    rename($name2 . '-tmp', $dir . $name1);
    rename($name1 . '-tmp', $dir . $name2);
}

Hope this helps!

m79lkm
  • 2,960
  • 1
  • 22
  • 22
  • the directory also needs to exist before the function is executed - you can add code to check it and then create it if it does not exist – m79lkm Jan 02 '14 at 22:42