Вопрос

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?

Это было полезно?

Решение

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!

Другие советы

<?php
rename('images/image1.jpg','images/tmp.jpg');
rename('images/image2.jpg','images/image1.jpg');
rename('images/tmp.jpg','images/image2.jpg');
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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top