Getting rid of files from domain name using PHP - php

I have the following URLs:
http://website.com/folder1/file.php
http://website.com/folder2/file.html
I want to know if there is any way in PHP that will let me hide the files and their extensions so the URLs will look like this:
http://website.com/folder1/
http://website.com/folder2/
I know this is possible using htaccess and mod_rewrite but I want to do it using PHP only.

ok I found the answer :
<? echo dirname("http://website.com/folder1/file.php"); ?>
so the url will look like this :
http://website.com/folder1/

dirname removes the last part of the URL.
To remove a specific string at the end of the URL if it exists, use rtrim:
$url = rtrim($url, 'file.php');
// http://website.com/folder/
$url = rtrim($url, '/');
// http://website.com/folder

Or a way via file extension detection:
function removeFilenameFromURL($url)
{
$urlPath = pathinfo($url);
// Remove if the URL has an file extension
if (isset($urlPath['extension'])) {
$lastPos = strripos($url, "/");
$url = substr($url, 0, $lastPos + 1);
}
return $url;
}
echo dirname("https://localhost/subdir/index.php") . "<br>";
echo removeFilenameFromURL("https://localhost/subdir/index.php") . "<br>";
echo phpversion();
OUTPUT:
https://localhost/subdir
https://localhost/subdir/
7.4.23
This always ensures a trailing slash.
ATTENTION:
With dirname() function on PHP 7.4 the trailing slash is gone ... (changing behavior on different PHP versions??)

Related

Trim function is removing my last character in different strings [duplicate]

