Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rename file in php

Tags:

php

I want to rename picture filename (without extension) to old.jpg from this code.

I have picture file in parent directory and the path is correctly

$old="picture";
$new="old.jpg";
rename($old , $new);

or this codes

$old="\picture";
$new="\old.jpg";
rename($old , $new);

$old="../picture";
$new="../old.jpg";
rename($old , $new);

$old="../picture";
$new="old.jpg";
rename($old , $new);

$old="./picture";
$new="./old.jpg";
rename($old , $new);

rename("picture", "old.jpg");

But I get this error:

 Warning: rename(picture,old.jpg) [function.rename]: The system cannot find the file specified. (code: 2) in C:\xampp\htdocs\prj\change.php on line 21
like image 916
DolDurma Avatar asked Nov 17 '12 21:11

DolDurma


People also ask

How can we rename file in PHP?

PHP rename() Function rename("images","pictures"); rename("/test/file1. txt","/home/docs/my_file. txt");

What is rename function in PHP?

rename() function in PHP The rename() function renames a file or directory. The function returns TRUE on success or FALSE on failure.

How do you rename a file in HTML?

Right-click on the item and select Rename, or select the file and press F2 . Type the new name and press Enter or click Rename.


2 Answers

You need to use either absolute or relative path (maybe better in that case). If it's in the parent directory, try this code:

old = '..' . DIRECTORY_SEPARATOR . 'picture';
$new = '..' . DIRECTORY_SEPARATOR . 'old.jpg';
rename($old , $new);
like image 189
Peter Krejci Avatar answered Sep 19 '22 14:09

Peter Krejci


A relative path is based on the script that's being executed ($_SERVER['SCRIPT_FILENAME'] when run in web server) which is not always the file in which the file operation takes place:

// index.php
include('includes/mylib.php');

// mylib.php
rename('picture', 'img506.jpg'); // looks for 'picture' in ../

Finding a relative path involves comparing the absolute paths of both the executing script and the file you wish to operate on, e.g.:

/var/www/html/index.php
/var/www/images/picture

In this example, the relative path is: ../images/picture

like image 39
Ja͢ck Avatar answered Sep 17 '22 14:09

Ja͢ck