server path, minus the current folder - php

Alright.
Think I am doing this far too complicated and there is an easier solution. I need to get the current server path $_SERVER['DOCUMENT_ROOT']; minus the current folder.
$full_path = $_SERVER['DOCUMENT_ROOT'];
$current_folder = strrchr( $full_path, '/' );
$strlength = strlen( $current_folder ) - 1;
$pathlength = strlen( $full_path );
$newlength = $pathlength - $strlength;
$newpath = substr( $full_path, 0, $newlength );
This code works, but I think it might be overkill.
Thanks,
Pete

dirname() is very handy for this.
dunno what path you're asking for though, gonna give you both:
$above_root = dirname($_SERVER['DOCUMENT_ROOT'])."/";
$above_current = dirname(dirname(__FILE__))."/";

Use the function realpath and go one folder higher by adding /../:
$newpath = realpath($_SERVER["DOCUMENT_ROOT"] . "/../");

Couldn't you just do something like this? It's not really pretty, but as far as I know you can just append .. to a path.
$parent = $_SERVER['DOCUMENT_ROOT'].'/../';
You might want to check if $_SERVER['DOCUMENT_ROOT']; has the directory separator in the end, and if you need to add it or not.

Try:
dirname($_SERVER['DOCUMENT_ROOT']);
PHP offers all kind of functions when working with paths and filesystem: http://www.php.net/manual/en/ref.filesystem.php

$newpath = preg_replace("/[^\/]+$/", "", $_SERVER['DOCUMENT_ROOT']);

Check out this:
$path = $_SERVER['DOCUMENT_ROOT'];
$dirs = explode('\\', $path);
$pathWithoutDir = array_slice($dirs, 0, count($dirs) - 1);
I guess that dirty code aboive will work. You can also change $_SERVER['DOCUMENT_ROOT']; to __DIR__ which is equal to dirname(__FILE__).
EDIT: Code updated.

Related

How to create dynamic path using php variable?

I want to create a path with dynamic variable.
echo $path='App\Widgets\mywidgetname';
I want to replace mywidgetname then I have to put a variable like this
$path='App\Widgets\'.$widgetname; // (but this not working)
Try this,
$path = 'App\Widgets\mywidgetname';
$path = str_replace('mywidgetname', $widgetname, $path);
OR
$path = 'App\Widgets\mywidgetname';
$path = substr($path, 0, strrpos($path, "\\") + 1) . $widgetname;
You can use:
$path = sprintf("App\Widgets\%s", $widgetname);
echo $path;

How can I convert a file uri to relative path in drupal8

