Remove slash from final string and GET - php

So earlier I was using http://localhost/profile.php?username=joe but now I'm using htaccess to make the URL look nice, so this is what it now looks like http://localhost/joe. Now here's the issue, before I did this
$username = $_GET['username'];
And then use it to get the username, but now how would I do it? I've seen other posts, but they seem to use longer and more complex URLs.
I can do this
$url = 'http://localhost/joe';
echo parse_url($url, PHP_URL_PATH);
And it seems to work fine, but I get a / before the actual result so I get /joe, and I want joe. I've also tried stripslashes but that didn't seem to work. So any ideas?

Trim the result on the left site to avoid removing or replacing slashes that are part of the actual value.
$result = ltrim($path, '/');

You can also use explode and array_pop.
$url = 'http://localhost/joe';
echo array_pop(explode("/", $url))

Use str_replace(). Like this
$url = 'http://localhost/joe';
$final = parse_url($url, PHP_URL_PATH);
$result = str_replace('/','',$final);
echo $result;
stripslashes() works for backward slashes, not forward slashes

Just a substr call should also work:
$url = 'http://localhost/joe';
echo substr(parse_url($url, PHP_URL_PATH), 1); // joe

You can learn about placeholders in routes. Try this article
Route Parameters
Route parameters can be used to insert placeholders into your route definition. This will effectively create a pattern in which URI segments can be collected and passed to the application’s logic handler.
This might sound a little confusing, but when you see it in action everything will fall into place. Here we go...
<?php
// app/routes.php
// routes for the books section
Route::get('/books', function()
{
return 'Books index.';
});
Route::get('/books/{genre}', function($genre)
{
return "Books in the {$genre} category.";
});

Also there is basename()
echo basename('http://localhost/joe'); //joe

It's better to use this rule or mod proxy to rewrite REQUEST_URI:
RewriteCond %{REQUEST_URI}
Then you can get your parameter and remove its slashes easily with trim($_SERVER['REQUEST_URI'],'/').

Related

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, '/');

Small issue with str_replace

This is my code:
$produrl = '/'. basename(str_replace(".html","",$_cat->getUrl())) .'/' . basename($_product->getProductUrl()) ;
$_cat->getUrl() returns this:
http://website.com/category/subcategory.html
I need: for $produrl part of basename(str_replace(".html","",$_cat->getUrl()))to return category/subcategory
The issue:
It gives back only category without /subcategory I know the issue is in the str_replace it's wrong isn't? Can you help me with that?
Pleast Note I have 2 Cases:
Sometimes I get http://website.com/category/subcategory.html.
Sometimes http://website.com/category.html
And I would like it to work with both of them :)
You should use parse_url instead:
$url = parse_url($_cat->getUrl());
$produrl = str_replace(".html","",$url['path']);
The problem is that you're using the basename() function.
Take a look at the documentation for it: http://php.net/manual/en/function.basename.php
It will only return the trailing string after the "/" (forward slash) or "\" (back slash, for Windows).

Why is my page resulting in a redirect loop?

I have a series of commands that check whether a url looks something like
http://localhost/questions/32/new-question-from-peter
and if the last part is missing I redirect to this. I do allow for a fragment at the end.
However, i would like to add a possibilty for it to be
http://localhost/questions/32/new-question-from-peter?page= <int>
Here is my code
if($question){
$url = $_SERVER['REQUEST_URI'];
$dashed = $question->dashed_title;
$pattern = '/^\/questions\/[0-9]+\/'.$dashed.'(\/#[0-9]+)?$/i';
if (!preg_match($pattern, $url)){
// redirect_301 is a function that I wrote
redirect_301('http://'.$_SERVER['HTTP_HOST'].'/questions/'.$question->id.'/'.$dashed);
}
}
At the moment it works fine and will always redirect to the correct path. But it will not let me append
?page=<int>.
So i thought that the pattern should be
$pattern = '/^\/questions\/[0-9]+\/'.$dashed.'((\/#[0-9]+)|(?[\w\d&=]+))?$/i';
But this is resulting in a redirect loop and I cant work out why. Can you help?
Remove the ending $ from your original pattern, since that is the end of the string, so it won't match if there is a query string.

Rewrite Youtube URL

I have some YouTube URLs stored in a database that I need to rewrite.
They are stored in this format:
$http://youtu.be/IkZuQ-aTIs0
I need to have them re-written to look like this:
$http://youtube.com/v/IkZuQ-aTIs0
These values are stored as a variable $VideoType
I'm calling the variable like this:
$<?php if ($video['VideoType']){
$echo "<a rel=\"shadowbox;width=700;height=400;player=swf\" href=\"" . $video['VideoType'] . "\">View Video</a>";
$}?>
How do I rewrite them?
Thank you for the help.
You want to use the preg_replace function:
Something like:
$oldurl = 'youtu.be/blah';
$pattern = '/youtu.be/';
$replacement = 'youtube.com/v';
$newurl = preg_replace($pattern, $replacement, $string);
You can use a regular expression to do this for you. If you have ONLY youtube URLs stored in your database, then it would be sufficient to take the part after the last slash 'IkZuQaTIs0' and place it in the src attribute after 'http://www.youtube.com/'.
For this simple solution, do something like this:
<?php
if ($video['VideoType']) {
$last_slash_position = strrpos($video['VideoType'], "/");
$youtube_url_code = substr($video['VideoType'], $last_slash_position);
echo "<a rel=\"shadowbox;width=700;height=400;player=swf\"
href=\"http://www.youtube.com/".$youtube_url_code."\">
View Video</a>";
}
?>
I cannot test it at the moment, maybe you can try to experiment with the position of the last slash occurence etc. You can also have a look at the function definitions:
http://www.php.net/manual/en/function.substr.php
http://www.php.net/manual/en/function.strrpos.php
However, be aware of the performance. Build a script which prases your database and converts every URL or stores a short and a long URL in each entry. Because regular expressions in the view are never a good idea.
UPDATE: it would be even better to store ONLY the youtube video identifier / url code in the database for every entry, so in the example's case it would be IkZuQ-aTIs0.

PHP Remove Domain Name Extension from String

I was wondering of the best way of removing certain things from a domain using PHP.
For example:
"http://mydomain.com/" into "mydomain"
or
"http://mydomain.co.uk/" into "mydomain"
I'm looking for a quick function that will allow me to remove such things as:
"http://", "www.", ".com", ".co.uk", ".net", ".org", "/" etc
Thanks in advance :)
To get the host part of a URL use parse_url:
$host = parse_url($url, PHP_URL_HOST);
And for the rest see my answer to Remove domain extension.
Could you use string replace?
str_replace('http://', '');
This would strip out 'http://' from a string. All you would have to do first is get the current url of the page and pass it through any string replace you wanted to..
I would str_replace out the 'http://' and then explode the periods in the full domain name.
You can combine parse_url() and str_* functions, but you'll never have correct result if you need cut domain zone (.com, .net, etc.) from your result.
For example:
parse_url('http://mydomain.co.uk/', PHP_URL_HOST); // will return 'mydomain.co.uk'
You need use library that uses Public Suffix List for handle such situations. I recomend TLDExtract.
Here is a sample code:
$extract = new LayerShifter\TLDExtract\Extract();
$result = $extract->parse('mydomain.co.uk');
$result->getHostname(); // will return 'mydomain'
$result->getSuffix(); // will return 'co.uk'
$result->getFullHost(); // will return 'mydomain.co.uk'
$result->getRegistrableDomain(); // will return 'mydomain.co.uk'

Categories