PHP - .htaccess and GET parameters - php

I am trying to create a simple redirect to another page on login script.
Currently I am rewriting my URLS to the following format using .htaccess:
RewriteRule ^login$ ?i=l [L]
RewriteRule ^login([^/]*)$ ?i=l&=$1
The normal URL is therefore: domain.com/login - although I wish to be able to do the following: domain.com/login&redirect=/account/settings (Where the "redirect" will be the $_GET parameter that I'll be redirecting to after successful login)
My problem is if I access the above URL I get a 404 page not found. What am I doing wrong?

Try these rules:
RewriteRule ^login/?$ ?i=l [L,QSA]
RewriteRule ^login(&[^/]+)/?$ ?i=l$1 [L,NC]
Though I suggest using:
domain.com/login?redirect=/account/settings
and get rid of 2nd rule altogether.
QSA flag in first rule will add redirect=/account/settings query parameter as $_GET to your php file.

I use a .htaccess.
It's more functional and simple. I do not know if that's what you need but the handling is very simple.
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?param=$1 [L,NC]
Url Example :
domain.com/login/account/settings
The treatment is in the script PHP
$param = $_GET['param'];
echo $param;
Return
login/account/settings
Or then
$param = $_SERVER['REQUEST_URI'];
// (PHP 5 >= 5.2.0)
// $param = filter_input(INPUT_SERVER, 'RESQUEST_URI');
$param = explode('/',$param);
print_r($param);
Return
Array( [0]=> [1]=>login [2]=>account [3]=>settings)
With this method it is possible to accomplish several goals.

Related

How to handle dynamic routes in PHP?

I'm creating an API via PHP. I need to let users see a particular user. For example if someone goes to mysite.com/users/2, he must get the data about the user with id=2.
This is my .htaccess file:
RewriteEngine On
RewriteCond %{REQUEST_URI} !\.css$
RewriteRule ^([-/_a-zA-Z0-9\s]*)$ index.php?url=$1 [QSA,L]
The variable $url in index.php contains the whole url (for example users/2)
I use something like if($url == "users"){ //code } for routes, but what can I do with id that can be various?
Since you have everything in $url, you can just use explode()
Here's an example:
$url = "users/1234";
$url_array = explode("/", $url, 2);
echo $url_array[1];
This doesn't handle any errors, and as you stated in the comments, you'd need to implement those. So, unless this is a very small project it does seem safer, more maintanable, faster, etc. to use a framework like Laravel, or perhaps a micro-framework Lumen or Slim if you only need a few features.
You dont have to include the url in the RewriteRule:
# Redirect all requests to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
Then in your index.php:
$urlparts = explode("/", substr(#$_SERVER['PATH_INFO'], 1));
if($urlparts[0] == 'users'){
//find user with id $urlparts[1]
}

Secure url parameter

ok,Let me explain you step by step,Point is im new for this developments.
php files in my cproject directory :
allproducts.php
watch.php
in allproducts.php im displaying all the products available in the database. and every products has it own url. In my watch.php im displaying certain data according to a parameter comes from the allproducts.php page.
in my allproducts.php page i have this url :
http://localhost/cproject/watch?v=
url looks like something like this :
localhost/cproject/watch?v=J46TKlqSw3Gt4sk
at the moment i wrote a rewriterule for make watch.php in to "watch"
now what i want is to get rid of this "?" mark in to "/" and "v= " into "/"
so i want my rul to looks like this
localhost/cproject/watch/J46TKlqSw3Gt4sk
i hope now u do understand what i want to do actually ?
if i suddenly explain you what i have on my .htaccess file for this watch.php
i have this line of code
RewriteRule ^watch watch.php [NC,L]
You have to use .htaccess for doing url this.
.htaccess file code
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?/$1 [L]
For PHP version less than 5.2.6 try this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]
If you need to get the parameter from the url then use:
javascript
var str = "http://localhost/cproject/watch?v=J46TKlqSw3Gt4sk";
var param = str.split("=")[1];
alert(param);
Result
J46TKlqSw3Gt4sk
With the new url
var str = "http://localhost/cproject/J46TKlqSw3Gt4sk";
var param = str.split("/");
alert(param[param.length - 1]);
Result
J46TKlqSw3Gt4sk
For the .htaccess file you can use this RewriteRule which will forward the urls with just a / to the url with /watch?v=.
RewriteRule ^cproject/(.*) cproject/watch?v=$1 [NC]
For example:
Start URL http://localhost/cproject/eeeeeeeaf
End URL http://localhost/cproject/watch?v=eeeeeeeaf
But what i want is to get a url like i have mentioned above and get the parameter in a different page
You can do this with PHP from the /watch file by using the REQUEST_URI element in the $_SERVER[] array.
For the PHP code you could do:
<?php
$request = $_SERVER['REQUEST_URI'];
$exploded = explode("/", $request);
$id = $exploded[4];
echo $id;
?>
In regards to your additions to your question, it is easy to do as I have put above. Instead of what I have put, you can instead just use:
RewriteRule ^watch/(.*) watch.php?v=$1 [NC,L]
You can add this rule alongside your current rule (preferably after) and it should function as you require.
now what i want is to get rid of this "?" mark in to "/" and "v= " into "/" so i want my rul to looks like this localhost/cproject/watch/J46TKlqSw3Gt4sk
The URL RewriteRule I provided will do this :)
Have you actually tested the rewrites you have been provided with?

htaccess and php - redirects and pretty urls

I have a webcommunity, and it's growing now. I like to do a link makeover for my web, and then I need to know the best solution for my case.
Right now my htaccess looks kind of like this:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/\.]+)/?$ index.php?page=user&username=$1 [L]
You are able to link to users like this domain.com/username and that's nice.
Then I have different pages like
index.php?page=forum&id=1
index.php?page=someotherpage&id=1&anotherid=5
index.php?page=3rd
... and so on. I want them to look something like this:
domain.com/forum/23/title-of-the-thread
domain.com/page2/id1/id2
... and so on.
How do I make these pretty urls without removing my domain.com/username functionality? What solution would you suggest?
I was thinking about creating a file that checks the URL, if it matches any pages, and users and so on. Then it will redirect with a header location.
If all of the urls you are going to rewrite are going to the same end point, you could simply use:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]
in index.php:
<?php
$url = $_SERVER['REQUEST_URI'];
How you use the request uri is up to you, you could for example use a simple strpos check:
<?php
$url = $_SERVER['REQUEST_URI'];
$rules = array(
'/forum/' => 'forum',
'/foo/' => 'foo',
'/' => 'username'
);
foreach($rules as $pattern => $action) {
if (strpos($url, $pattern) === 0) {
// use action
$file = "app/$action.php";
require $file;
exit;
}
}
// error handling - 404 no route found
I was thinking about creating a file that checks the URL,
you actually have that file, it's index.php
if it matches any pages, and users and so on. Then it will redirect with a header location.
that's wrong. HTTP redirect won't make your URLs look "pretty"
you have to include appropriate file, not redirect to.
Just change your rule to more general one
RewriteRule ^(.*)$ index.php [L,QSA]
You basically have two options.
Route all URLs to a central dispatcher (FrontController) and have that PHP script anaylze the URL and include the correct scripts
Note every possible route (url rewrite) you have in the .htaccess
I've always worked with option 1, as this allows greatest flexibility with lowest mod_rewrite overhead. Option 2 may look something like:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^forum/([^/]+)/([^/]+)/?$ index.php?page=forum&id=$1 [L]
RewriteRule ^otherpage/([^/]+)/([^/]+)/?$ index.php?page=someotherpage&id=$1&anotherid=$21 [L]
RewriteRule ^page/([^/]+)/?$ index.php?page=$1 [L]
# …
RewriteRule ^([^/\.]+)/?$ index.php?page=user&username=$1 [L]
you said
I was thinking about creating a file that checks the URL, if it
matches any pages, and users and so on. Then it will redirect with a
header location.
While "creating a file that checks the URL" sounds a lot like option 1, "redirect with a header location" is the worst you could do. That would result in
an extra HTTP roundtrip for the client, leading to slower page loads
the "pretty URL" won't stick, the browser will show the URL you've redirected to
losing link-juice (SEO)
This can be done entirely with htaccess or php
//First Parameer
RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ index.php?page=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ index.php?page=$1
//Second Parameter
RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)/([0-9]+)$ index.php?page=$1&username=$2
RewriteRule ^([a-zA-Z0-9_-]+)/([0-9]+)/$ index.php?page=$1&username=$2
read more about it here:
http://net.tutsplus.com/tutorials/other/using-htaccess-files-for-pretty-urls/
http://www.roscripts.com/Pretty_URLs_-_a_guide_to_URL_rewriting-168.html

