Jump to content

Recommended Posts

Hello everyone,

 

Here is what I am working on. I am in the process of creating a URL shortner. I am only doing this so that i can learn more about PHP. The problem that I am having is that the shortened URl keeps redirecting back to the home page instead of the site that it is supposed to represent.

 

Example: http://shortit.org/IlwU3g

 

I typed in the full url like this http://shortit.org/index.php?code=$IlwU3g

 

Here is the code for my htaccess page

 

 

 

RewriteEngine On

RewriteBase /
RewriteRule ^([a-zA-Z0-9]+)$ index.php?code=$1

##### Remove query string ###################################
RewriteCond %{QUERY_STRING} .
RewriteRule ^(.*)$ [url="http://shortit.org/$1"]http://shortit.org/$1[/url]? [R=301,L]

 

 

Here is the function I am using to do the redirect

 

 

 

function redirect($code){
$code = mysql_real_escape_string($code);
if(code_exists($code)){
$url_query = mysql_query("SELECT `url` FROM `urls` WHERE `code` = '$code'") or die (mysql_error());
$url = mysql_result($url_query, 0 , 'url');
header('Location:' . $url);
}
}

 

 

Here is the code from my index page

 

 

 




<?php
include('function/init.php');
if(isset($_GET['code']) && !empty($_GET['code'])) {
	$code = $_GET['code'];
	redirect($code);
	die();
}
?>
<!doctype html>
<!--[if gt IE 8]><!--><html class="">
<!--<![endif]-->
<base href="http://shortit.org">
<?php include('includes/head.php'); ?>
<script src="/js/respond.min.js"></script>
<script TYPE="text/javascript" SRC="/js/jquery.js"></script>
<script TYPE="text/javascript">
function go(url){
	$.post('/url.php', { url:url }, function(data) {
		if(data == 'error_no_url') {
			$('#message').html('<p>No Url Specified</p>');
		}else if (data == 'error_invalid_url') {
			$('#message').html('<p>Not a Valid URL</p>');
		} else if (data == 'all_ready_short') {
			$('#message').html('<p>Allready a shortit.org URL</p>');
		}else {
			$('#url').val(data);
			$('#url').select();
			$('#message').html('<p>Sucessfully Shortened your URL!</p>');
		}
	});
}
</script>
<body>
<div class="gridContainer clearfix">
<?php include('includes/header.php'); ?>
<div id="LayoutDiv1">
<h1>Shorten your URL</h1>
			<ul>
<li><input ID="url" TYPE="text" NAME="url" SIZE ="60" placeholder="http://" autofocus onkeydown="if(event.keyCode == 13 || event.which == 13) { go($('#url').val()); }" /></li>
<li><input ID="submit" TYPE="submit" NAME="shorten" VALUE="shorten url" onclick="go($('#url').val());" /></li>
			</ul>
			<div ID="message">
				<p> </p>
			</div>
<div class="columns">
<div class="col-1">
<p class="col-header">Future Additions</p>
<p>Share links on Facebook one click</p>
<p>Share links on twitter one click</p>
<p>Share links on google+ one click</p>
<p>Custom URL's</p>
<p>Ability to give names to your most used links</p>
<p>Ability to track your URL's</p>
<p>Tell your friend about system</p>
</div>
<div class="col-2">
<p class="col-header">Links</p>
<?php
							$random_url = mysql_query("SELECT * FROM `urls` ORDER BY RAND() LIMIT 0,1;");
							$random = mysql_fetch_array($random_url, MYSQL_ASSOC);

							echo "<p><a href='http://".$random['url']."' target='new'>Random Shortit URL</a></p>";
						?>
<p>Most common URL shortened(coming soon)</p>
<p>Most clicked URL(coming soon)</p>
</div>
<div class="col-3">
<p class="col-header">Statistics</p>
<p><?php echo url_count(); ?> URL's currently in database</p>
</div>
</div>
</div>
<?php
		 	include('includes/rightside.php');
		 	include('includes/footer.php');
		 ?>
</div>
</body>
</html>

Edited by mdmartiny
Link to comment
https://forums.phpfreaks.com/topic/269084-trying-to-get-url-redirect-to-work/
Share on other sites

I don't see where you're inserting anything into the database. Is the table storing the full URL?

 

Narrow this problem down yourself. So far you have "the whole process is broken, here's some of the code." Does the form post include the whole URL? If so, does the script accept the whole url? If so, does the whole URL get inserted into the database? If so, does the key for that URL get represented properly by the system? If so, does that key retrieve the full URL? If so, does the full URL get added to the location redirect?

 

That's how debugging works. Small units of functionality.

OK I did some playing around with the site and this is what I came up with... I am not sure why it is doing this. So I am hoping that someone can explain it to me

 

When I type in shortit.zxq.net/index.php?code=OV8R6t or shortit.zxq.net/OV8R6t it works

but when I type in shortit.org/OV8R6t all it does is take me to the index page of the site?

 

So what I am taking from it is that the code works so there has to be something with the URL

The problem is that rewriting won't stop when a rule matches and executes. Follow along:

1. I go to www.shortit.org/IlwU3g

