Create a rewrite rule in .htaccess for php file - php

I am very new to .htaccess, I am having some problem with file action.
Example:
http://www.domain.com/upload_pic.php?action=save_pic
I wrote the .htaccess rule like
RewriteEngine On
RewriteRule ^sabc([a-zA-Z0-9!##$-_]*)$ upload_pic.php?action=$1
I want the desired result like:
http://www.domain.com/sabc/save_pic
How can I get the desired result, please correct my .htaccess line.

Change it to:
RewriteEngine On
RewriteRule ^sabc/(.+)$ upload_pic.php?action=$1
The .+ will capture one or more characters after the / and be captured into $1

There are several other guides on the web already, but to understand it in better way as you are beginner #AMY, I have writen this for you. Hope this will work for you.
Most dynamic sites include variables in their URLs that tell the site what information to show the user. Typically, this gives URLs like the following, telling the relevant script on a site to load product number 7.
http://www.domain.com/upload_pic.php?pic_id=7
The problems with this kind of URL structure are that the URL is not at all memorable. It's difficult to read out over the phone (you'd be surprised how many people pass URLs this way). Search engines and users alike get no useful information about the content of a page from that URL. You can't tell from that URL that that page allows you to buy a Norwegian Blue Parrot (lovely plumage). It's a fairly standard URL - the sort you'd get by default from most CMSes. Compare that to this URL:
http://www.domain.com/sabc/7/
Clearly a much cleaner and shorter URL. It's much easier to remember, and vastly easier to read out. That said, it doesn't exactly tell anyone what it refers to. But we can do more:
http://www.domain.com/sabc/user-navnish/
Now we're getting somewhere. You can tell from the URL, even when it's taken out of context, what you're likely to find on that page. Search engines can split that URL into words (hyphens in URLs are treated as spaces by search engines, whereas underscores are not), and they can use that information to better determine the content of the page. It's an easy URL to remember and to pass to another person.
Unfortunately, the last URL cannot be easily understood by a server without some work on our part. When a request is made for that URL, the server needs to work out how to process that URL so that it knows what to send back to the user. URL rewriting is the technique used to "translate" a URL like the last one into something the server can understand.
To accomplish this, we need to first create a text document called ".htaccess" to contain our rules. It must be named exactly that (not ".htaccess.txt" or "rules.htaccess"). This would be placed in the root directory of the server (the same folder as "upload_pic.php" in our example). There may already be an .htaccess file there, in which case we should edit that rather than overwrite it.
RewriteEngine On # Turn on the rewriting engine
RewriteRule ^sabc/?$ upload_pic.php [NC,L] # Handle requests for "sabc"
A couple of quick items to note - everything following a hash symbol in an .htaccess file is ignored as a comment, and I'd recommend you use comments liberally; and the "RewriteEngine" line should only be used once per .htaccess file (please note that I've not included this line from here onwards in code example).
The "RewriteRule" line is where the magic happens. The line can be broken down into 5 parts:
RewriteRule - Tells Apache that this like refers to a single
RewriteRule.
^/sabc/?$ - The "pattern". The server will check the URL of every
request to the site to see if this pattern matches. If it does, then
Apache will swap the URL of the request for the "substitution"
section that follows.
upload_pic.php - The "substitution". If the pattern
above matches the request, Apache uses this URL instead of the
requested URL.
[NC,L] - "Flags", that tell Apache how to apply the rule. In this
case, we're using two flags. "NC", tells Apache that this rule should
be case-insensitive, and "L" tells Apache not to process any more
rules if this one is used.
# Handle requests for "sabc" - Comment explaining what the rule does (optional but recommended)
The rule above is a simple method for rewriting a single URL, and is the basis for almost all URL rewriting rules.
RewriteEngine On
RewriteRule ^sabc/(.+)$ upload_pic.php?action=$1
Hope this will be helpful for you to understand URL rewriting #AMY.

Related

GET request without needing the ? at the end

I am developing my login system a bit further to look a lot more professional, and I wanted to know how I could turn get requests into simple links so they look a lot more sleeker?
For example for one of my systems a user can search someones elses profile by going to http://www.example.com/user?user=JimmyJones
Thats all fine and dandy but I don't think it looks very good and many other websites don't have this in their links due to some kind of trick I don't know about, as you can see I have gotten rid of the .php at the end which is done using some very simple htaccess.
But how can I change that link above to:
http://www.example.com/user/JimmyJones
Thank you very much for taking your time to read this and I really hope someone can help me out with my little problem, I assume there is some way to do this in .htaccess?
EDIT:
Here are some websites that do it just about how I would like to do it:
imgur.com/user/example
facebook.com/exampleuser
you make .htaccess file in the root dictionary then start it with
RewriteEngine on
then write your rules, For your example it would be like this
RewriteRule ^/?user/([^/]+)/?$ user?user=$1 [L,QSA]
so a full page would be like this
RewriteEngine on
RewriteRule ^/?user/([^/]+)/?$ user.php?user=$1
just for your example.
In .htaccess assuming the Apache web server with the rewrite module enabled, something like this:
RewriteEngine On
RewriteRule ^user/([a-zA-Z]+)$ user.php?user=$1 [L]
The first line says use the rewrite engine.
The second, says match a url that begins (or rather is relative to the .htaccess containing folder) with the pattern 'user' followed by a slash and matching a pattern of any alphabetic characters until the end of the string (not including additional query parameters).
The L flag basically says job done.
If the .htaccess were in the public root:
//example.com/user/JimmieJones
would map to:
//example.com/user.php?user=JimmieJones
However it will not match:
//example.com/user
//example.com/user/
//example.com/user/JimmieJones/
//example.com/user/Freddy_K9
Note that any existing links in your application:
Visit Jimmie's Profile
Would likely need to be updated. And with the example pattern above, the old style urls (previously indexed/bookmarked) could fail without your existing rule. You may need to adapt the pattern or set up redirects for the old style.
Managing lots of redirects and rewrites can become a headache. I'd advice some attention to your url name spacing. And documenting them.
I reserve first level patterns for aliases/shortcuts/campaigns.
//example.com/slug
I'd avoid that for your user profile urls if possible.
You'll ideally want to aim for consistency and have one-one correspondence for URLs(with associated http method) and resources (canonical urls).

PHP Get method without?

Hey so im working on a website and one part of it allows you to lookup a user based on their name. At the moment i have it using a $_GET request so the link would look like:
http://website.com/p?name=John+Smith
How would i be able to remove that ?name= because i see alot of sites doing things like:
http://website.com/p/John+Smith
how would i achieve this because to my knowladge their arent any other forum request types only Post and Get?
URL rewriting is definitely what you're looking to do. It's well worth playing carefully with it but lots of testing is recommended. With great power comes great responsibility!
Most dynamic sites include variables in their URLs that tell the site what information to show the user. The example you provided is exactly like this.
Unfortunately, a cleaned up URL cannot be easily understood by a server without some work. When a request is made for the clean URL, the server needs to work out how to process it so that it knows what to send back to the user. URL rewriting is the technique used to "translate" a URL like the last one into something the server can understand.
To accomplish this, you need to first create a text document called ".htaccess" to contain the rules. This would be placed in the root directory of the server. To tell the server to rewrite a URL pattern, you need to add the following to the file:
RewriteEngine On # Turn on the rewriting engine
RewriteRule ^p/[A-Za-z\+]$ /p/?name=$1 [NC,L] # Rewriting rule here
The NC bit denotes case insensitive URLs and the L indicates this is the last rule that should be applied before attempting to access the final URL.
You can do quite a bit with this one rule, but the specifics extend far beyond the space of my answer here.
https://www.addedbytes.com/articles/for-beginners/url-rewriting-for-beginners/
I would highly suggest reading that thorough guide to help you on your quest!

