I have this URL on localhost: http://localhost:7777/somesite/sites/default/files/devel-7.x-1.5.zip and want to get c:\xampp\htdocs\somesites\default\files\devel-7.x-1.5.zip.
As mentioned on this question PHP: Get absolute path from absolute URL:
$path = parse_url($url, PHP_URL_PATH);
echo $_SERVER['DOCUMENT_ROOT'] . $path;
The above snippet should let me get the actual path of the file. Unfortunately this is not working. When printing $path it returns the $url instead of somesites\default\files. Could this be because I'm running it on localhost:7777?
You can do this with server variables:
echo $_SERVER['DOCUMENT_ROOT'] . $_SERVER['REQUEST_URI'];
This might be causing because correct url is not being passed to parse_url function. Print the $url value before passing to parse_url function and check if it is printing appropriate value. You might be passing something like this http://http://localhost:7777/http://localhost:7777/somesite/sites/default/files/devel-7.x-1.5.zip in $url because of which when parse_url processes the $url, it returns your original $url.
Hope this helps :)
Try
$path = parse_url($url);
echo str_replace('/', "\\", $_SERVER['DOCUMENT_ROOT'].$path['host'].$path['path']);
Related
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
I have to extract a specific part of an URL.
Example
original URLs
http://www.example.com/PARTiNEED/some/other/stuff
http://www.example.com/PARTiNEED
in case 1 I need to extract
/PARTiNEED/
and in case 2 I need to extract the same part but add an additional "/" at the end
/PARTiNEED/
What I've got right now is this
$tempURL = 'http://'. $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
$tempURL = explode('/', $tempURL);
$tempURL = "/" . $tempURL[3] . "/";
is there a more convenient way to do this or is this solution fine?
It's normally a good idea to use PHP's built in functions for things like this where possible. In this case, the parse_url method is designed for parsing URLs.
In your case:
// Extract the path from the URL
$path = parse_url($url, PHP_URL_PATH);
// Separate by forward slashes
$parts = explode('/', $path);
// The part you want is index 1 - the first is an empty string
$result = "/{$parts[1]}/";
You don't need this part:
'http://'. $_SERVER['SERVER_NAME']
you can just do:
$tempURL = explode('/', $_SERVER['REQUEST_URI']);
$tempURL = "/" . $tempURL[1] . "/";
Edited index from 0 to 1 as commented.
Maybe regex suits your needs better?
$tempURL = "http://www.example.com/PARTiNEED/some/other/stuff"; // or $tempURL = "http://www.example.com/PARTiNEED
$pattern = '#(?<=\.com)(.+?)(?=/|$)#';
preg_match($pattern, $tempURL, $match);
$result = $match[0] . "/";
Here this should solve your problem
// check if the var $_SERVER['REQUEST_URI'] is set
if(isset($_SERVER['REQUEST_URI'])) {
// explode by /
$tempURL = explode('/', $_SERVER['REQUEST_URI']);
// what you need in in the array $tempURL;
$WhatUNeed = $tempURL[1];
} else {
$WhatUNeed = '/';
}
Dont worry about the trailing slash, that can be added anytime in your code.
$WhatUNeed = $tempURL[1].'/';
This will give you proper idea about your requirment.
<?php
$url_array = parse_url("http://www.example.com/PARTiNEED/some/other/stuff");
$path = $url_array['path'];
var_dump($path);
?>
now you can use string explode function to get your job done.
I am uploading a file using Codeigniter's File Uploading Library and trying to insert the URL into the database. Codeigniter only supplies the server_path when using $this->upload->data(), which isn't usable for displaying the image to users.
I could normally just do something like base_url('uploads) . '/' . $data['file_name'] but I am storing the images in a folder for each post.
For example, I am getting C:/xampp/htdocs/site/uploads/32/image.jpg as the full_path, how can I convert this to http://mysite.com/uploads/32/image.jpg
The only thing that comes to mind is using a regular expression, but I feel like there has to be PHP function or Codeigniter function to help with this?
How can I convert the server path into the correct URL?
You can use $_SERVER['HTTP_HOST']; to get the url. Using the ID for your post, you can construct your path like so:
$url = "http://" . $_SERVER['HTTP_HOST'] . "/" . $id . "/" . basename($data['file_name']);
the basename() function returns everything after the last / in your path.
you only need to save the filename to the database and just use the post id and filename:
$url = "http://mysite.com/uploads/" . $postID . "/" . $fileName;
to get the file name use: How to get file name from full path with PHP?
<?php
$path = "C:/xampp/htdocs/site/uploads/32/image.jpg";
$file = basename($path); // $file is set to "image.jpg"
$file = basename($path, ".jpg"); // $file is set to "image"
?>
In CodeIgniter you should use $config['base_url']
You can use the ENVIRONMENT to setup different base_url, for example:
switch(ENVIRONMENT)
{
case 'development':
$config['base_url'] = 'http://localhost/';
break;
case 'testing':
$config['base_url'] = 'http://testing.server.com/';
break;
default:
$config['base_url'] = 'http://liveserver.com/';
}
See config.php
Now simply replace your local path with the base_url, str_replace should do the job (documentation here)
$newpath = str_replace("C:/xampp/htdocs/site/", $config['base_url'], $localpath);
Also, if you're interested in getting parts of the path, you could use explode (documented here) with / to create an array with every "section" of your path
$pathElements = explode('/', $localpath);
In this case, $pathElements[0] is C:, $pathElements[1] is xampp, etc...
I have the following URL:
http://localhost/mysite.loc/web/app_dev.php/blah/blah/blah
I need to calculate the root URL to the app_dev.php script. The result for the above should be:
http://localhost/mysite.loc/web/
which will serve as the base path for images, in order to make their paths absolute.
How do I go about calculating the above path, and cater for different setups, vhosts etc?
I hope this is making sense! :)
The $_SERVER will likely give you what you are looking for. If I am interpreting what you are asking correctly then you can do something like:
$host = 'http://'.$_SERVER['HTTP_HOST'];
$dir = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
Then echo $host.$dir should give you your base path to which you can add whatever path you need.
Assuming you want it in app_dev.php its very easy:
$dir = dirname($_SERVER['PHP_SELF'])."/";
Note you don't need http://localhost/ part, it's silly.
Looks like this is what I needed:
$url = strpos($_SERVER['SERVER_SIGNATURE'], '443') !== false ? 'https://' : 'http://';
$url .= $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$split = preg_split('%/|\\\\%i', $_SERVER['SCRIPT_NAME']);
$url = preg_split("/{$split[count($split)-1]}/i", $url);
Did the trick, I just need to test it now.
As simple as: $path = $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF'])
To get the FQDN you would have to do something like so:
$path = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);'
this would produce the results like so:
http://localhost/mysite.loc/web/
https://localhost/mysite.loc/web/
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