Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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 program\mj.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.

like image 977
Graviton Avatar asked Jun 26 '09 16:06

Graviton


People also ask

What is path Combine in c#?

Combine(String[]) Combines an array of strings into a path. Combine(String, String) Combines two strings into a path. Combine(String, String, String)

Why we use path combine?

Path. Combine uses the Path. PathSeparator and it checks whether the first path has already a separator at the end so it will not duplicate the separators. Additionally, it checks whether the path elements to combine have invalid chars.


2 Answers

$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.

like image 88
Tom Haigh Avatar answered Sep 29 '22 11:09

Tom Haigh


I think the most clean and flexible way to do it would be using the join function plus the DIRECTORY_SEPARATOR constant:

$fullPath = join(DIRECTORY_SEPARATOR, array($directoryPath, $fileName)); 
like image 27
slashCoder Avatar answered Sep 29 '22 10:09

slashCoder