-2

How to rename file with name containing "/", in PHP example : "A / B"

$filename= "A / B";
rename("1.html", $filename.".html"); 

doesn't work!

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
filip
  • 41
  • 6
  • 3
    You can't do this on the vast majority of operating systems since `/` is used as a path delimeter for directories. Also "doesn't work !!!" is not a description of a problem. Check out [ask]. – CollinD Jan 06 '17 at 22:35
  • i can use `$filename = str_replace ("/", "-", $filename);` but i dont wanna change the original name of file – filip Jan 06 '17 at 22:37
  • I really doubt the original name of the file contained a `/` character. And you should most likely be doing quite a bit of sanitization on these filenames if you are receiving them from a user via the web. – CollinD Jan 06 '17 at 22:38
  • @filip The original name is `1.html`, it doesn't have `/` in it. – Barmar Jan 06 '17 at 22:51
  • are you serious !!! – filip Jan 06 '17 at 23:08
  • @filip Please do not forget to mark the coorect answert with the checkmark. ;) – michael-mammut Jan 13 '17 at 07:52

2 Answers2

1

On linux machines and on OSX, the forward slash (/) is a forbidden character. The file system will not let you use this character in a filename.

S. Imp
  • 2,833
  • 11
  • 24
  • 1
    Windows since at least 2000 as well. – CollinD Jan 06 '17 at 22:37
  • @filip Essentially, yes, there is no way. There might exist some file system that doesn't forbid it (I think the Rackspace CloudFiles storage system might not) but for any normal file system I think you are out of luck. – S. Imp Jan 06 '17 at 22:41
0

I try it and it is possible to modify the string, but as the other users say... it is possible/you will run into a problem with your OS. Becouse the / caracter is used by tree of the OS.

/                 --> is root
/folderX          --> is the folde X in the root folder
/folderX/yourFile --> is the file in the folderX in the root folder

This is the code I run on the website

<?php
$filename = "this/is/a/test";

$filename = str_replace("/", "-", $filename);
var_dump($filename)

?>

And this is the result

string(14) "this-is-a-test"

As you see this is a path to a file called test this/is/a/test

And this a filename without a path this-is-a-test

I hope this answer helps you to see the difference.

michael-mammut
  • 2,595
  • 5
  • 28
  • 46