PHP Obtain the URL as a variable - php

I have noticed that many websites use urls that end in
website.com/index.php?var="value"&var2="value2"
and I was wondering how I could make it so that instead of having that be the end of the URL have this instead:
website.com/value/value2
and then have it so that instead of searching for "/value/value2" inside of the servers root folder it would instead just open index.php and then inside the PHP coding have a function that would get what the URL is. Either as a string "/value/value2" or an array "value" "value2" it doesn't matter but just some way of getting those variables. This would be so that the URL could be cleaned up and easy to tell where you were in the website.
Also if there is a way of doing this would it be possible for style.php that is in the same folder as index.php (but has a PHP header setting it to output CSS) that would be called in the head of index.php using <link rel="stylesheet" type="text/css" url="style.php" /> or whatever the syntax for that is, to be able to obtain that same variable so that the css styling could be changed according to the URL.

You can use rewriting of urls in .htaccess file
Check this.
RewriteEngine on
RewriteRule ^([^/]+)/([^/]+)/([^/]+) /?var=$1&var2=$2 [L]
There are three parts to this:
RewriteRule specifies that this is a rule for rewriting (as opposed to a condition or some other directive). The command is to rewrite part 2 into part 3.
This part is a regex, and the rule will be run only if the URL matches this regex. In this case, it says - look for the beginning of the string, then a bunch of non-slash characters, then a slash, then another bunch of non-slash characters. then again bunch of non-slash characters, then a slash, then another bunch of non-slash characters. The parentheses mean the parts within the parentheses will be stored for future reference.
Finally, this part says to rewrite the given URL in this format. $1 and $2 refer to the parts that were captured and stored.
Refer Beginner's Guide to mod_rewrite.
Also tutorial for same.

You need to re write the URL.. if u are using apache you would have to add changes in the .htaccess file. Check this and this manual.

If using apache, enable mod_rewrite and use .htaccess
RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ /index.php [L]
If using nginx, use nginx_rewrite_module http://nginx.org/ru/docs/http/ngx_http_rewrite_module.html
And inside your index.php parse $_SERVER['REQUEST_URI'] variable, it will contain requested url.

This can be achieved easily. Everything after the question mark are called $_GET variables. So you can call $_GET['var'] or $_GET['var2'] to get their values.
For example. I have the URL: http://www.example.com?username=username&password=password
Now i can take that url and make it so:
<?php
$user = $_GET['username'];
$pass = $_GET['password'];
$newUrl = 'http://www.example.com/' . $user . '/' . $pass;
echo 'Link text here';
?>
This results in a formatted url based on $_GET variables: http://www.example.com/username/password

Related

.htaccess Php rewrite url

I try to realize a system of rewriting URLs in .htaccess.
Then here is my goal:
If I have an url of this form: http://localhost/view.php?Id=456
Then I want to transform it to: http://localhost/456
I use this rule in htaccess:
RewriteRule ^ ([a-zA-Z0-9] +) $ view.php? Id = $ 1
Now this works very well!
But my problem I want to add points to id ie instead of 456 I can put: my.book
That is to say: http://localhost/my.book
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([a-zA-Z0-9\.]+)$ view.php?id=$1 [QSA,L]
You need RewriteCond %{REQUEST_FILENAME} !-f before the RewriteRule line to tell the server that the RewriteRule written below to be executed if the input passed in the URL is not an actual file. Because server searches for a file matching the input you pass in the URL and also it won't work in case you pass my.book in the URL since web server recognizes . as prefix for extension like .php or .html or like so and thereby it results in Not Found error if there is no file named my.book exists. So, you also need to escape . in the URL.
To allow .'s in the input, you need to add . with escape sequence \ in the character class group like ^([a-zA-Z0-9\.]+)$. Note, allowing this can result in escaping the extension in the URL, that is, passing view.php in the URL won't navigate to the actual file. Rather, it will be considered as a value in the query string.
Try this:
RewriteRule ^([a-zA-Z0-9\.]+)$ view.php?Id=$1
Basically what I did is I added \. with your pattern. This will make sure your regex matches any letter (small/caps), decimal numbers and periods (.). Hope this helps :)

Problems with special characters in url

