Php - get path after php script - php

I have search high and low for an answer to my question and I cannot find it. Basically what I want to do is get the path after a php script. ex. "http://www.example.com/index.php/arg1/arg2/arg3/etc/" and get arg1, arg2, arg3, etc in an array. How can I do this in php and once I do this will "http://www.example.com/arg1/arg2/arg3/etc" still return the same results. If not then how can I achieve this?

Here is how to get the answer, and a few others you will have in the future. Make a script, e.g. "test.php", and just put this one line in it:
<?php phpinfo();
Then browse to it with http://www.example.com/test.php/one/two/three/etc
Look through the $_SERVER values for the one that matches what you are after.
I see the answer you want in this case in $_SERVER["PATH_INFO"]: "/one/two/three/etc"
Then use explode to turn it into an array:
print_r( explode('/',$_SERVER['PATH_INFO'] );
However sometimes $_SERVER["REQUEST_URI"] is going to be the one you want, especially if using URL rewriting.
UPDATE:
Responding to comment, here is what I'd do:
$args = explode('/',$_SERVER['REQUEST_URI']);
if($args[0] == 'index.php')array_shift($args);

Try like this :
$url ="http://www.example.com/index.php/arg1/arg2/arg3/etc/";
$array = explode("/",parse_url($url, PHP_URL_PATH));
if (in_array('index.php', $array))
{
unset($array[array_search('index.php',$array)]);
}
print_r(array_values(array_filter($array)));

Can you try using parse_url and parse_str
$url =$_SERVER['REQUEST_URI'];
$ParseUrl = parse_url($url);
print_r($ParseUrl);
$arr = parse_str($ParseUrl['query']);
print_r($arr);

Related

save the last part of url in variable

I want to get the last part of an url that looks like this:
http://localhost:8888/blog/public/index.php/categories/Horror
I've tried it with
$endOfUrl = end(explode('/',$url));
but the thing is I get a notice that "Only variables should be passed by reference"
I need this "Horror" to get it's ID in my database and get all the posts with this id, since I'm trying to code a blog to get experience with php.
Another question linked to this: Is it possible to make it dynamic so it can be used for all the other categories as well? Or do I have to do this for every single category?
I'm new to the world of php so I would really appreciate it if someone could help me on this.
Try like this way for end() but If I were you I will try basename() to get my job done.
<?php
$url = 'http://localhost:8888/blog/public/index.php/categories/Horror';
$exploded = explode('/',$url);
$endOfUrl = end($exploded);
echo $endOfUrl;
?>
Reason why it is not working on single line:
end() requires a reference, because it modifies the internal
representation of the array (i.e. it makes the current element pointer
point to the last element).The result of explode('.', $url) cannot be
turned into a reference and this is a restriction in the PHP language itself.
DEMO: https://3v4l.org/ttKui
Using basename(),
$url = 'http://localhost:8888/blog/public/index.php/categories/Horror';
echo basename($url);
DEMO: https://3v4l.org/pt2cQ

How do I get the depth of a URL using PHP?

I'd like to echo the depth (or number of directories from my home) of my current page's URL using PHP. How would I do that?
For example, if I'm on mysite.com, the output displays "0", if I'm on mysite.com/recipes, the output displays "1", and if I'm on mysite.com/recipes/pies, the output displays "2", and so on.
How do I do that?
I tried simplifying it and doing this, but it's exporting as 0:
$folder_depth = substr_count($_SERVER["PHP_SELF"] , "/");
echo $folder_depth;
Just for fun, here is my cheap and cheezy solution using PHP's parse_url() and its PHP_URL_PATH return value along with a couple of other functions:
$url = 'http://universeofscifi.com/content/tagged/model/battlestar_galactica.html';
echo var_dump(parse_url($url, PHP_URL_PATH));
echo count(explode('/', (parse_url($url, PHP_URL_PATH)))) - 2;
This returns:
string(47) "/content/tagged/model/battlestar_galactica.html"
3
I subtract 2 from the count to discard the domain at the front and the file at the end, leaving only the directory depth count.
If you won't have a query string, you can explode on /. If you will have a query string, you need to remove that first, such as...
$url = preg_replace('/?.*$/','',$url);
If you have http:// or https:// at the front of your URL, that can mess it up also. So remove it...
$url = preg_replace('~^https*://~','',$url);
Now, you only have the url as example.com/some/path/to/something. You can explode on / and get a count:
$a = explode('/',$url);
The size of $a will be 1 more than what you want. So, you need to subtract one:
$depth = sizeof($a)-1;
New problem... I just counted the file itself, such as example.com/links.html will come up as 1, not just 0. So, before the explode I need to get rid of the file name. But... how do I know if it is a file or a directory? That isn't built into the URL specification. For example, example.com/test could be a file or it could be a directory (and then it automatically goes to example.com/test/index.html). You need to assume what file extensions you will have and remove those files before you explode, such as:
$url = preg_replace('~/[^/]+.(html|php|gig|png|mp3)$~','',$url);
#kainaw, I like your answer! Thanks!
I took a spin on that. First, I noticed I was using the wrong PHP function to get the part of the URL I needed. Second, I needed to use #kaniaw's example and get the parts of the URL which I'm supposed to count, and ignore the others.
I also had to account for urls without content between the "/", so something like /word//// would still count as 1. Therefore, I only counted array elements after explode() which were not empty.
Here's my code:
$url = $_SERVER['REQUEST_URI'];
//echo "*".$_SERVER['REQUEST_URI']."*";
//$url = preg_replace('/?.*$/','',$url);
//$url = preg_replace('~^https*://~','',$url);
//$url = preg_replace('~/[^/]+.(html|php|gig|png|mp3)$~','',$url);
$a = explode('/',$url);
$depth =count(array_filter($a));
echo $depth;
I commented out some of those lines because I didn't seen them, but they were mentioned above.
Thanks!

basename not giving me complete URL PHP

Right now I'm printing the current URL I have and it kinda does it ok:
$currentURL = basename($_SERVER['PHP_SELF']);
The problem is that it only prints
solutions.php
instead of printing
solutions.php?id=581298a7-6c08-11e3-9bea-742f689f29f1
Anybody knows why this is happening? I need to get to print the part of
?id=581298a7-6c08-11e3-9bea-742f689f29f1
Because then I will be performing a substring to get just the ID.
Use parse_url, which parses a URL and returns its various components in a usable array. You'll also want to make sure you're parsing the correct string; in this case use:
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
Full usage:
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
print_r(parse_url($url));
This is expected behavior, because everything from the ? afterwards are not part of the filename. The parameters that you're looking for are in the $_GET superglobal.

PHP - Get the end of a URL

So I think I need to submit a new question for this...
Here is my old question: PHP - Get path minus root
I need a way in PHP to take the URL being any of the following...
http://kenthomes.net/plan_detail.php?mod=39
http://kenthomes.net/Amelia-Cove
and get everything after leaving me with...
"plan_detail.php?mod=39" // If there is no alias for that page
OR
"Amelia-Cove" // If that page has an alias being applied
In reality, they are the same page, because of the alias, but not all of these pages have aliases associated with them such as...
http://kenthomes.net/plan_detail.php?mod=52
unlike...
http://kenthomes.net/Amelia-Cove
Currently I am using...
trim($_SERVER['REQUEST_URI'],'/')
which gives me...
"Amelia-Cove" // Which is fine.
OR
"plan_detail.php" // Which is not okay.
I need..
"Amelia-Cove" // Which is fine.
OR
"plan_detail.php?mod=39" // Which is fine.
How do I do this?
You can get all the parts of an URL via parse_url()
For example;
$parts = parse_url('http://kenthomes.net/plan_detail.php?mod=39');
print_r($parts);
Should give you something like this:
Array
(
[scheme] => http
[host] => kenthomes.net
[path] => /plan_detail.php
[query] => mod=39
)
Which you can use to create your own URL containing the parts that you need
$_SERVER["REQUEST_URI"] only contains the URI.
When you also want the part after the ?, you need to also use $_SERVER["QUERY_STRING"].
Use:
trim($_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING'], '/');
Append $_SERVER['REQUEST_URI'] with $_SERVER['QUERY_STRING'].
PHP: $_SERVER - Manual
You can get the query string (the bit after the question mark), via $_SERVER['QUERY_STRING']
parse_url, and if you just want the far right, using str_split would be sufficient.
$data = parse_url($url, PHP_URL_PATH);
Should be enough.
Otherwise if responding to the current request, $_SERVER['REQUEST_URI'] might work, as that is the entire URI.
You can try this:
$uri = $_SERVER['REQUEST_URI'];
$qs = $_SERVER['QUERY_STRING'];
echo trim($uri . $qs, '/');

Remove certain part of string in PHP [duplicate]

This question already has answers here:
Get domain name (not subdomain) in php
(18 answers)
Closed 10 years ago.
I've already seen a bunch of questions on this exact subject, but none seem to solve my problem. I want to create a function that will remove everything from a website address, except for the domain name.
For example if the user inputs: http://www.stackoverflow.com/blahblahblah I want to get stackoverflow, and the same way if the user inputs facebook.com/user/bacon I want to get facebook.
Do anyone know of a function or a way where I can remove certain parts of strings? Maybe it'll search for http, and when found it'll remove everything until after the // Then it'll search for www, if found it'll remove everything until the . Then it keeps everything until the next dot, where it removes everything behind it? Looking at it now, this might cause problems with sites as http://www.en.wikipedia.org because I'll be left with only en.
Any ideas (preferably in PHP, but JavaScript is also welcome)?
EDIT 1:
Thanks to great feedback I think I've been able to work out a function that does what I want:
function getdomain($url) {
$parts = parse_url($url);
if($parts['scheme'] != 'http') {
$url = 'http://'.$url;
}
$parts2 = parse_url($url);
$host = $parts2['host'];
$remove = explode('.', $host);
$result = $remove[0];
if($result == 'www') {
$result = $remove[1];
}
return $result;
}
It's not perfect, at least considering subdomains, but I think it's possible to do something about it. Maybe add a second if statement at the end to check the length of the array. If it's bigger than two, then choose item nr1 instead of item nr0. This obviously gives me trouble related to any domain using .co.uk (because that'll be tree items long, but I don't want to return co). I'll try to work around on it a little bit, and see what I come up with. I'd be glad if some of you PHP gurus out there could take a look as well. I'm not as skilled or as experienced as any of you... :P
Use parse_url to split the URL into the different parts. What you need is the hostname. Then you will want to split it by the dot and get the first part:
$url = 'http://facebook.com/blahblah';
$parts = parse_url($url);
$host = $parts['host']; // facebook.com
$foo = explode('.', $host);
$result = $foo[0]; // facebook
You can use the parse_url function from PHP which returns exactly what you want - see
Use the parse_url method in php to get domain.com and then use replace .com with empty string.
I am a little rusty on my regular expressions but this should work.
$url='http://www.en.wikipedia.org';
$domain = parse_url($url, PHP_URL_HOST); //Will return en.wikipedia.org
$domain = preg_replace('\.com|\.org', '', $domain);
http://php.net/manual/en/function.parse-url.php
PHP REGEX: Get domain from URL
http://rubular.com/r/MvyPO9ijnQ //Check regular expressions
You're looking for info on Regular Expression. It's a bit complicated, so be prepared to read up. In your case, you'll best utilize preg_match and preg_replace. It searches for a match based on your pattern and replaces the matches with your replacement.
preg_match
preg_replace
I'd start with a pattern like this: find .com, .net or .org and delete it and everything after it. Then find the last . and delete it and everything in front of it. Finally, if // exists, delete it and everything in front of it.
if (preg_match("/^http:\/\//i",$url))
preg_replace("/^http:\/\//i","",$url);
if (preg_match("/www./i",$url))
preg_replace("/www./i","",$url);
if (preg_match("/.com/i",$url))
preg_replace("/.com/i","",$url);
if (preg_match("/\/*$/",$url))
preg_replace("/\/*$/","",$url);
^ = at the start of the string
i = case insensitive
\ = escape char
$ = the end of the string
This will have to be played around with and tweaked, but it should get your pointed in the right direction.
Javascript:
document.domain.replace(".com","")
PHP:
$url = 'http://google.com/something/something';
$parse = parse_url($url);
echo str_replace(".com","", $parse['host']); //returns google
This is quite a quick method but should do what you want in PHP:
function getDomain( $URL ) {
return explode('.',$URL)[1];
}
I will update it when I get chance but basically it splits the URL into pieces by the full stop and then returns the second item which should be the domain. A bit more logic would be required for longer domains such as www.abc.xyz.com but for normal urls it would suffice.

Categories