.htaccess RewriteRule for URL Shortener - php

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");

Related

URL Shortner Code is working fine on localhost but not on website

I have made a url shortner code in which user put the long url in text field and when user click on the submit button it insert the long url in DB and shows Short URL to the user, which is working perfectly on my localhost.
But when i uploaded it online its not working. Although the Data is inserting the DB online and it shows the Short URL but when i enter the url in the address bar it shows The Site Cant Be Reached server DNS address could not be found..
I think it is related to my .htaccess file.
This is my .htaccess file:
RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ index.php?r=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ index.php?r=$1
This is my index.php file:
<?php
include 'config.php';
if(isset($_GET['r']) || !empty($_GET['r']))
{
$url_id = $_GET['r'];
$sql = "SELECT long_url FROM url_shortner WHERE url_id = '$url_id'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
if(mysqli_num_rows($result) == 1)
{
$l_url = $row['long_url'];
header('Location:' .$l_url);
}
else
{
header('Location: index2.php');
}
}?>
As discussed in the chat room, there were some unexpected mistakes prior to deploying to your production server.
Despite of identifying and fixing the problem above, you still get 404 error which indicates a problem in the rewrite rule.
The rule below should work. You only need this one. No need for 2 rules.
RewriteRule ^([a-zA-Z0-9_-]+)\/?$ index.php?r=$1

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

htaccess get code and redirect with 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

SEO Url Redirect/Rewrite Using Database Managed Links

I have searched left and right.
And I am trying to find a script or a method on how I can store links in database and use them for redirection.
This is an E-commerce project and I am looking for something to manage product and system URL from database.
Something similar like magento does.
Basically anything after the domain say like domain.com/demo/12/my_iphone
so now demo/12/my_iphone will be sent to database for query and in databases there will be a destination URL which could be productlisting.php?searchstring=iphones
The user will see link domain.com/demo/12/my_iphone but actually he will be seing productlisting.php?searchstring=iphones
Basically demo/12/my_iphone = productlisting.php?searchstring=iphones
And tomorrow if the user wants to edit demo/12/my_iphone to demo/12/myiphone he can just do so using simple form which will update in the database.
How can I achieve this?
Use mod_rewrite in apache in combination with a PHP script.
1) Make a .htaccess file and put it in a folder, say www.yourdomain.com/a/.htaccess
Options +FollowSymLinks -Indexes
RewriteEngine On
RewriteRule .* index.php?%{QUERY_STRING} [L]
2) Create an index.php that handles all requests
(psaudo-code)
<?php
/**
* This script is simply parsing the url used, /demo/12/my_iphone
*/
require_once('library.php');
$request_uri = $_SERVER['REQUEST_URI'];
// parse $request_uri by splitting on slashes /
$params = my_parse_function($request_uri); // <= parse_url() is helpful here!
$param1 = $params[0]; // "demo"
$param2 = $params[1]; // "12";
$param3 = $params[2]; // "my_iphone";
// db-lookup based on the request
$url = fetchUrlFromDB($param1, $param2, $param3);
if($url){
header('Location: '.$url); // $url = "productlisting.php?searchstring=iphones"
die();
}
else{
echo "invalid parameters";
}
?>
It wouldn't be difficult to program such a solution if it comes to that. You could grab the uri from $_SERVER['REQUEST_URI'] and pass it to parse_url to grab the path. Then use the path to query against the database.

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.";
}

Categories