I am working on a client project and I am trying to improve the process of passing variables from a url to php. The url structure of the project looks like the following:
http://xyz.com -> Domain
http://xyz.com/folder -> Folder/File
http://xyz.com/doesnotexist -> Folder/File does not exist
-> Pass it as a parameter to index.php Script
htaccess Rules take this parameter "doesnotexist" and make it available in a $_GET variable in index.php.
The variable gets encoded in javascript with encodeURIComponent, the url can be called in a browser and decoded in php with urldecode. This works perfectly.
Now to my problem: When the passed variable contains special chars like a slash "/" or an ampersand "&" it does not work anymore, because the browser thinks he is searching for a subdirectory. e.g. variable: "does/notexist" -> Browser tries to open http://xyz.com/does/notexist. At the moment I'm replacing such characters like a slash with others that are no problems in a url before encoding. So I replace "/" with "," or "&" with ";", encode it and everything is fine. In my php script I decode it and replace "," with "/" and ";" with "&" and so one. This works, but is really ugly, so I am searching for a better way to do it.
The initial url structure can not be changed. Does anyone know a better way to do this? I'm stuck here. One idea would be to base_encode the whole url parameter, but this is not the way I want it, because the url should be readable.
Thid is a typical situation where you would use a .htaccess file.
\Use mod_rewrite.
from here: howto mod_rewrite every request to index.php except real files but exclude one real directory?
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

URL encode in htaccess, maybe?

Consider the following scenario:
I want to be able to access http://www.example.com/word/hello/, where the word hello is variable. So I set up .htaccess to configure that.
RewriteEngine On
RewriteRule ^word/(.+)/?$ displayword.php?word=$1 [L]
I used .+ because I also want to filter any symbols such as ?+-.!;: etc.
And I set up my PHP file accordingly:
<?php
echo $_GET['word'];
?>
Remember that this is just a scenario. Now, I went to this URL: http://www.example.com/word/Are you ok?/, and the page outputted this:
Are you ok
And I couldn't figure out why. But then I realised that the question mark symbol is the starting point of the URL variables.
So is there a way to 'url encode' the question mark in the above example, in order for it to be displayed correctly?
There is no need to encode it, try this:
RewriteEngine On
RewriteRule ^word/([a-zA-Z0-9-=_.?]+)/?$ displayword.php?word=$1 [L]
It will display ? in the parameter and any other character you add to the [group]. I did not test if the rule works, though, but I suppose it does. Looks ok and that is not the question.
I don't know heaps about .htaccess files, but you could change your PHP script to use $_SERVER['PATH_INFO'] instead of $_GET or $_REQUEST.
Particularly, this comment might help you out.
In the HTTP protocol the "?" separates the querystring from the rest of the URL, so I don't think it will be possible to use it directly inside the URL. One solution would be to encode the question mark into %3F.
Then you can use string urldecode (string $str) to decode the string.
See this URL Encoding Reference for the encoding of other characters.
Change your code to this:
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+word/([^/]+) [NC]
RewriteRule ^ index.php?word=%1 [L,QSA]
Reason this works is because RewriteRule works on %{REQUEST_URI} which gets URI i.e. string before question mark ? however %{THE_REQUEST} works on the full URL that includes question mark ? as well.

Rewrite URL in PHP

