Strange basic file rename issue

Hello,

i can’t rename / move a file to another folder despite the source file is exist.

<?php
rename("/plugins/jQuery-File-Upload-master/server/php/files/quote_new.jpg","
/content/register/profile_pics/12_quote_new.jpg");
?>

error:
Warning: rename(/plugins/jQuery-File-Upload-master/server/php/files/quote_new.jpg,
/content/register/profile_pics/12_quote_new.jpg): No such file or directory in …

but if i put the source url with the domain name it shows the image.
ex: http://www.example.com//plugins/jQuery-File-Upload-master/server/php/files/quote_new.jpg

The file does not exist because the path is incorrect.

The leading right-hand-slash means it is in the root directory.

Maybe precede the file with $_SERVER['DOCUMENT_ROOT']

<?php
echo '<br>__DIR__ &nbsp;  '  . __DIR__;
echo '<br>getcwd() &nbsp; '  . getcwd();
$docRoot = $_SERVER["DOCUMENT_ROOT"] ;
echo '<br>$docRoot &nbsp; '  .$docRoot;
echo '<br>';

$src = '/plugins/jQuery-File-Upload-master/server/php/files/quote_new.jpg';
echo '<br>' .$src = $docRoot . $src;
echo '<br>' .$dst = $docRoot .'/content/register/profile_pics/12_quote_new.jpg';

if ( file_exists($src) ):
    $ok  = rename( $src, $dst);
    $msg = $ok ?  'Champion, file copied OK'  :   ' BIG Problem trying to copy file :(' ;
else:
  $msg = 'Yes we have no &nbsp; ' .$src;
endif;
echo '<br>' .$msg;
?>


**Edit:** Corrected syntax.
1 Like

Hi John,
Thanks for the very valuable dir commands. really appriciate it.
yes it works !!!

cheers!!

1 Like

You can also use the full path to the file itself. Generally, I don’t find $_SERVER['DOCUMENT_ROOT'] and dirname(__DIR__) very helpful because they don’t give an exact path. Say you are creating an installation folder and the root folder of the installation can change and vary depending on what the client wants it to be. That being said $_SERVER['DOCUMENT_ROOT'] won’t necessarily help because it only outputs the root directory up until your root folder stops. Where your domain folder beings is where it stops. So you would have to manually write in the directory you want. And that shouldn’t be the case because you want the file path to be dynamic and exact. So I propose using this

realpath(__DIR__)

I use it all the time because it gives you an exact path that the current file is in. All you need to do is then either strip out the current file name or go a directory level below.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.