Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 14 additions & 9 deletions README → README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
# PHP-URL-Shortener

## License

This software is released under GPL-2 conditions. You can get a copy of it here:
License: http://www.gnu.org/licenses/gpl-2.0.html

Benefits
## Benefits

- Can shorten over 42 billion unique URLs in 6 or less characters (it can do more than 12,000,000 in only 4!)
- Super duper fast—uses very little server resources
Expand All @@ -14,23 +19,23 @@ Benefits
- Option to store a local cache to prevent database queries on every redirect
- Option to change the characters allowed in a shortened url

Installation
## Installation

1. Make sure your server meets the requirements:
a) Optionally you can run this from your current domain or find a short domain
b) Apache
c) PHP
d) MySQL
e) Access to run SQL queries for installation
* Optionally you can run this from your current domain or find a short domain
* Apache
* PHP
* A PDO driver with its database
* Access to run SQL queries for installation
2. Download a .zip file of the PHP URL shortener script files
3. Upload the contents of the .zip file to your web server
4. Update the database info in config.php
5. Run the SQL included in shortenedurls.sql. Many people use phpMyAdmin for this, if you can’t do it yourself contact your host.
6. Rename rename.htaccess to .htaccess
7. If you want to use the caching option, create a directory named cache with permissions 777

Using your personal URL shortener service
## Using your personal URL shortener service

- To manually shorten URLs open in your web browser the location where you uploaded the files.
- To programmatically shorten URLs with PHP use the following code:
$shortenedurl = file_get_contents('http://yourdomain.com/shorten.php?longurl=' . urlencode('http://' . $_SERVER['HTTP_HOST'] . '/' . $_SERVER['REQUEST_URI']));
```$shortenedurl = file_get_contents('http://yourdomain.com/shorten.php?longurl=' . urlencode('http://' . $_SERVER['HTTP_HOST'] . '/' . $_SERVER['REQUEST_URI']));```
10 changes: 8 additions & 2 deletions config.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,21 @@
*/

// db options
define('DB_TYPE', 'pgsql');
define('DB_NAME', 'your db name');
define('DB_USER', 'your db usernae');
define('DB_PASSWORD', 'your db password');
define('DB_HOST', 'localhost');
define('DB_TABLE', 'shortenedurls');

// connect to database
mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysql_select_db(DB_NAME);
try {
$dbh = new PDO(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASSWORD);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
print "Erreur !: " . $e->getMessage() . "<br/>";
die();
}

// base location of script (include trailing slash)
define('BASE_HREF', 'http://' . $_SERVER['HTTP_HOST'] . '/');
Expand Down
40 changes: 32 additions & 8 deletions redirect.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,26 +16,49 @@

$shortened_id = getIDFromShortenedURL($_GET['url']);

try {
$stmt = $dbh->prepare('SELECT long_url FROM '.DB_TABLE." WHERE id=?");
$stmt->execute(array($shortened_id));
$tmp = $stmt->fetch(PDO::FETCH_NUM);
$long_url = $tmp[0];
} catch (Exception $e) {
echo "Failed " . $e->getMessage();
exit;
}

if(CACHE)
{
$long_url = file_get_contents(CACHE_DIR . $shortened_id);
if(empty($long_url) || !preg_match('|^https?://|', $long_url))
{
$long_url = mysql_result(mysql_query('SELECT long_url FROM ' . DB_TABLE . ' WHERE id="' . mysql_real_escape_string($shortened_id) . '"'), 0, 0);
@mkdir(CACHE_DIR, 0777);
$handle = fopen(CACHE_DIR . $shortened_id, 'w+');
fwrite($handle, $long_url);
fclose($handle);
try {
$stmt->execute(array($shortened_id));
$tmp = $stmt->fetch(PDO::FETCH_NUM);
$long_url = $tmp[0];
@mkdir(CACHE_DIR, 0777);
$handle = fopen(CACHE_DIR . $shortened_id, 'w+');
fwrite($handle, $long_url);
fclose($handle);
} catch (Exception $e) {
echo "Failed " . $e->getMessage();
exit;
}
}
}
else
{
$long_url = mysql_result(mysql_query('SELECT long_url FROM ' . DB_TABLE . ' WHERE id="' . mysql_real_escape_string($shortened_id) . '"'), 0, 0);
try {
$stmt->execute(array($shortened_id));
$tmp = $stmt->fetch(PDO::FETCH_NUM);
$long_url = $tmp[0];
} catch (Exception $e) {
echo "Failed " . $e->getMessage();
}
}

if(TRACK)
{
mysql_query('UPDATE ' . DB_TABLE . ' SET referrals=referrals+1 WHERE id="' . mysql_real_escape_string($shortened_id) . '"');
$dbh->query('UPDATE ' . DB_TABLE . ' SET referrals=referrals+1 WHERE id="' . pg_escape_string($shortened_id) . '"');
}

header('HTTP/1.1 301 Moved Permanently');
Expand All @@ -52,5 +75,6 @@ function getIDFromShortenedURL ($string, $base = ALLOWED_CHARS)
{
$out += strpos($base, $char) * pow($length, $size - $i);
}
$out -= 65536;
return $out;
}
}
27 changes: 22 additions & 5 deletions shorten.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,13 @@
}

}

$stmt = $dbh->prepare('SELECT id FROM '.DB_TABLE.' WHERE long_url=?');

// check if the URL has already been shortened
$already_shortened = mysql_result(mysql_query('SELECT id FROM ' . DB_TABLE. ' WHERE long_url="' . mysql_real_escape_string($url_to_shorten) . '"'), 0, 0);
$stmt->execute(array($url_to_shorten));
$tmp = $stmt->fetch(PDO::FETCH_NUM);
$already_shortened = $tmp[0];
if(!empty($already_shortened))
{
// URL has already been shortened
Expand All @@ -45,16 +49,29 @@
else
{
// URL not in database, insert
mysql_query('LOCK TABLES ' . DB_TABLE . ' WRITE;');
mysql_query('INSERT INTO ' . DB_TABLE . ' (long_url, created, creator) VALUES ("' . mysql_real_escape_string($url_to_shorten) . '", "' . time() . '", "' . mysql_real_escape_string($_SERVER['REMOTE_ADDR']) . '")');
$shortened_url = getShortenedURLFromID(mysql_insert_id());
mysql_query('UNLOCK TABLES');
try {
$dbh->beginTransaction();
$stmt2 = $dbh->prepare('INSERT INTO '.DB_TABLE." (long_url, created, creator) VALUES (?,?,?)");
$stmt2->execute(array($url_to_shorten, time(), $_SERVER['REMOTE_ADDR']));
$stmt->execute(array($url_to_shorten));
$tmp = $stmt->fetch(PDO::FETCH_NUM);
print_r($tmp);
$shortened_url = getShortenedURLFromID($tmp[0]);
if(empty($shortend_url)) {
die('Insertion ratee');
}
$dbh->commit();
} catch (Exception $e) {
$dbh->rollBack();
echo "Failed: " . $e->getMessage();
}
}
echo BASE_HREF . $shortened_url;
}

function getShortenedURLFromID ($integer, $base = ALLOWED_CHARS)
{
$integer += 65536;
$length = strlen($base);
while($integer > $length - 1)
{
Expand Down