htaccess get code and redirect with php - php

Ex:
If we entered these url (Like This site)
http://stackoverflow.com/questions/10139779/ or http://stackoverflow.com/questions/10139779
Its automatically redirect to this url http://stackoverflow.com/questions/10139779/handling-get-with-htaccess
I want to get this code (10139779) from url and redirect to full url. Someone go to full url how to get this code (10139779)
Edit :
I created htaccess file like this.
<Files .htaccess>
order allow,deny
</Files>
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^(\w+)$ ./load.php?code=$1
Now i want to give video title to url after video id Like this www.example.com/16056/video-title
load.php
<?php
echo $_GET['code'];
//I can get video title from php then how to give to url it?
?>
I can get code this from www.example.com/16566 but i can't get code this from this url www.example.com/16566/video-title
after id / link was doesnt work. how to fixed it

This answer is an additional update of #bjb568's answer, which handles exceptions.
<?php
if(isset($_GET['code'])) {
$code = (int)$_GET['code'];
$url = '/videos/' . $code . '/' .getTheVideoTitle($code);
} else {
$url = '404_page_not_found.php'; // or redirect visitors to homepage
}
header("Location: $url");
exit;
?>
Also, this prevents someone intentionally "hack" the link by entering strings with escape character & crash the code. (Of course, it's developer's duty to validate the input in the getTheVideoTitle() function)