I would like to rewrite the following URL
www.mysite.com/mypage.php?userid=ca49b6ff-9e90-446e-8a92-38804f3405e7&roleid=037a0e55-d10e-4302-951e-a7864f5e563e
to
www.mysite.com/mypage/userid/ca49b6ff-9e90-446e-8a92-38804f3405e7/roleid/037a0e55-d10e-4302-951e-a7864f5e563e
The problem here is that the php file can be anything. Do i have to specify rules for each page on the .htaccess file?
how can i do this using the rewrite engine in php?
To get the rewrite rule to work, you have to add this to your apache configs (in the virtualhost block):
RewriteEngine On
RewriteRule ^([^/]*)/userid/([^/]*)/roleid/(.*)$ /$1.php?userid=$2&roleid=$3 [L,NS]
RewriteRule basically accepts two arguments. The first one is a regex describing what it should match. Here it is looking for the user requesting a url like /<mypage>/<pid>/roleid/<rid>. The second argument is where it should actually go on your server to do the request (in this case, it is your php file that is doing the request). It refers back to the groups in the regex using $1, $2, and $3.
RewriteEngine on
RewriteBase /
RewriteRule ^mypage\/userid\/(([a-z0-9]).+)\/roleid\/(([a-z0-9]).+)$ www.mysite.com/mypage.php?userid=$1&roleid=$2
No you don't need a separate rule for every php file, you can make the filename variable in your regex something like this:
RewriteRule ^(a-z0-9)/userid/([a-z0-9].+)/roleid/([a-z0-9].+)$ $1.php?userid=$2&roleid=$3
If you want to rewrite the latter URL that is entered in the browser TO the first format, you would want to use a .htaccess file.
However, if you want to produce the pretty URLs in PHP (e.g. for use in link tags), then you have two options.
First, you could simply build the URL directly (instead of converting) which in my opinion is preferred.
Second, you could rewrite the first (ugly) URL to the pretty latter URL. You would then need to use preg_replace() in PHP. See http://php.net/manual/en/function.preg-replace.php for more info. Basically, you would want to use something like
$rewrittenurl = preg_replace("#mysite\.com\/mypage.php?userid=(([a-z0-9\-]).+)\&roleid=(([a-z0-9\-]).+)$", "mysite.com/userid/$1/roleid/$2", $firsturl);
Good luck!

How to use mod_rewrite with Zend Framework?

I've just deployed a new site using Zend Framework. Due to the popularity of my tutorials I'd like to redirect any request for a tutorial to the relevant page on the new site. So far this is what I've got:
URL before Rewrite: http://neranjara.org/tutorials/?tid=56
URL after Rewrite: http://neranjara.org/article/id/56
The .htaccess file I'm attempting to use looks like this:
$ cat html/.htaccess
RewriteEngine on
RewriteRule tutorials/\?tid=(.*)$ /article/id/$1 [R=301]
RewriteRule !\.(js|ico|gif|jpg|png|css|xml|phps)$ index.php
But this rule is not matching any URLs ... :'(
Does any one see a problem here?
Based on your previous entry:
$ cat html/.htaccess
RewriteEngine on
RewriteRule tutorials/\?tid=(.*)$ /article/id/$1 [R=301]
RewriteRule !\.(js|ico|gif|jpg|png|css|xml|phps)$ index.php
I'd suggest using this instead:
$ cat html/.htaccess
RewriteEngine on
RewriteCond %{QUERY_STRING} ^tid=([^&]*)
RewriteRule tutorials/ /article/id/%1 [R=301, L]
RewriteRule !\.(js|ico|gif|jpg|png|css|xml|phps)$ index.php [L]
BTW, this is just an example of the many things you could do using the QUERY_STRING variable in mod_rewrite. My vote goes to 'lpfavreau' since this is option #2 from their answer.
The query string (the parameters passed to your file) won't be in the RewriteRule.
Taken from http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#rewriterule:
The Pattern will not be matched
against the query string. Instead, you
must use a RewriteCond with the
%{QUERY_STRING} variable. You can,
however, create URLs in the
substitution string, containing a
query string part. Simply use a
question mark inside the substitution
string, to indicate that the following
text should be re-injected into the
query string. When you want to erase
an existing query string, end the
substitution string with just a
question mark. To combine a new query
string with an old one, use the [QSA]
flag.
You have two possibilities here:
Remove your first RewriteRule and do the verification in your index.php instead before continuing to your framework. The initial query should be available in $_SERVER['REQUEST_URI'] or something like that. So verify if it's tutorials, take the tid parameter and then go on with a redirection:
header("Location: http://http://neranjara.org/article/id/$id");
exit();
Use RewriteCond with %{QUERY_STRING} instead as stated in the Apache documentation. This solution is discussed in thread like this one.
// Edit:
Have a look at Chris' answer who was kind enough to detail the solution using QUERY_STRING. This is probably what you'll want to use. Thanks Chris.
Zend uses all the htaccess power that htaccess can deliver so theres a very handy(chainable and interesting and not very well documented) method to achive this in the bootstrap!
You must use the Zend Router in your bootstrap (index.php). Probably something like: (this would be foo.com/article/23
$router =
$frontController->getRouter();
$route = new
Zend_Controller_Router_Route(
'article/:id',
array('id' => 1) ); $router->addRoute('article', $route);
More info here

Categories