PHP Functions: realpath()

Watch Out – Hard Code

Perhaps every developer knows that hard coded paths are no good! The code’s good to be flexible and extensible, but what the way to achieve that? In a typically developed application you’re completely sure the way the folders are nested will be permanent and no change will occur, and that’s maybe true, but however don’t be completely sure.

An Example

Let’s take a typical example. You’ve to access a uploaded file with PHP. By default the files are uploaded in the /tmp folder with PHP given name. That’s why immediately after the upload (the form submit) you’ve to process the _POST and the _FILES arrays and perhaps move the uploaded file somewhere else.

However you’d like to access this file wherever the application is – on the production servers or on the development server or even on the localhost!

I ran into that kind of problem/task. The thing I’d like to achieve was a bit different. I constructed the path with the dirname() function, but there were still ‘/../../’ chunks in it. So the solution is the realpath() function that removes those chunks and converts the path into one “calculated” real path to the file.

Let me show you an example:

// get the uploaded file path
$scriptPath = dirname(__FILE__);
 
// get the realpath to avoid the /../ part of the path
// with dirname they remain in the path
$uploadFolderPath = realpath($scriptPath . '/../../folder_name/');

If you were using dirname() you’d get something like that:

/folder1/folder2/folder3/../../folder2/file.txt

Now with realpath() the result is:

/folder1/folder2/file.txt

That’s more clear and even both are working correctly I’d prefer the second one!

Leave a Reply

Your email address will not be published. Required fields are marked *