Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

Combine directory and file name in PHP ( equivalent of Path.Combine in .Net)

This should be a simple question, but I just can't recall the relevant API. A search on google with the term "combine directory name php" doesn't yield any results . So I guess I am doing both myself and the programming community a service by asking this question. this is now the top entry returned by Google and DDG!

How to combine directory and file name to form a full file path in PHP? Let's say the directory name is "D:setup program", and the file name is "mj.txt". The method should return me, on Windows "D:setup programmj.txt". Of course the method should return the correct file path in Linux or other OS.

The related function in .Net is Path.Combine, but in PHP, I couldn't recall that, even though I must have seen it before.

question from:https://stackoverflow.com/questions/1049949/combine-directory-and-file-name-in-php-equivalent-of-path-combine-in-net

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$filepath = $path . DIRECTORY_SEPARATOR . $file;

Although in newer versions of PHP it doesn't matter which way the slashes go, so it is fine to always use forward slashes.

You can get a correct absolute path using realpath(), this will also remove things like extra unnecessary slashes and resolve references like ../. It will return false if the path is not valid.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...