简体   繁体   中英

PHP rename function does not working

I want to move a file from one directory to another directory using PHP rename() function. But the function is not working. every time it display Not done . Your suggestions please.

Here is my code

<?php
    error_reporting(1);
    error_reporting('On');

    include 'includes/config.php';    // database configuration file

    $site_path = "http://www.website.com/";

    $file_name = "images800466507.jpg";
    $currentPath = 'TempImages/'.$file_name;    // ( file permission : 777 )
    $newPath = 'ImagesNew/'.$file_name;      // ( file permission : 755 )

    if( rename($site_path.$currentPath , $site_path.$newPath ) )
        echo 'done';
    else
        echo 'not done';
?>

You need to get your real path, for me real path /Applications/MAMP/htdocs/phptest but you can define ABSPATH like define('ABSPATH', dirname(__FILE__).'/');

Complete code:

 error_reporting(1);
 error_reporting('On');

define('ABSPATH', dirname(__FILE__).'/');

include 'includes/config.php';    // database configuration file

$file_name = "images800466507.jpg";
$currentPath = ABSPATH.'/TempImages/'.$file_name;    // ( file permission : 777 )
$newPath = ABSPATH.'/ImagesNew/'.$file_name;     // ( file permission : 755 )
if( rename($currentPath ,$newPath ) )
   echo 'done';
else
   echo 'not done';

I tested and it worked for me.

Perhaps using the full local path might do the trick

$filename = 'images800466507.jpg';

$currentpath = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'TempImages' . DIRECTORY_SEPARATOR . $filename;
$targetpath  = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'ImagesNew' . DIRECTORY_SEPARATOR . $filename;

echo realpath( $currentpath ) && rename($currentpath,$targetpath) ? 'done' : 'not done';

Does the source file exist at the location specified?

if( !file_exists( $currentpath ) ) echo 'Bad Foo - ' . $currentpath . ' not found!';

Add / before TempImages/ and ImagesNew/ directory like /TempImages/ and /ImagesNew/

<?php
    error_reporting(1);
    error_reporting('On');

    include 'includes/config.php';    // database configuration file

    //$site_path = "http://www.website.com/";

    $file_name = "images800466507.jpg";
    $currentPath = '/TempImages/'.$file_name;    // ( file permission : 777 )
    $newPath = '/ImagesNew/'.$file_name;      // ( file permission : 755 )

    if( rename($currentPath , $newPath ) )
        echo 'done';
    else
        echo 'not done';
?>

more details rename function http://php.net/manual/en/function.rename.php

获取真实路径可以提供帮助:

$file = realpath($filename);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM