Rewrite URL using PHP with a generated key - php

I want to rewrite my URL with an generated key.
So...
My base URL -> www.example.com
My problematic URL -> www.example.com/actions.php
And the final URL I want to be like www.example.com/41f1341df14r12
The problem is that i want to generate each page based on a key (41f1341df14r12) from my database (MYSQL).
P.S. I want to use PHP for that.
Thanks!
UPDATE:
Sorry for confusing. My English is not so well.
So... what i want:
In index.php I have a <input type="text">. When the user press the submit button my PHP generates a key (41f1341df14r12) and store both (key and input text) in database. I want when user press the submit to go to a page with URL like
www.example.com/41f1341df14r12
and on that page to see his message.
I hope to understand now :D

First your apache need mod_rewrite Url. Then you can use this code in your .htaccess to redirect the key to a php file that can process the key.
RewriteEngine On
# Rewrite only if its not a file
RewriteCond %{REQUEST_FILENAME} !-f
# and if its not a directory
RewriteCond %{REQUEST_FILENAME} !-d
# rewrite the request to action.php
RewriteRule .* action.php [L]
In the PHP Script you can read from the super global variable $_SERVER['REQUEST_URI'].
<?php
echo substr($_SERVER['REQUEST_URI'], 1); //remove the first /
Alternative you could redirect the key to a GET variable:
RewriteRule (.*) action.php?key=$1 [L]

One way to accomplish this is using URL rewriting. This is when the web server opens a certain (PHP) file if an address matches one of the set rules.
The process is different for every web server, I'm assuming you are using apache.
You will need to create an .htaccess file in the root of your web server and add the following lines:
RewriteEngine On
RewriteRule ^([a-z0-9]+)/?$ handler.php?key=$1 [L]
The first line enables URL rewriting. The second creates a rule that says: "If the requested URL matches the format 'example.com/key/', open the file 'handler.php' and pass it the key."
In your PHP file (handler.php in this example), you can access your key with $_GET['key'] and use it to generate the page.
For more information see this tutorial.
Notes:
You may need to restart the web server after creating the .htaccess
file.
This will not match uppercase letters, use ^([A-Za-z0-9]+)/?$ instead.
If you are not using shared hosting, you may need to enable mod_rewrite in the apache httpd.conf (see tutorial).

Related

Get page id value and display in URL via .htaccess

I'm trying to display SEO friendly URLs by using a rewrite in our .htaccess file, but I can't get it to work (I've researched many of the related topics on StackExhange and elsewhere, but to no avail). I'd like to get the value of the id on this page...
http://199.119.123.135/info/tool_surety_company.php?id=1
...and display the id value in the URL instead of the ugly "tool_surety_company.php?id=1".
I'm going for a result like this: http://199.119.123.135/info/travelers-group
I'm using the following code in my .htaccess file:
RewriteCond %{THE_REQUEST} \ /+info/tool_surety_company\.php\?id=([^&]+)
RewriteRule ^ /info/%1/? [L,R]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^^info/([^/]+)/?$ /info/tool_surety_company.php?id=$1 [QSA]
But I'm receiving a 404 error.
Any ideas? Thanks in advance!
There might be something I'm misunderstanding here but I believe there would need to be a mechanism on the server side code to load the correct content for the new "seo-friendly url". In other words, sure, you can redirect the user to show a different url but how is the server going to know what content to load for that new url?
Here's a good resource for putting together a simple example.
https://moz.com/ugc/using-mod-rewrite-to-convert-dynamic-urls-to-seo-friendly-urls
Update:
From here - https://mediatemple.net/community/products/dv/204643270/using-htaccess-rewrite-rules
TROUBLESHOOTING
404 Not Found
Examine the new URL in your browser closely. Does it match a file that
exists on the server in the new location specified by the rewrite
rule? You may have to make your rewrite rule more broad (you may be
able to remove the $1 from the second string). This will direct
rewrites to the main index page given in the second string. Or, you
may need to copy files from your old location to the new location.
In other words, the only reason you would be getting a 404 is because the server does not find the file that is requested as defined in the URL visible in your browser address bar.
Htaccess Rewrites are enabled by using the Apache module mod_rewrite,
which is one of the most powerful Apache modules and features
availale. Htaccess Rewrites through mod_rewrite provide the special
ability to Rewrite requests internally as well as Redirect request
externally.
When the url in your browser's location bar stays the same for a
request it is an internal rewrite, when the url changes an external
redirection is taking place. This is one of the first, and one of the
biggest mental-blocks people have when learning about mod_rewrite.
More info from here:
http://www.askapache.com/htaccess/modrewrite-tips-tricks.html

Path formatting for underscore or non-alphanumerics in URL for YII

I have paths like follwing
http://locahost.com/wayinfra/site/wayinfracms?view=about_us
http://locahost.com/wayinfra/site/project?view=justa_hotels
I want to use the urls as
http://locahost.com/wayinfra/about_us
http://locahost.com/wayinfra/project/justa_hotels
Added requirements - When i am using in url manager 'project/<view:\w+>'=>'site/project/' the url locahost.com/wayinfra/project/justa display perfect but locahost.com/wayinfra/project/justa_hotels generate error unable to find the request.
how i can do this?
Read the following document:
Yii's URL Management
Source - http://www.yiiframework.com/doc/guide/1.1/en/topics.url
You first need to configure the Web server so that a URL without the entry script can still be handled by the entry script. For Apache HTTP server, this can be done by turning on the URL rewriting engine and specifying some rewriting rules. We can create the file /wwwroot/blog/.htaccess with the following content. Note that the same content can also be put in the Apache configuration file within the Directory element for /wwwroot/blog.
RewriteEngine on
# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# otherwise forward it to index.php
RewriteRule . index.php
Then configure the 'showScriptName'=>false in the urlManager array.
Use code below for alphanumerics and underscore in the parameter as required.
`'project/<view:[a-zA-Z0-9_]+>'=>'site/project/'`

How to have a PHP file be used for multiple URLs

I want to have a single PHP file that takes care of multiple URLs in a subdirectory.
For example, my site is http://www.startingtofeelit.com/. I want one php file, say, called playlist.php which would handle when a user goes to http://www.startingtofeelit.com/playlist/101 or if they go to http://www.startingtofeelit.com/playlist/142 etc. I want to be able to strip the number (101, 142 in my example urls above) to use as a variable (the playlist ID), so I can display the correct playlist.
I know that I can create an index.php in my playlist subdirectory and use GET variables like http://www.startingtofeelit.com/playlist?id=102 and get the ID that way, but this is much sloppier looking and I'd like to be able to know how to do it the other way.
My site is built on WordPress, but I don't think this should make a difference in any way.
Well, you cannot achieve this with PHP alone.
If you use Apache, you can use .htaccess
If you use IIS, you can use URL Rewrite
The basic idea behind those modules is to mapping from one URL to another URL. For example: you would want to map from
http://www.startingtofeelit.com/playlist/142 =>
http://www.startingtofeelit.com/playlist.php?id=142
You can express the URL mapping in regular expression. For example, in .htaccess (Apache). You can write like this
RewriteRule ^playlist/([0-9]+)/?$ playlist.php?id=$1
Noted that, you need to have .htaccess file in your website directory. Since, you are using Wordpress, chance that you have existed .htaccess is high. You can simply append that line of code to existed .htaccess
The following is an explanation of the regular expression:
^playlist/ # any URL start with playlist/
([0+9]+) # following by number, and store it as $1
/?$ # end with or without /
Mapping to
playlist.php?id=$1 # where $1 is taken from the matched number from our pattern.
This is usually handled in a way similar to what you already tried. However, it's common to use a re-writing script so that your application will accept a clean URL such as:
http://www.startingtofeelit.com/playlist/142
...and re-write it for your application as such:
http://www.startingtofeelit.com/playlist?id=142
For example, if you're using an Apache web server and have the mod_rewrite module installed and enabled, you can use the following snippet in an .htaccess file and use your GET parameter as you indicated you already know how to do. Other popular web servers have unique URL re-writing modules that will let you do the same.
<IfModule mod_rewrite.c>
RewriteEngine On
# Rewrite this:
# http://www.example.com/somepage/1
# ...into this:
# http://www.example.com/somepage?id=1
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

Redirect based on url arguments (via PHP or cPanel)

I just started using Amazon S3 to host static files (images, videos, etc.).
For accessing the uploaded files, temporary links are created.
A temporary link looks like this one:
http://zeebit.s3.amazonaws.com/stackoverflow-logo.png?AWSAccessKeyId=AKIAIXEHEYSBDWAAXVVA&Expires=1346888760&Signature=B%2BS%2FlUoRXno3UfSqf9Ua0RuCcBc%3D
What I want is to serve these file through my url, something like this:
http://s3.mydomain.com/zeebit/stackoverflow-logo.png/AKIAIXEHEYSBDWAAXVVA/B%2BS%2FlUoRXno3UfSqf9Ua0RuCcBc%3D
I know I can redirect requests to http://s3.mydomain.com to the Amazon url via PHP (for example), but I don't want the address bar to change.
I can create a .htaccess to transform the url to the Amazon url, but as I know .htaccess can't redirect to external resources.
So, how can I solve this?
There are a couple of solutions:
.htaccess Solution #1 - Rewrite Rule
RewriteEngine On
RewriteCond %{HTTP_HOST} ^s3\. # Hostname starts with "s3."
RewriteCond %{REQUEST_URI} !-f # Not a file
RewriteCond %{REQUEST_URI} !-d # Not a directory
RewriteRule ^/(.+)/(.+)/(.+)/(.+)/(.+)$ http://$1.s3.amazonaws.com/$2?AWSAccessKeyId=$3&Expires=$5&Signature=$4 [R=302,L]
NOTE: Your initial desired URL was missing the "Expires" value, so the above would work for URLs formed like so:
http://s3.yourdomain.com/[[S3_Bucket_Name]]/[[S3_Filename]]/[[AWSAccessKeyId]]/[[Signature]]/[[Expires]]
So:
http://s3.mydomain.com/zeebit/stackoverflow-logo.png/AKIAIXEHEYSBDWAAXVVA/B%2BS%2FlUoRXno3UfSqf9Ua0RuCcBc%3D/1346888760
would redirect to
http://zeebit.s3.amazonaws.com/stackoverflow-logo.png?AWSAccessKeyId=AKIAIXEHEYSBDWAAXVVA&Expires=B%2BS%2FlUoRXno3UfSqf9Ua0RuCcBc%3D&Signature=1346888760
.htaccess Solution #2 - Redirect
Whilst being a less flexible solution than the above, you could put the following into your .htaccess file
redirect 302 /s3/ http://zeebit.s3.mydomain.com/
Using this rule, requests for
http://yourdomain.com/s3/stackoverflow-logo.png?AWSAccessKeyId=AKIAIXEHEYSBDWAAXVVA&Expires=B%2BS%2FlUoRXno3UfSqf9Ua0RuCcBc%3D&Signature=1346888760
Would basically retain everything after /s3/ and simply replace everything preceeding it with the Amazon S3 location.
http://zeebit.s3.amazonaws.com/stackoverflow-logo.png?AWSAccessKeyId=AKIAIXEHEYSBDWAAXVVA&Expires=B%2BS%2FlUoRXno3UfSqf9Ua0RuCcBc%3D&Signature=1346888760

How to understand PHP's URL parsing/routing?

I just inherited a website built in PHP. The main page of www.mysite.com has a href to www.mysite.com/index/35.html somewhere in the page. In the site's root directory and its children there is no document 35.html.
The number 35 is actually an id found in a DB which also holds the html contents of the page.
If I load URL: www.mysite.com/index.php?id=35 the same page loads.
How does PHP know how to automatically convert
/index/35.html
to
/index.php?id=35
EDIT
Based on the answers, I have found a .htaccess file containing rewrite instructions that would explain the functionality.
However, IIS doesn't seem to (or is not configured) know how to use this. (probably because this is an Apache feature?)
So this begs the following question: Is there a way to configure IIS to work with this?
it will be done usign URL Rewriting using .htaccess - should be in the webroot.
It may look something like:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
May have other bits, but what this basically tells apache is to send anything that DOES NOT physically exist to index.php
It doesn't. There is a mod_rewrite rule that rewrites from /index/foo to /index.php?id=foo, either in a .htaccess file somewhere or in the httpd configuration itself.
RewriteEngine On
RewriteRule ^index/([\d]+)\.html /index.php?id=$1 [NC,L]
This is off the top of my head. Any browsers trying to load an address starting with index/ has any number ending in .html will be internally redirected to index.php?id= whatever the number is.
Edit: Just saw that your working on IIS. This probably won't work for you. Sorry.
I think you will be using .htaccess to redirect all requests to index.php. From there You can pass the query string a routing class, which will parse the url and identify the unique ids.
In this case we can say like, your routing class will parse the request /index/35.html to indexController, indexAction, id=35. now you can pass this id to the model to get corresponding page contents
NB : Here I a am assuming you are using mvc pattern. Anyway it can be treated in your own way, with the concept remaining the same. Hope this make sence.

Categories