Send out a location header for the correct URL. (load.php:)
<?php
header('Location: /videos/'.$_GET['code'].'/'.getTheVideoTitle($_GET['code']));
?>
There is nothing you can do in .htaccess to get the video title, so php must do it.
Also, for .htaccess:
RewriteRule ^(\w+)$ ./load.php?code=$1
Should be:
RewriteRule ^(\w+)/*$ ./load.php?code=$1
This makes it match slash(s) after the URL. If you also want it to match the title after the URL, make it:
RewriteRule ^(\w+) ./load.php?code=$1

Related

using $_GET without using '?'

I want to create a link which is catched by $_GET in PHP. Let me explain:
Currently i do this in HTML:
Contact Us
And this is what i do in php:
<?php
if (isset($_GET['contactus'])){
include "contactus.php";
}
?>
In this case the address becomes like this www.domain.com/?contactus.
But I want the address like this: www.domain.com/contactus
If i change html to Contact Us
but it doesn't work. Anyone please tell me. Thanks
you need a .htaccess file to make it work
like this:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^contactus\/?/?$ index.php?contactus
</IfModule>
and index.php like this
<?php
if (isset($_GET['contactus'])){
include "contactus.php";
}
?>
You can use domain.com/contactus and parse the URL
$url = "http://domain.com/contactus";
$url = parse_url($url);
$path = $url['path']; // contactus
echo $path; // contactus
You can then use it
if ($path == "contactus"){
include "contactus.php";
}
You will still need URL rewrite, try adding or editing your .htaccess file
RewriteEngine On # Turn on the rewriting engine
RewriteRule ^contactus/?$ contactus-page.php [NC,L] # Handle requests for "contactus"
hi you need to do like this
at page where u set anchor tag do following
$url="contact.php?page"='contactus';
give href="$url" .
And other side you can use $urlget = $_GET['page'];
plz note the attribute u used is page so when u try to get in nother page u need to use $_GET['page'] and you can see url when you click on contact us page in your address bar there is also contact.php?page='contactus' showing

Implementing friendly links into custom CMS [duplicate]

Normally, the practice or very old way of displaying some profile page is like this:
www.domain.com/profile.php?u=12345
where u=12345 is the user id.
In recent years, I found some website with very nice urls like:
www.domain.com/profile/12345
How do I do this in PHP?
Just as a wild guess, is it something to do with the .htaccess file? Can you give me more tips or some sample code on how to write the .htaccess file?
According to this article, you want a mod_rewrite (placed in an .htaccess file) rule that looks something like this:
RewriteEngine on
RewriteRule ^/news/([0-9]+)\.html /news.php?news_id=$1
And this maps requests from
/news.php?news_id=63
to
/news/63.html
Another possibility is doing it with forcetype, which forces anything down a particular path to use php to eval the content. So, in your .htaccess file, put the following:
<Files news>
ForceType application/x-httpd-php
</Files>
And then the index.php can take action based on the $_SERVER['PATH_INFO'] variable:
<?php
echo $_SERVER['PATH_INFO'];
// outputs '/63.html'
?>
I recently used the following in an application that is working well for my needs.
.htaccess
<IfModule mod_rewrite.c>
# enable rewrite engine
RewriteEngine On
# if requested url does not exist pass it as path info to index.php
RewriteRule ^$ index.php?/ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php?/$1 [QSA,L]
</IfModule>
index.php
foreach (explode ("/", $_SERVER['REQUEST_URI']) as $part)
{
// Figure out what you want to do with the URL parts.
}
I try to explain this problem step by step in following example.
0) Question
I try to ask you like this :
i want to open page like facebook profile www.facebook.com/kaila.piyush
it get id from url and parse it to profile.php file and return featch data from database and show user to his profile
normally when we develope any website its link look like
www.website.com/profile.php?id=username
example.com/weblog/index.php?y=2000&m=11&d=23&id=5678
now we update with new style not rewrite we use www.website.com/username or example.com/weblog/2000/11/23/5678 as permalink
http://example.com/profile/userid (get a profile by the ID)
http://example.com/profile/username (get a profile by the username)
http://example.com/myprofile (get the profile of the currently logged-in user)
1) .htaccess
Create a .htaccess file in the root folder or update the existing one :
Options +FollowSymLinks
# Turn on the RewriteEngine
RewriteEngine On
# Rules
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php
What does that do ?
If the request is for a real directory or file (one that exists on the server), index.php isn't served, else every url is redirected to index.php.
2) index.php
Now, we want to know what action to trigger, so we need to read the URL :
In index.php :
// index.php
// This is necessary when index.php is not in the root folder, but in some subfolder...
// We compare $requestURL and $scriptName to remove the inappropriate values
$requestURI = explode(‘/’, $_SERVER[‘REQUEST_URI’]);
$scriptName = explode(‘/’,$_SERVER[‘SCRIPT_NAME’]);
for ($i= 0; $i < sizeof($scriptName); $i++)
{
if ($requestURI[$i] == $scriptName[$i])
{
unset($requestURI[$i]);
}
}
$command = array_values($requestURI);
With the url http://example.com/profile/19837, $command would contain :
$command = array(
[0] => 'profile',
[1] => 19837,
[2] => ,
)
Now, we have to dispatch the URLs. We add this in the index.php :
// index.php
require_once("profile.php"); // We need this file
switch($command[0])
{
case ‘profile’ :
// We run the profile function from the profile.php file.
profile($command([1]);
break;
case ‘myprofile’ :
// We run the myProfile function from the profile.php file.
myProfile();
break;
default:
// Wrong page ! You could also redirect to your custom 404 page.
echo "404 Error : wrong page.";
break;
}
2) profile.php
Now in the profile.php file, we should have something like this :
// profile.php
function profile($chars)
{
// We check if $chars is an Integer (ie. an ID) or a String (ie. a potential username)
if (is_int($chars)) {
$id = $chars;
// Do the SQL to get the $user from his ID
// ........
} else {
$username = mysqli_real_escape_string($char);
// Do the SQL to get the $user from his username
// ...........
}
// Render your view with the $user variable
// .........
}
function myProfile()
{
// Get the currently logged-in user ID from the session :
$id = ....
// Run the above function :
profile($id);
}
Simple way to do this. Try this code. Put code in your htaccess file:
Options +FollowSymLinks
RewriteEngine on
RewriteRule profile/(.*)/ profile.php?u=$1
RewriteRule profile/(.*) profile.php?u=$1
It will create this type pretty URL:
http://www.domain.com/profile/12345/
For more htaccess Pretty URL:http://www.webconfs.com/url-rewriting-tool.php
It's actually not PHP, it's apache using mod_rewrite. What happens is the person requests the link, www.example.com/profile/12345 and then apache chops it up using a rewrite rule making it look like this, www.example.com/profile.php?u=12345, to the server. You can find more here: Rewrite Guide
ModRewrite is not the only answer. You could also use Options +MultiViews in .htaccess and then check $_SERVER REQUEST_URI to find everything that is in URL.
There are lots of different ways to do this. One way is to use the RewriteRule techniques mentioned earlier to mask query string values.
One of the ways I really like is if you use the front controller pattern, you can also use urls like http://yoursite.com/index.php/path/to/your/page/here and parse the value of $_SERVER['REQUEST_URI'].
You can easily extract the /path/to/your/page/here bit with the following bit of code:
$route = substr($_SERVER['REQUEST_URI'], strlen($_SERVER['SCRIPT_NAME']));
From there, you can parse it however you please, but for pete's sake make sure you sanitise it ;)
It looks like you are talking about a RESTful webservice.
http://en.wikipedia.org/wiki/Representational_State_Transfer
The .htaccess file does rewrite all URIs to point to one controller, but that is more detailed then you want to get at this point. You may want to look at Recess
It's a RESTful framework all in PHP

.htaccess RewriteRule for URL Shortener

I am trying to build a very basic URL shortening website. I used almost all of basixnick's coding in this tutorial (https://www.youtube.com/watch?v=ZnthmFQKlVY all 3 parts) but I'm having an issue.
When you enter a URL into the shortening inbox, for example www.google.com, you will get the corresponding shortened code. Then when you copy and paste the URL, let's say www.mysite.com/xyz123, it will redirect you to www.mysite.com/www.google.com instead of simply www.google.com.
.htaccess looks like this. Is there an issue with the RewriteRule?
<Files .htaccess>
order allow,deny
</Files>
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^(\w+)$ ./load.php?code=$1
EDIT to question:
Here is my load.php file:
<?php
$code = $_GET['code'];
require("./connect.php");
$query = mysql_query("SELECT * FROM items WHERE code='$code'");
$numrows = mysql_num_rows($query);
if ($numrows == 1) {
$row = mysql_fetch_assoc($query);
$url = $row['url'];
header("Location: $url");
}
else
echo "No shortened url was found.";
mysql_close();
?>
When I remove the 'header(...)' code, and replace it with 'echo "$url";' the long url will be echoed just fine. So everything up to that point works fine. Maybe it's the 'header(...)' line. What do you think?
Something's wrong with load.php, there's nothing wrong with the rewrite rule. It looks like the redirect code is redirecting to /www.google.com instead of www.google.com.
EDIT:
If the $url variable is literally www.google.com, then this is the problem. The browser is going to assume that www.google.com is a relative URI, and append it to the URL path that it used to make the request, http://www.mysite.com/www.google.com.
You either need to make it so the URL that you shorten include a protocol (e.g. http:// or https://), or you make the protocol one or the other:
header("Location: http://$url");

How do append URL code from database to domain name and redirect with PHP?

I am on half of URL shortening system. I get the URL from the user and then create code in MySQL for that. Then I have to append coming code to my domain name (now I am working on localhost) like http://localhost/a5c3 then redirect it to real domain.
I stuck in here. A code snippet would be good for me at least to understand what I am going to do or you can explain what I am going to do.
If you are not associating short code with a URL then you need to do that, and redirection will be easy.
Algorithm:
Save the URL from the form and generated code to the database for later use.
$url = $_POST['url']
Generate code
Concatenate your URL with the code
$full_url = $url.$code
Show the shortened URL to the user.
If you want redirect the user, after he/she puts the URL in the browser address then do this:
Create a .htaccess file, add the following lines to it and drop it to your root folder:
RewriteEngine on
RewriteCond $1 !^(index\.php)
RewriteRule ^(.*)$ index.php?code=$1 [L]
The .htaccess file will redirect everything to your index.php. For example, if the user types http://example.com/ujijui then .htaccess will call http://example.com/index.php?code=ujijui. So you can capture the query string in the URL by using $_GET.
In your index.php file:
$code = $_GET['code']
mysql_connect('localhost', 'user', 'password')
mysql_select_db('your_db')
$sql = "SELECT url from Table where code=$code"
$result = mysql_query($sql)
Loop through result and get the URL
header("Location: $url")
Get it, this is just an algorithm.
You need to have your server redirect non-existent URLs to an existing page (for example, using mod_rewrite on Apache). This 'catch-all' page will read the URL, check if the code given exists in the database, and if so, redirect to the proper URL. Ainab's pseudocode explains the last part.
if you are not associating short code
with a URL then you need to do that,
and redirection will be easy.
SELECT url from Table where code=code
header("Location: $url")
For the redirection problem, you should try something like this:
The .htaccess file:
RewriteEngine on
RewriteCond $1 !^(index\.php)
RewriteRule ^(.*)$ index.php?url=$1 [L]
And in the index.php file:
<?php
$url = $_GET['url'];
// These will be taken from database
$urls_associations = array(
'1234' => "http://www.example.com",
'5678' => "http://www.google.com",
'90AB' => "http://stackoverflow.com",
);
// Redirect
if (isset($urls_associations[$url])) {
$redirect = $urls_associations[$url];
header("Location: $redirect");
echo "<a href='$redirect'>Go To : $redirect</a>";
}
else {
echo "Unknown URL code.";
}
Then, when the user goes to, for example, http://localhost/1234, he/she gets redirected to http://example.com, etc. Of course, you should run a query on the database instead of reading from an array, but it looks quite easy, just use something like:
$code = mysql_escape_string($url);
$res = mysql_query("SELECT url FROM mytable WHERE code='$code'");
if ($redirect = mysql_result($res)) {
header("Location: $redirect");
echo "<a href='$redirect'>Go To : $redirect</a>";
}
else {
echo "Unknown URL code.";
}

How to create friendly URL in php?

Normally, the practice or very old way of displaying some profile page is like this:
www.domain.com/profile.php?u=12345
where u=12345 is the user id.
In recent years, I found some website with very nice urls like:
www.domain.com/profile/12345
How do I do this in PHP?
Just as a wild guess, is it something to do with the .htaccess file? Can you give me more tips or some sample code on how to write the .htaccess file?
According to this article, you want a mod_rewrite (placed in an .htaccess file) rule that looks something like this:
RewriteEngine on
RewriteRule ^/news/([0-9]+)\.html /news.php?news_id=$1
And this maps requests from
/news.php?news_id=63
to
/news/63.html
Another possibility is doing it with forcetype, which forces anything down a particular path to use php to eval the content. So, in your .htaccess file, put the following:
<Files news>
ForceType application/x-httpd-php
</Files>
And then the index.php can take action based on the $_SERVER['PATH_INFO'] variable:
<?php
echo $_SERVER['PATH_INFO'];
// outputs '/63.html'
?>
I recently used the following in an application that is working well for my needs.
.htaccess
<IfModule mod_rewrite.c>
# enable rewrite engine
RewriteEngine On
# if requested url does not exist pass it as path info to index.php
RewriteRule ^$ index.php?/ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php?/$1 [QSA,L]
</IfModule>
index.php
foreach (explode ("/", $_SERVER['REQUEST_URI']) as $part)
{
// Figure out what you want to do with the URL parts.
}
I try to explain this problem step by step in following example.
0) Question
I try to ask you like this :
i want to open page like facebook profile www.facebook.com/kaila.piyush
it get id from url and parse it to profile.php file and return featch data from database and show user to his profile
normally when we develope any website its link look like
www.website.com/profile.php?id=username
example.com/weblog/index.php?y=2000&m=11&d=23&id=5678
now we update with new style not rewrite we use www.website.com/username or example.com/weblog/2000/11/23/5678 as permalink
http://example.com/profile/userid (get a profile by the ID)
http://example.com/profile/username (get a profile by the username)
http://example.com/myprofile (get the profile of the currently logged-in user)
1) .htaccess
Create a .htaccess file in the root folder or update the existing one :
Options +FollowSymLinks
# Turn on the RewriteEngine
RewriteEngine On
# Rules
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php
What does that do ?
If the request is for a real directory or file (one that exists on the server), index.php isn't served, else every url is redirected to index.php.
2) index.php
Now, we want to know what action to trigger, so we need to read the URL :
In index.php :
// index.php
// This is necessary when index.php is not in the root folder, but in some subfolder...
// We compare $requestURL and $scriptName to remove the inappropriate values
$requestURI = explode(‘/’, $_SERVER[‘REQUEST_URI’]);
$scriptName = explode(‘/’,$_SERVER[‘SCRIPT_NAME’]);
for ($i= 0; $i < sizeof($scriptName); $i++)
{
if ($requestURI[$i] == $scriptName[$i])
{
unset($requestURI[$i]);
}
}
$command = array_values($requestURI);
With the url http://example.com/profile/19837, $command would contain :
$command = array(
[0] => 'profile',
[1] => 19837,
[2] => ,
)
Now, we have to dispatch the URLs. We add this in the index.php :
// index.php
require_once("profile.php"); // We need this file
switch($command[0])
{
case ‘profile’ :
// We run the profile function from the profile.php file.
profile($command([1]);
break;
case ‘myprofile’ :
// We run the myProfile function from the profile.php file.
myProfile();
break;
default:
// Wrong page ! You could also redirect to your custom 404 page.
echo "404 Error : wrong page.";
break;
}
2) profile.php
Now in the profile.php file, we should have something like this :
// profile.php
function profile($chars)
{
// We check if $chars is an Integer (ie. an ID) or a String (ie. a potential username)
if (is_int($chars)) {
$id = $chars;
// Do the SQL to get the $user from his ID
// ........
} else {
$username = mysqli_real_escape_string($char);
// Do the SQL to get the $user from his username
// ...........
}
// Render your view with the $user variable
// .........
}
function myProfile()
{
// Get the currently logged-in user ID from the session :
$id = ....
// Run the above function :
profile($id);
}
Simple way to do this. Try this code. Put code in your htaccess file:
Options +FollowSymLinks
RewriteEngine on
RewriteRule profile/(.*)/ profile.php?u=$1
RewriteRule profile/(.*) profile.php?u=$1
It will create this type pretty URL:
http://www.domain.com/profile/12345/
For more htaccess Pretty URL:http://www.webconfs.com/url-rewriting-tool.php
It's actually not PHP, it's apache using mod_rewrite. What happens is the person requests the link, www.example.com/profile/12345 and then apache chops it up using a rewrite rule making it look like this, www.example.com/profile.php?u=12345, to the server. You can find more here: Rewrite Guide
ModRewrite is not the only answer. You could also use Options +MultiViews in .htaccess and then check $_SERVER REQUEST_URI to find everything that is in URL.
There are lots of different ways to do this. One way is to use the RewriteRule techniques mentioned earlier to mask query string values.
One of the ways I really like is if you use the front controller pattern, you can also use urls like http://yoursite.com/index.php/path/to/your/page/here and parse the value of $_SERVER['REQUEST_URI'].
You can easily extract the /path/to/your/page/here bit with the following bit of code:
$route = substr($_SERVER['REQUEST_URI'], strlen($_SERVER['SCRIPT_NAME']));
From there, you can parse it however you please, but for pete's sake make sure you sanitise it ;)
It looks like you are talking about a RESTful webservice.
http://en.wikipedia.org/wiki/Representational_State_Transfer
The .htaccess file does rewrite all URIs to point to one controller, but that is more detailed then you want to get at this point. You may want to look at Recess
It's a RESTful framework all in PHP

Categories