php request vars in sef urls

I have a page (ie www.mysite.com/products.php?catid=5) in which I use the $_REQUEST[catid'] to get the category id and use it in a query. I switched to SEF urls and now the urls display like www.mysite.com/products/category/5
How can I use the new urls to retrieve the catid value?
The following lines were used in the .htaccess file for switching to SEF urls:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/index.php
RewriteCond %{REQUEST_URI} (/|\.php|\.html|\.htm|\.feed|\.pdf|\.raw|/[^.]*)$ [NC]
RewriteRule (.*) index.php
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
You need to rewrite the URL correspondingly using mod_rewrite for example.
RewriteRule ^(.*)$ index.php?url=$1 [NC,QSA]
This rule would rewrite the URL www.mysite.com/products/category/5 to www.mysite.com/index.php?url=products/category/5. From this point on you can parse the variable $_GET["url"] or refine the rewrite rule.
Since the htaccess takes effect before the PHP starts to build you can grab the current URL with the below code snippet and get the value of the element as follows using the literal example of
www.mysite.com/products/category/5
$currentURL = $_SERVER['REQUEST_URI'];
$elements = explode("/",$currentURL);
$id_variable = $elements[3];
if you include the http:// in the url, then the element count should be 5 I believe
OR ... if you know that the id will always be the last element
$id_variable = $elements[(count($elements)-1)];
that will grab the last element in the array;
you can always use the following to show the data temporarily
echo "<div style='background-color:#FFF;'>";
echo ("Elements array:<br>\n");
print_r($elements);
echo "</div>";
hope this helps

$_GET URL from ?url=http://google.com

I'm making a redirect script for my site, I use htaccess to rewrite the URL so it looks nicer.
eg. http://localhost/r/http://google.com is the URL, but when I printing the value it shows up like this http:/google.com.
One / is missing, how can I fix that?
Edit:
Rewrite rule:
RewriteRule ^r/(.*)/$ /system/offsite/redirect/index.php?url=$1 [L]
Thanks for any help :)
This behavior is due to Apache that removes empty path segments before mapping it. But you can access the original requested URI path via THE_REQUEST:
RewriteCond %{THE_REQUEST} ^GET\ /r/([^\ ]+)
RewriteRule ^r/ /system/offsite/redirect/index.php?url=%1 [L]
Use php urlencode function
EDIT:
//echo your url
echo 'http://localhost/r/'. urlencode('http://google.com');
and in your index.php file
//get your url
$url = urldecode($GET['url']);
I think REQUEST_URI variable will have correct text. Use it like this:
Options +FollowSymlinks -MultiViews
RewriteEngine on
RewriteCond %{REQUEST_URI} ^/r/(.*)$
RewriteRule ^r/ /system/offsite/redirect/index.php?url=%1 [L,QSA,NC]

Categories