Jim34
Jim34

Reputation: 45

Php url shortener with static htmls

My htaccess:

RewriteEngine On
RewriteCond $1 !^(index\.php)
RewriteRule ^(.*)$ index.php?l=$1 [L]

and php:

<?php
$links = parse_ini_file('links.ini');

if(isset($_GET['l']) && array_key_exists($_GET['l'], $links)){
header('Location: ' . $links[$_GET['l']]);
}
else
    include ('index.html');
?>

In the links.ini I have short url and website url:

youtube1 = "https://www.youtube.com/watch?v=9bZkp7q19f0"
youtube2 = "https://www.youtube.com/watch?v=wcLNteez3c4"
etc.

These files are in the root and url shortening works.

In the index.html I have menu with static html pages:

<a href="/" >Home page</a>
<a href="page1" >page1</a>
<a href="page2" >page2</a>
etc.

But when I click on them it only reloads index.html?

Any help will be appriciated!

I tried to put static html links into links.ini:

page1 = page1

but that doesn't work either... I get the Page isn't redirecting properly error.

Upvotes: 1

Views: 113

Answers (3)

Uri Goren
Uri Goren

Reputation: 13700

You might want to look at this simple url shortener, it's very similar to what you are doing, but with a json instead of an ini file.

The core is the .htaccess file:

Options +SymLinksIfOwnerMatch
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^((?!index\.php).+)$ /index.php?short=$1 [NC,L,QSA]

Upvotes: 0

Jim34
Jim34

Reputation: 45

So i changed the php to this:

<?php
$links = parse_ini_file('links.ini');

if(isset($_GET['l']) && array_key_exists($_GET['l'], $links)){
header('Location: ' . $links[$_GET['l']]);
}

else if($_GET['l'] == 'index' | $_GET['l'] == 'page1' | $_GET['l'] == 'page2')
    include($_GET['l']. '.html');

else if($_GET['l'] == '')
    include('index.html');

else 
    include('404.html');

?>

I don't know how elegant this is... If someone knows a better way...

Upvotes: 0

Olaf Dietsche
Olaf Dietsche

Reputation: 74078

When you look into error messages, you will notice

PHP Warning: syntax error, unexpected '=' in links.ini on line 1\n in /var/www/example.com/index.php on line 2

and when looking at links.ini, you will see a second equal sign = in the URL

youtube1 = https://www.youtube.com/watch?v=9bZkp7q19f0

So quoting the value, e.g.

youtube1 = "https://www.youtube.com/watch?v=9bZkp7q19f0"

should make it work as expected.

Upvotes: 1

Related Questions