Need some answer about example.php/example

I am doing on a project and i stumble upon on this while going through some code. I had tried to google but could not find a correct keyword to search regarding this question.
http://www.fruit.com/example.php/red
I am confuse with this and the end of a .php it still have a character /red for example.
What is the purpose of this? Does it have something to do with POST method?
A possible explanation is that the developer is using .htaccess rewrite rules. It is most likely extra data that has to do with the page (such as you mentioned, POST and GET) and it's only done this way to make the URL look prettier or to simplify the URL.
It is also sometimes done this way to make it easier to linkback to this page, especially if the page is being generated based on the data.
A popular place to do this would be blogs. You often see blogs display links as:
http://blog.com/blog/2001/02/23/how-pretty-is-this
when in reality, the request to the server is something like:
/blog.php?year=2001&month=02&day=23&title=how-pretty-is-this
which isn't that pretty and not as easy to link-back to this particular page.
Mr.Xenotype answered your question well but missed one little part.
Does it have something to do with POST method?
No, it deals with the GET method. As he stated, it's pretty much to make the URL look "pretty", and it could actually be a crucial part of a RESTful API (bit advanced for a beginner) if that's how the site was designed.
http://www.fruit.com/example.php/red
Is the same as
http://www.fruit.com/example.php?id=red
Some tinkering with the .htaccess file is required to accomplish this using what are called regular expressions, or REGEX. If you'd like to know more I'll gladly provide some examples.
Adding a "RewriteRule" to the .htaccess file (a server configuration file) can allow the server to change the way the server files/folders are accessed
//probably what the rewrite looks like of the example you provided
RewriteRule .* example.php/$0 [L]
RewriteRules are broken into 4 blocks: action, pattern, rewrite and flag
Action: RewriteRule, essentially just lets the server know we're going to be performing a rewrite
Pattern: .* is our pattern in this example. The "." stands for any character, meaning match any character, and the "*" tells it to repeat this. So, match any character after the rewrite.
The rewrite is the page to perform this on, so example.php is the rewrite. The "$" of this tells it where to start the rewrite. So, we'll start the rewrite at the "$" symbol, and use our pattern. Our pattern ".*" tells us to match any character, in this case, red.
The [L] means last rule. This is it, no more rules to follow. You can use multiple rewrite rules for multiple pages.
So now, instead of using example.php?id=red, the server now knows that starting after "example.php/" to match any characters we supply.

php based website that displays page content based on URL?

I would like to make a website that is php and only requires one php document to display the content. It's kinda hard to explain, so let me try my best.
Some websites use a directory based system such as this:
web.URL.com/index.htm
web.URL.com/about.htm
web.URL.com/blog.htm
and so on.
This involves creating a text file for each page.
So, the goal here is to create one page that acts like a frame, and displays content based on the Url, so it will be acting like the above method, but is only one page. I'm pretty sure you can do this, but don't know the proper way to word it or what vocabulary to use when typing it in to google.
Some questions you may have:
Q:Why not use parameters like this:
web.url.com?pgid=some+page
A: I would like the url to be as clean as possible when it comes to the visitor typing the url. For example, this is much easier to remember:
web.url.com/about
than this:
web.url.com?p=about
Q: Wordpress??
A: We want our own stuff. Wordpress is great, but not for our project.
Q: JQuery?
A: PHP please.
Thank you in advance!
With PHP alone, I don't think it's possible. However, it's likely that your webserver is running Apache, which makes this task fairly straightforward by transforming your pretty URLs into ugly URLs (with query strings) that your PHP script can handle. Your visitors have no idea this is happening; they aren't redirected or anything.
I strongly recommend you take a look at this tutorial, and its followup. The second tutorial contains the information you need for this task (starting in this section), but I strongly recommend reading the first tutorial to gain a deeper understanding of what you're doing.
Essentially, those tutorials will teach you how to specify (ugly, scary-looking) URL-rewriting rules in a file called .htaccess. These rules will transform (or "rewrite") your pretty URLs into less pretty ones that your PHP script can handle.
For example, yoursite.com/about would actually be accessing yoursite.com/index.php?page=about, or something along those lines.
For some sample code, here's a snippet 95% copied and pasted from this tutorial:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?page=$1 [L,QSA]
As that link explains, it will forward all requests to index.php, unless an actual file or directory is being requested.
Use a RewriteRule based .htaccess. Then you can have all non-existing files redirected (internally in Apache) to a general index.php with the requested path as a query string ?p=about. The redirecting is handled internally, so http://example.com/about is the external URL to that page.
You can have a switch statement checking $_GET values and output the page based on the provided parameter. Also, you will have to add some mod_rewrite rules to route those requests.
Use PHP URL rewrite. PHP will enteprate part of your URL as query string