2. The first RewriteRule matches and the URL is now /index.php?code=IlwU3g

- But without a redirection

- Rewriting continues!

3. The following RewriteCond and RewriteRule match so I'm redirected to shortit.org/index.php

- RewriteRule does not match against the query string so the .* is just "index.php"

- Rewriting stops because of the [L] flag

 

In other words, you have the first Rule which adds a query string, but then you have the second Rule which strips it away.

 

Here's how I would do this:

"# First, the stuff I don't want

# Only shortit.zxq.net and shortit.org are acceptable hostnames
RewriteCond %{HTTP_HOST} !^(shortit.zxq.net|shortit.org)$
RewriteRule ^ http://shortit.org%{REQUEST_URI} [L,R=301]

# Don't allow people to go to /index.php?code=xyz and send them to /xyz
# I prefer looking at the exact request for things like this
RewriteCond %{REQUEST_URI} ^/index\.php\?code=([a-zA-Z0-9]+)$
RewriteRule ^ /%1 [L,R=301]

# Now stuff I do want

# Non-existant requests like /xyz are shortcodes
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9]+)$ index.php?code=$1 [L]"

Ignore the quotes, code tags don't work that well yet.

 

For the record, with that one "don't allow them to go to /index.php?code=xyz" I would actually just

RewriteCond %{REQUEST_URI} ^/index\.php\?code=([a-zA-Z0-9]+)$
RewriteRule ^ index.php? [L]

make it look like a normal request to /index.php (doesn't reveal anything about how your shortcodes are URL-rewritten).

Edited by requinix

That is what I thought might of been happening after I had read the last post.

 

The strip query part was supposed to remove the query string so that user information was not posted in the url. Like on the view-links.php page. So people did not see view-links.php?u=1. I guess that is not really important. Just thought it would look nicer.

 

Thank you for your help. I will definitely do more research on htacess pages.

 

#1 thing to remember with mod_rewrite is that when a RewriteRule matches rewriting will keep going on with that new URL unless you explicitly stop it (like with a [L]).

 

[edit] Annnd moved.

Edited by requinix

I just re did the htacess page and it is still not working. I made the changes that you suggested.

 

The only one that works now is the link that writes out the whole code along with the query string

 

When I type in shortit.zxq.net/index.php?code=OV8R6t takes me through the redirect

When I type in shortit.zxq.net/OV8R6t gives me an 404 error

when I type in shortit.org/OV8R6t all it does is take me to http://shortit.org/index.php

RewriteEngine On

ErrorDocument 404 /error/404.php
ErrorDocument 500 /error/500.php

# First, the stuff I don't want

# Only shortit.zxq.net and shortit.org are acceptable hostnames
RewriteCond %{HTTP_HOST} !^(shortit.zxq.net|shortit.org)$
RewriteRule ^ http://shortit.org%{REQUEST_URI} [L,R=301]

# Don't allow people to go to /index.php?code=xyz and send them to /xyz
# I prefer looking at the exact request for things like this
RewriteCond %{REQUEST_URI} ^/index\.php\?code=([a-zA-Z0-9]+)$
RewriteRule ^ index.php? [L]

# Now stuff I do want

# Non-existant requests like /xyz are shortcodes
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9]+)$ index.php?code=$1 [L]

I am sorry if I confused everyone.

 

I am not getting any error messages. It is not putting out any at least from what I can see.

 

When I try to use a URL that has been shortened it takes me to a 404 error page... It does not redirect based on the URL like I am trying to get it to do. Once again I am sorry if I have confused people.

It doesn't look like the one disallowing direct access to index.php?code=xyz is working either. Can't test the one about hostnames because apparently you have a shared IP address (so if I try a different hostname the server won't know what to do with it).

 

What happens if you have

RewriteEngine On

ErrorDocument 404 /error/404.php
ErrorDocument 500 /error/500.php

RewriteRule test /index.php?test [L,R]

and you go to shortit.org/test?

Sorry it has been a couple of days since I have responded.

 

The company that hosted my site has had their database system down for two days with no explanation. So I had to wait for them to get it back up and I switched providers. I did that like an hour ago and after I switched the shortner has been working.

 

This is my final code if you were wondering

 

RewriteEngine On

# Do not remove this line, otherwise mod_rewrite rules will stop working

RewriteBase /

ErrorDocument 404 /error/404.php
ErrorDocument 500 /error/500.php

# First, the stuff I don't want

# Only shortit.zxq.net and shortit.org are acceptable hostnames
RewriteCond %{HTTP_HOST} !^(shortit.zxq.net|shortit.org)$
RewriteRule ^ http://shortit.org%{REQUEST_URI} [L,R=301]

# Don't allow people to go to /index.php?code=xyz and send them to /xyz
# I prefer looking at the exact request for things like this
RewriteCond %{REQUEST_URI} ^/index\.php\?code=([a-zA-Z0-9]+)$
RewriteRule ^ index.php? [L]

# Now stuff I do want
# Non-existant requests like /xyz are shortcodes

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?([a-zA-Z0-9]+)$ index.php?code=$1 [L]

 

Thank you for all of your assistance in helping me figure this out

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.