I would like get the last path segment in a URL:
http://blabla/bla/wce/news.php or
http://blabla/blablabla/dut2a/news.php
For example, in these two URLs, I want to get the path segment: 'wce', and 'dut2a'.
I tried to use $_SERVER['REQUEST_URI'], but I get the whole URL path.
Try:
$url = 'http://blabla/blablabla/dut2a/news.php';
$tokens = explode('/', $url);
echo $tokens[sizeof($tokens)-2];
Assuming $tokens has at least 2 elements.
Try this:
function getLastPathSegment($url) {
$path = parse_url($url, PHP_URL_PATH); // to get the path from a whole URL
$pathTrimmed = trim($path, '/'); // normalise with no leading or trailing slash
$pathTokens = explode('/', $pathTrimmed); // get segments delimited by a slash
if (substr($path, -1) !== '/') {
array_pop($pathTokens);
}
return end($pathTokens); // get the last segment
}
echo getLastPathSegment($_SERVER['REQUEST_URI']);
I've also tested it with a few URLs from the comments. I'm going to have to assume that all paths end with a slash, because I can not identify if /bob is a directory or a file. This will assume it is a file unless it has a trailing slash too.
echo getLastPathSegment('http://server.com/bla/wce/news.php'); // wce
echo getLastPathSegment('http://server.com/bla/wce/'); // wce
echo getLastPathSegment('http://server.com/bla/wce'); // bla
it is easy
<?php
echo basename(dirname($url)); // if your url/path includes a file
echo basename($url); // if your url/path does not include a file
?>
basename will return the trailing trailing name component of path
dirname will return the parent directory's path
http://php.net/manual/en/function.dirname.php
http://php.net/manual/en/function.basename.php
Try this:
$parts = explode('/', 'your_url_here');
$last = end($parts);
$arr = explode("/", $uri);
Another solution:
$last_slash = strrpos('/', $url);
$last = substr($url, $last_slash);
1: getting the last slash position
2: getting the substring between the last slash and the end of string
Look here: TEST
If you want to process an absolute URL, then you can use parse_url() (it doesn't work with relative urls).
$url = 'http://aplicaciones.org/wp-content/uploads/2011/09/skypevideo-500x361.jpg?arg=value#anchor';
print_r(parse_url($url));
$url_path = parse_url($url, PHP_URL_PATH);
$parts = explode('/', $url_path);
$last = end($parts);
echo $last;
Full code example here: http://codepad.org/klqk5o29
I wrote myself a little function to get the last dir/folder of an url. It only works with real/existing urls, not theoretical ones. In my case, that was always the case, so ...
function uf_getLastDir($sUrl)
{
$sPath = parse_url($sUrl, PHP_URL_PATH); // parse URL and return only path component
$aPath = explode('/', trim($sPath, '/')); // remove surrounding "/" and return parts into array
end($aPath); // last element of array
if (is_dir($sPath)) // if path points to dir
return current($aPath); // return last element of array
if (is_file($sPath)) // if path points to file
return prev($aPath); // return second to last element of array
return false; // or return false
}
Works for me! Enjoy! And kudos to the previous answers!!!
This will keep the part after the last slash.
No worries about explode, when for example no slash is there.
$url = 'http://blabla/blablabla/dut2a/news.php';
$url = preg_replace('~.*/~', '', $url);
Will give
news.php

How to get website filename without extension and ?id=someid using php

I would like to get a website filename after domain without the extension and any query string.
I try to resolve with basename, but if the user put ? after .php the output is display incorrect.
https://example.com/customers/NameIWant.php
returns: NameIWan
https://example.com/customers/NameIWant.php?someting
returns: NameIWan.php?someting
$url= basename($_SERVER['REQUEST_URI'], '.php' . $_SERVER['QUERY_STRING'])
This $url I will use it to query MySQL.
And I don't need query in URL or any code only the name of the current file.
You can use parse_url() and basename() to get the filename only:
<?php
$url = 'https://example.com/customers/NameIWant.php?someting';
// /customers/NameIWant.php
$path = parse_url($url, PHP_URL_PATH);
// NameIWant
$filename = basename($path, '.php');
(Replace $url = 'https://example.com/customers/NameIWant.php?someting'; with $url = $_SERVER['REQUEST_URI'];)
https://www.php.net/manual/en/function.parse-url.php
https://www.php.net/manual/en/function.basename.php

dirname with folders that contain ~

I am trying to do a URL parser for my project, something very simple that gets an URL like you would enter it in a browser and convert it into a valid URL, once that is done parse such URL and grab all the images with full paths.
I was able to "fix" the user entered URL and pre-pend the http when needed, remove the last / on domain only (`http://www.domain.com/ become http://www.domain.com but http://www.domain.com/test/ stays unchanged).
The problem that I am having is dirname is parsing the path of certain folders.
my code looks something like this:
<?php
$url = 'www.domain.com/~folder/'; //This is a variable that changes often
$url = $this->fix_url($url); //$url is now http://www.domain.com/~folder/
$url_image = 'image.png';
$parse = parse_url($url);
$dir = (isset($parse['path'])?dirname($parse['path']):'');
$ret = 'http://'.$parse['host'].$dir.'/'.$url_image;
var_dump($parse, $dir, $ret);
?>
The way I was able to go around the problem is with this code that I use to find $dir
<?php
$path = (isset($parse['path'])?$parse['path']:'/');
$tmp = explode('/', $path);
if(is_array($tmp) && count($tmp) > 0){
array_pop($tmp);
}
$dir = implode('/', $tmp);
?>
But there must be a better way

PHP: Find images and links with relative path in output and convert them to absolute path

There are a lot of posts on converting relative to absolute paths in PHP. I'm looking for a specific implementation beyond these posts (hopefully). Could anyone please help me with this specific implementation?
I have a PHP variable containing diverse HTML, including hrefs and imgs containing relative urls. Mostly (for example) /en/discover or /img/icons/facebook.png
I want to process this PHP variable in such a way that the values of my hrefs and imgs will be converted to http://mydomain.com/en/discover and http://mydomain.com/img/icons/facebook.png
I believe the question below covers the solution for hrefs. How can we expand this to also consider imgs?
Change a relative URL to absolute URL
Would a regex be in order? Or since we're dealing with a lot of output should we use DOMDocument?
After some further research I've stumbled upon this article from Gerd Riesselmann on how to solve the absence of a base href solution for RSS-feeds. His snippet actually solves my question!
http://www.gerd-riesselmann.net/archives/2005/11/rss-doesnt-know-a-base-url
<?php
function relToAbs($text, $base)
{
if (empty($base))
return $text;
// base url needs trailing /
if (substr($base, -1, 1) != "/")
$base .= "/";
// Replace links
$pattern = "/<a([^>]*) " .
"href=\"[^http|ftp|https|mailto]([^\"]*)\"/";
$replace = "<a\${1} href=\"" . $base . "\${2}\"";
$text = preg_replace($pattern, $replace, $text);
// Replace images
$pattern = "/<img([^>]*) " .
"src=\"[^http|ftp|https]([^\"]*)\"/";
$replace = "<img\${1} src=\"" . $base . "\${2}\"";
$text = preg_replace($pattern, $replace, $text);
// Done
return $text;
}
?>
Thank you Gerd! And thank you shadyyx to point me in the direction of base href!
Excellent solution.
However, there is a small typo in the pattern. As written above, it truncates the first character of the href or src. Here are patterns that work as intended:
// Replace links
$pattern = "/<a([^>]*) " .
"href=\"([^http|ftp|https|mailto][^\"]*)\"/";
and
// Replace images
$pattern = "/<img([^>]*) " .
"src=\"([^http|ftp|https][^\"]*)\"/";
The opening parenthesis of the second replacement references are moved. This brings the first character of the href or src which doesn't match http|ftp|https into the replacement references.
I found that when the href src and base url started getting more complex, the accepted answer solution didn't work for me.
for example:
base url: http://www.journalofadvertisingresearch.com/ArticleCenter/default.asp?ID=86411&Type=Article
href src: /ArticleCenter/LeftMenu.asp?Type=Article&FN=&ID=86411&Vol=&No=&Year=&Any=
incorrectly returned: /ArticleCenter/LeftMenu.asp?Type=Article&FN=&ID=86411&Vol=&No=&Year=&Any=
I found the below function which correctly returns the url. I got this from a comment here: http://php.net/manual/en/function.realpath.php from Isaac Z. Schlueter.
This correctly returned: http://www.journalofadvertisingresearch.com/ArticleCenter/LeftMenu.asp?Type=Article&FN=&ID=86411&Vol=&No=&Year=&Any=
function resolve_href ($base, $href) {
// href="" ==> current url.
if (!$href) {
return $base;
}
// href="http://..." ==> href isn't relative
$rel_parsed = parse_url($href);
if (array_key_exists('scheme', $rel_parsed)) {
return $href;
}
// add an extra character so that, if it ends in a /, we don't lose the last piece.
$base_parsed = parse_url("$base ");
// if it's just server.com and no path, then put a / there.
if (!array_key_exists('path', $base_parsed)) {
$base_parsed = parse_url("$base/ ");
}
// href="/ ==> throw away current path.
if ($href{0} === "/") {
$path = $href;
} else {
$path = dirname($base_parsed['path']) . "/$href";
}
// bla/./bloo ==> bla/bloo
$path = preg_replace('~/\./~', '/', $path);
// resolve /../
// loop through all the parts, popping whenever there's a .., pushing otherwise.
$parts = array();
foreach (
explode('/', preg_replace('~/+~', '/', $path)) as $part
) if ($part === "..") {
array_pop($parts);
} elseif ($part!="") {
$parts[] = $part;
}
return (
(array_key_exists('scheme', $base_parsed)) ?
$base_parsed['scheme'] . '://' . $base_parsed['host'] : ""
) . "/" . implode("/", $parts);
}

How to get the last path in a URL?

I would like get the last path segment in a URL:
http://blabla/bla/wce/news.php or
http://blabla/blablabla/dut2a/news.php
For example, in these two URLs, I want to get the path segment: 'wce', and 'dut2a'.
I tried to use $_SERVER['REQUEST_URI'], but I get the whole URL path.
Try:
$url = 'http://blabla/blablabla/dut2a/news.php';
$tokens = explode('/', $url);
echo $tokens[sizeof($tokens)-2];
Assuming $tokens has at least 2 elements.
Try this:
function getLastPathSegment($url) {
$path = parse_url($url, PHP_URL_PATH); // to get the path from a whole URL
$pathTrimmed = trim($path, '/'); // normalise with no leading or trailing slash
$pathTokens = explode('/', $pathTrimmed); // get segments delimited by a slash
if (substr($path, -1) !== '/') {
array_pop($pathTokens);
}
return end($pathTokens); // get the last segment
}
echo getLastPathSegment($_SERVER['REQUEST_URI']);
I've also tested it with a few URLs from the comments. I'm going to have to assume that all paths end with a slash, because I can not identify if /bob is a directory or a file. This will assume it is a file unless it has a trailing slash too.
echo getLastPathSegment('http://server.com/bla/wce/news.php'); // wce
echo getLastPathSegment('http://server.com/bla/wce/'); // wce
echo getLastPathSegment('http://server.com/bla/wce'); // bla
it is easy
<?php
echo basename(dirname($url)); // if your url/path includes a file
echo basename($url); // if your url/path does not include a file
?>
basename will return the trailing trailing name component of path
dirname will return the parent directory's path
http://php.net/manual/en/function.dirname.php
http://php.net/manual/en/function.basename.php
Try this:
$parts = explode('/', 'your_url_here');
$last = end($parts);
$arr = explode("/", $uri);
Another solution:
$last_slash = strrpos('/', $url);
$last = substr($url, $last_slash);
1: getting the last slash position
2: getting the substring between the last slash and the end of string
Look here: TEST
If you want to process an absolute URL, then you can use parse_url() (it doesn't work with relative urls).
$url = 'http://aplicaciones.org/wp-content/uploads/2011/09/skypevideo-500x361.jpg?arg=value#anchor';
print_r(parse_url($url));
$url_path = parse_url($url, PHP_URL_PATH);
$parts = explode('/', $url_path);
$last = end($parts);
echo $last;
Full code example here: http://codepad.org/klqk5o29
I wrote myself a little function to get the last dir/folder of an url. It only works with real/existing urls, not theoretical ones. In my case, that was always the case, so ...
function uf_getLastDir($sUrl)
{
$sPath = parse_url($sUrl, PHP_URL_PATH); // parse URL and return only path component
$aPath = explode('/', trim($sPath, '/')); // remove surrounding "/" and return parts into array
end($aPath); // last element of array
if (is_dir($sPath)) // if path points to dir
return current($aPath); // return last element of array
if (is_file($sPath)) // if path points to file
return prev($aPath); // return second to last element of array
return false; // or return false
}
Works for me! Enjoy! And kudos to the previous answers!!!
This will keep the part after the last slash.
No worries about explode, when for example no slash is there.
$url = 'http://blabla/blablabla/dut2a/news.php';
$url = preg_replace('~.*/~', '', $url);
Will give
news.php

Categories