I'm trying to find the way to convert an uri like
public://field/image/link-carousel.png
to a relative path
sites/default/files/directory/link-carousel.png
(of course this is an example because public:// could have other path).
How to do it?
Code:
if(isset($article_node['field_image']['und']['n0'])){
$uri = $article_node['field_image']['und']['n0']['uri'];
$realpath = \Drupal::service('file_system')->realpath($uri);
$path = str_replace($_SERVER['DOCUMENT_ROOT'] . '/', '', $realpath);
}
here on printing $uri will get public://field/image/link-caribbean-carousel-epic-press-release.png.on printing $realpath it gives a blank page.
Taken from https://gist.github.com/illepic/fa451e49c5c43b4a1742333f109dbfcd:
// public://images/blah.jpg
$drupal_file_uri = File::load($fid)->getFileUri();
// /sites/default/files/images/blah.jpg
$image_path = file_url_transform_relative(file_create_url($drupal_file_uri));
/** #var Drupal\file\Entity\File $file */
$file = // get file.
$file->createFileUrl(TRUE); // to get relative path
$file->createFileUrl(FALSE); // to get absolute path https://
Link : https://api.drupal.org/api/drupal/core%21modules%21file%21src%21Entity%21File.php/function/File%3A%3AcreateFileUrl/8.7.x
Use FileSystem::realpath() to convert from sream-wrapped URIs:
use Drupal\Core\File\FileSystem;
//$realpath = drupal_realpath($uri); // D7, D8 deprecated
$realpath = FileSystem::realpath($uri);
$path = str_replace($_SERVER['DOCUMENT_ROOT'].'/','',$realpath);
UPD: For some reason the above example is not valid, we need to use file_system service instead:
$uri = $node->field_document->entity->getFileUri();
$realpath = \Drupal::service('file_system')->realpath($uri);
$path = str_replace($_SERVER['DOCUMENT_ROOT'] . '/', '', $realpath);
Since Drupal 9.3 you can do:
$relativePathToFile = \Drupal::service('file_url_generator')->generateString($thumbnailUri);
See: https://www.drupal.org/node/2940031

Find FILE path relative to the htdocs directory

I have a script which displays the images present on a folder.
E.g. Script path (from HTDOCS):
/admin/global/thisscript.php
E.g. Pictures folder path (from HTDOCS):
/public/test/images/
Now I need to print under each image the path of the file starting from the HTDOCS directory.
E.g. if I have:
$picture1 = /WEB/mysite/htdocs/public/test/images/picture1.png
$picture1name = basename($picture1)
I'd like to print
print "/public/test/images/".$picture1name
having
/public/test/images
in a variable which is automatically update if picture1.png path changes.
If I use
$_SERVER['PHP_SELF']
it returns the path of the file I'm displaing. Also
__FILE__
__DIR__
basename
dirname
are not working for me.
How can I get the path?
Thank you
perhaps $_SERVER['DOCUMENT_ROOT']
edit:
Something like:
$path = "/WEB/mysite/htdocs/public/test/images/picture1.png";
$path = dirname(str_replace($_SERVER['DOCUMENT_ROOT'], '', $path));
Not sure if this could help but could you explode the path result you have and build it back from the HTDOCS entry? something like:
$fullpath = /WEB/mysite/htdocs/public/test/images/picture1.png
$pathbits = explode("/", $fullpath);
$newpath = "";
$foundstart = false;
foreach($pathbits as $key => $value){
if ($value == "htdocs" || $foundstart == true) {
$foundstart = true;
$newpath = $newpath + "/" + $value;
}
}

php php_replace regex \\\ forward slash

I'm calling an Amazon API to get a URL to book cover thumbnails.
The thumbnail URL comes back like this:
\\ebc.amazon.com\images\EtcLkasff-_-23.jpg
The forward slashes are the problem. To make these images show up on my page is replace the "\" with a "/". But, my regex php_replace syntax is failing me.
I've got this:
$thumbnail = str_replace('\', '//', $apiString);
I've tried
$thumbnail = str_replace('\\', '//', $apiString);
and it still doesn't work.
Thanks in advance, everyone!!
EDIT:::
after I do:
$thumbnail = "http://" . $thumbnail;
The URL looks like this:
http://\/\/ecx.images-amazon.com\/images\/I\/51vCLCTcmAL._SL75_.jpg
I've tried
$picture4 = str_replace('\', '/', $picture4);
This gives me an escape error.
I'm sorry :( One more edit to make things perfectly clear:
I've done this:
// get amazon picture URL
$picture1 = preg_split('/,/', str_replace("\"", "", $details));
$picture2 = preg_split('/:/', $picture1[7]);
$picture3 = preg_replace('/\\//','/',$picture2[2]);
$picture4 = preg_replace('/\\//','/',$picture3);
// $picture4 = str_replace('\', '/', $picture4);
$picture4 = "http://" . $picture4;
echo "<pre>";print_r($picture4);echo "</pre>";
At this point, $picture4 is:
http://\/\/ecx.images-amazon.com\/images\/I\/51vCLCTcmAL.SL75.jpg
This should really be all you need:
$thumbnail = str_replace('\\', '/', $apiString);
// ^^^ the backslash must be escaped
This would convert:
\\ebc.amazon.com\images\EtcLkasff-_-23.jpg
to
//ebc.amazon.com/images/EtcLkasff-_-23.jpg

How can I get the current web directory from the URL?

If I have a URL that is http://www.example.com/sites/dir/index.html, I would want to extract the word "sites". I know I have to use regular expressions but for some reason my knowledge of them is not working on PHP.
I am trying to use :
$URL = $_SERVER["REQUEST_URI"];
preg_match("%^/(.*)/%", $URL, $matches);
But I must be doing something wrong. I would also like it to have a catch function where if it is at the main site, www.example.com then it would do the word "MAIN"
Edit: sorry, I've known about dirname...It gives the full directory path. I only want the first directory.... So if its www.example.com/1/2/3/4/5/index.html then it returns just 1, not /1/2/3/4/5/
Use the dirname function like this:
$dir = dirname($_SERVER['PHP_SELF']);
$dirs = explode('/', $dir);
echo $dirs[0]; // get first dir
Use parse_url to get the path from $_SERVER['REQUEST_URI'] and then you could get the path segments with explode:
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', substr($_SERVER['REQUEST_URI_PATH'], 1));
echo $segments[1];
The dirname function should get you what you need
http://us3.php.net/manual/en/function.dirname.php
<?php
$URL = dirname($_SERVER["REQUEST_URI"]);
?>
Just wanted to recommend additionally to check for a prefixed "/" or "\"
and to use DIRECTORY_SEPARATOR :
$testPath = dirname(__FILE__);
$_testPath = (substr($testPath,0,1)==DIRECTORY_SEPARATOR) ? substr($testPath,1):$testPath;
$firstDirectory = reset( explode(DIRECTORY_SEPARATOR, dirname($_testPath)) );
echo $firstDirectory;
A simple and robust way is:
$currentWebDir = substr(__DIR__, strlen($_SERVER['DOCUMENT_ROOT']));
If you are worried about DIRECTORY_SEPARATORS, you could also do:
$currentWebDir = str_replace('\\', '/', substr(__DIR__, strlen($_SERVER['DOCUMENT_ROOT'])));
Also be aware of mod_rewrite issues mentioned by FrancescoMM

Categories