Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php how to go one level up on dirname(__FILE__)

Tags:

php

dirname

I have a folder structure as follows:

mydomain.com   ->Folder-A   ->Folder-B 

I have a string from Database that is '../Folder-B/image1.jpg', which points to an image in Folder-B.

Inside a script in Folder-A, I am using dirname(FILE) to fetch the filename and I get mydomain.com/Folder-A. Inside this script, I need to get a string that says 'mydomain.com/Folder-B/image1.jpg. I tried

$path=dirname(__FILE__).'/'.'../Folder-B/image1.jpg'; 

This shows up as mydomain.com%2FFolder-A%2F..%2FFolder-B%2Fimage1.jpg

This is for a facebook share button, and this fails to fetch the correct image. Anyone know how to get the path correctly?

Edit: I hope to get a url >>>mydomain.com%2FFolder-B%2Fimage1.jpg

like image 304
aVC Avatar asked Jun 19 '12 05:06

aVC


People also ask

How do I move up one directory in PHP?

If you are using PHP 7.0 and above then the best way to navigate from your current directory or file path is to use dirname(). This function will return the parent directory of whatever path we pass to it.

What is dirname (__ FILE __) in PHP?

dirname(__FILE__) allows you to get an absolute path (and thus avoid an include path search) without relying on the working directory being the directory in which bootstrap. php resides. (Note: since PHP 5.3, you can use __DIR__ in place of dirname(__FILE__) .)

How do I go back to a parent directory in PHP?

The dirname() returns the parent directory's path that is $levels up from the current directory. Note that you can use both slash ( / ) and backslash ( \ ) as the directory separator character on Windows and the forward-slash ( / ) on other environments such as Linux and macOS.

What is dirname (__ DIR __?

__DIR__ : The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__) . This directory name does not have a trailing slash unless it is the root directory.


1 Answers

For PHP < 5.3 use:

$upOne = realpath(dirname(__FILE__) . '/..'); 

In PHP 5.3 to 5.6 use:

$upOne = realpath(__DIR__ . '/..'); 

In PHP >= 7.0 use:

$upOne = dirname(__DIR__, 1); 
like image 139
Petah Avatar answered Sep 22 '22 08:09

Petah