How To Make PHP Application To Use Actual URL's If Mod-Rewrite Is Disabled?

I am working on a PHP Application, Every thing works perfectly, The only problem is.
I have enabled SEO Friendly URL's, Which re-writes the actual URL's to virtual URL's( i know you guys know it )
Ex : hxxp://www.website.com/index.php?page=about-us
To
hxxp://www.website.com/page/about-us/
What i want to achieve is If the SEO URL's / Mod Rewrite is disabled, the user should be able to access the direct/actual URL's.
In brief, If Mod-Rewrite is enabled, the web application should automatically use the SEO Friendly URL's otherwise go with the default URL's.
You would have to replace all occurrences of links with a function that checks if mod_rewrite is available, or more likely, a config value. It would then return the appropriate link.
getLink("?page=about-us")
Use an <IfModule> to avoid breaking other .htaccess directives and or 500 internal server errors if Apache doesn't understand your rules. Also add a single non-rewriting rewriterule (before all others);
<IfModule mod_rewrite.c>
RewriteEngine On
#The next rule does no rewriting, but sets en environmental variable.
RewriteRule .* - [E=RewriteCapable:On]
</IfModule>
In your file (store as setting or check on places generating/outputting urls):
if(isset($_SERVER['RewriteCapable'])){
//make fancy urls
} else {
//cludgy old-style urls
}
Hmm.. this may need thought about a bit to get the correct solution.. follow me here if you will :)
SEO URLs were primarily introduced to (1) include human readable text in the URLs and (2) to get rid of the GET parameters.
To look at point (2) for a moment, this was the primary driver initially, because people used about.php?id=1, id=2 ... id=3457348 to get the same page listed in the search engines multiple times, which of course got detected and stopped, then sometimes people would pass a session id=24234234 which would also get stopped as being a duplicate page (rightfully as it uses HTTP as a stateful protocol when it's not).
With an URL, everything from the first char up to a the # of a #fragment defines a resource (from an HTTP perspective), so rightly so when several different URLs all resolve to the same 'page' they are indeed duplicates.
So, by negating the GET parameters you solve this problem, which now isn't a problem by the way and hasn't been for a long time, there's no reason not to use GET params properly other than vanity.
So, really you solve no problem but have instead introduced a new problem, in that you want '/page/about-us' and '?page=about-us' to both go to the same 'page' which means you've got duplicate resources again and this could be detected and you could get penalised.
Thus, by introducing 'SEO URLs' you've actually created the problem SEO URLs were 'invented' to counteract.
This only leaves the point about human readable words in the URL. URLs are supposed to be transparent so they don't count for anything in reality, but some still like - so I'd have to ask what's wrong with using '/?/page/about-us'... and if you don't like that then whats wrong with creating a fixed file with the filesystem path '/page/about-us' which simply includes your index.php with the right variables set?
Of course you can create duplicate pages and have both SEO friendly urls and GET param URLs but as you can see that won't be SEO friendly now will it?
Something to chew on :)

Categories