Help with rename if file exists

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
nofuse
Forum Newbie
Posts: 1
Joined: Tue Feb 05, 2008 6:31 pm

Help with rename if file exists

Post by nofuse »

Hi

I have a code im using but I need to change it to rename the file is it already exists instead of overwriting it, don't care what it is renamed to but must have the same extension i.e filename.mst or make up a random name ending in the extension .mst.

I have copied the existing full script below:

***** PLEASE USE THE

Code: Select all

TAG WHEN POSTING *****[/color]

Code: Select all

<?php
 
// gettimers.php
 
 
$key = 'xxxxxxxxx' ;
$filename = 'timer.mst' ;
$destination = 'ProgramFiles\Settings\MyStuff\CTs' ;
 
if ( ! file_exists($filename) ) {
 
 
    $url = sprintf( 'http://www.toppy.org.uk/timers/Sfetch.php/%s/%s', $key, $filename ) ;
 
    $timerinfo = @file_get_contents($url);
 
    
    if ( $timerinfo == '' ) {
        print "No timers waiting, or download error\n" ;
    } else if ( preg_match( '/^ERROR:/', $timerinfo )) {
        print $timerinfo ;
    } else {
    
    
    
        $timerfile = fopen( $filename, 'w' ) or die("Can't save timers to disk\n") ;
 
        fwrite($timerfile, $timerinfo) ;
        fclose($timerfile) ;
    }
 
}
 
 
if ( file_exists($filename)) {
    $tfcommand = sprintf("tfcopy %s \"#:\%s\%s\"", $filename, $destination, $filename) ;
    exec($tfcommand, $result) ;
    print "Command is $tfcommand\n";
 
    $res = implode(' ', $result) ; 
    
   if ( preg_match('/Copy done/', $res ))  {
        unlink($filename) ;
   }
}
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Re: Help with rename if file exists

Post by Ambush Commander »

The logic would be to check if the file exists, if it does, rename the existing one to a new file, and then perform the rename. Can we see at least an attempt?
Post Reply