Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add config-example.php and MYSQL_PORT when connecting to database #15

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
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
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
.DS_Store
.DS_Store
.idea
config.php
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ Requires PHP ≥ 5.4.0 or higher.

1. Download the source code as located within this repository, and upload it to your web server.
2. Use `database.sql` to create the `redirect` table in a database of choice. (Do *not* delete the `INSERT` statement on [line 10](https://github.com/mathiasbynens/php-url-shortener/blob/f64ee342246fa5bf0340641372680a2d398afc79/database.sql#L10) as it is needed to initialize the database.)
3. Edit `config.php` and enter your database credentials.
4. For additional *security through obscurity™*, consider renaming `shorten.php` to a secret file name of your choosing and tweaking the `.htaccess` file ([line 3](https://github.com/mathiasbynens/php-url-shortener/blob/f64ee342246fa5bf0340641372680a2d398afc79/.htaccess#L3)) accordingly.
3. Rename `config-example.php` to `config.php`.
4. Edit `config.php` and enter your database credentials.
5. For additional *security through obscurity™*, consider renaming `shorten.php` to a secret file name of your choosing and tweaking the `.htaccess` file ([line 3](https://github.com/mathiasbynens/php-url-shortener/blob/f64ee342246fa5bf0340641372680a2d398afc79/.htaccess#L3)) accordingly.

## Features

Expand Down Expand Up @@ -49,4 +50,5 @@ This script is available under the MIT license.

* [Peter Beverloo](http://peter.sh/)
* [Tomislav Biscan](https://github.com/B-Scan)
* [Medard Mandane](https://github.com/medardm/)

9 changes: 4 additions & 5 deletions config.php → config-example.php
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
<?php

define('MYSQL_HOST', 'localhost');
define('MYSQL_USER', 'user');
define('MYSQL_PASSWORD', 'password');
define('MYSQL_DATABASE', 'database');
define('TWITTER_USERNAME', 'mathias');
define('MYSQL_USER', 'test');
define('MYSQL_DATABASE', 'url_redirect');
define('MYSQL_PASSWORD', 'test');
define('TWITTER_USERNAME', 'sparkpointio');
define('GOOGLE_PLUS_ID', '106697091536876736486');
define('SHORT_URL', 'https://mths.be/'); // include the trailing slash!
define('DEFAULT_URL', 'https://mathiasbynens.be'); // omit the trailing slash!

?>
75 changes: 41 additions & 34 deletions index.php
Original file line number Diff line number Diff line change
@@ -1,46 +1,53 @@
<?php

require 'config.php';
if (file_exists('config.php')) {
require 'config.php';
} else {
require 'config-example.php';
}

$url = DEFAULT_URL . '/';

if (isset($_GET['slug'])) {

$slug = $_GET['slug'];

if ('@' == $slug) {
$url = 'https://twitter.com/' . TWITTER_USERNAME;
} else if (' ' == $slug) { // +
$url = 'https://plus.google.com/u/0/' . GOOGLE_PLUS_ID . '/posts';
} else {

$slug = preg_replace('/[^a-z0-9]/si', '', $slug);

if (is_numeric($slug) && strlen($slug) > 8) {
$url = 'https://twitter.com/' . TWITTER_USERNAME . '/status/' . $slug;
} else {

$db = new MySQLi(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE);
$db->set_charset('utf8mb4');

$escapedSlug = $db->real_escape_string($slug);
$redirectResult = $db->query('SELECT url FROM redirect WHERE slug = "' . $escapedSlug . '"');

if ($redirectResult && $redirectResult->num_rows > 0) {
$db->query('UPDATE redirect SET hits = hits + 1 WHERE slug = "' . $escapedSlug . '"');
$url = $redirectResult->fetch_object()->url;
} else {
$url = DEFAULT_URL . $_SERVER['REQUEST_URI'];
}

$db->close();

}
}
$slug = $_GET['slug'];

if ('@' == $slug) {
$url = 'https://twitter.com/' . TWITTER_USERNAME;
} else {
if (' ' == $slug) {
// +
$url = 'https://plus.google.com/u/0/' . GOOGLE_PLUS_ID . '/posts';
} else {
$slug = preg_replace('/[^a-z0-9]/si', '', $slug);

if (is_numeric($slug) && strlen($slug) > 8) {
$url = 'https://twitter.com/' . TWITTER_USERNAME . '/status/' . $slug;
} else {
$db = new MySQLi(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE, MYSQL_PORT);
$db->set_charset('utf8mb4');

$escapedSlug = $db->real_escape_string($slug);
$redirectResult = $db->query('SELECT url FROM redirect WHERE slug = "' . $escapedSlug . '"');

if ($redirectResult && $redirectResult->num_rows > 0) {
$db->query('UPDATE redirect SET hits = hits + 1 WHERE slug = "' . $escapedSlug . '"');
$url = $redirectResult->fetch_object()->url;
} else {
$url = DEFAULT_URL . $_SERVER['REQUEST_URI'];
}

$db->close();
}
}
}
}

header('Location: ' . $url, null, 301);

$attributeValue = htmlspecialchars($url);
?>
<meta http-equiv=refresh content="0;URL=<?php echo $attributeValue; ?>"><a href="<?php echo $attributeValue; ?>">Continue</a><script>location.href=<?php echo json_encode($url, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES); ?></script>
<meta
http-equiv=refresh
content="0;URL=<?php echo $attributeValue; ?>"
><a href="<?php echo $attributeValue; ?>">Continue</a>
<script>location.href =<?php echo json_encode($url, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES); ?></script>
71 changes: 43 additions & 28 deletions shorten.php
Original file line number Diff line number Diff line change
@@ -1,55 +1,70 @@
<?php

require 'config.php';
if (file_exists('config.php')) {
require 'config.php';
} else {
require 'config-example.php';
}

header('Content-Type: text/plain;charset=UTF-8');

$url = isset($_GET['url']) ? urldecode(trim($_GET['url'])) : '';
$customSlug = isset($_GET['slug']) ? trim($_GET['slug']) : '';

if (in_array($url, array('', 'about:blank', 'undefined', 'http://localhost/'))) {
die('Enter a URL.');
if (in_array($url, ['', 'about:blank', 'undefined', 'http://localhost/'])) {
die('Enter a URL.');
}

// If the URL is already a short URL on this domain, don’t re-shorten it
if (strpos($url, SHORT_URL) === 0) {
die($url);
die($url);
}

function nextLetter(&$str) {
$str = ('z' == $str ? 'a' : ++$str);
function nextLetter(&$str)
{
$str = ('z' == $str ? 'a' : ++$str);
}

function getNextShortURL($s) {
$a = str_split($s);
$c = count($a);
if (preg_match('/^z*$/', $s)) { // string consists entirely of `z`
return str_repeat('a', $c + 1);
}
while ('z' == $a[--$c]) {
nextLetter($a[$c]);
}
nextLetter($a[$c]);
return implode($a);
function getNextShortURL($s)
{
$a = str_split($s);
$c = count($a);
if (preg_match('/^z*$/', $s)) { // string consists entirely of `z`
return str_repeat('a', $c + 1);
}
while ('z' == $a[--$c]) {
nextLetter($a[$c]);
}
nextLetter($a[$c]);
return implode($a);
}

$db = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE);
$db = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE, MYSQL_PORT);
$db->set_charset('utf8mb4');

$url = $db->real_escape_string($url);

$result = $db->query('SELECT slug FROM redirect WHERE url = "' . $url . '" LIMIT 1');
if (!empty($customSlug)) {
$resultSlug = $db->query('SELECT slug FROM redirect WHERE slug = "' . $customSlug . '" LIMIT 1');

if ($resultSlug && $resultSlug->num_rows > 0) { // If there’s already a short URL for this URL
die(SHORT_URL . $result->fetch_object()->slug);
}
}
if ($result && $result->num_rows > 0) { // If there’s already a short URL for this URL
die(SHORT_URL . $result->fetch_object()->slug);
die(SHORT_URL . $result->fetch_object()->slug);
} else {
$result = $db->query('SELECT slug, url FROM redirect ORDER BY date DESC, slug DESC LIMIT 1');
if ($result && $result->num_rows > 0) {
$slug = getNextShortURL($result->fetch_object()->slug);
if ($db->query('INSERT INTO redirect (slug, url, date, hits) VALUES ("' . $slug . '", "' . $url . '", NOW(), 0)')) {
header('HTTP/1.1 201 Created');
echo SHORT_URL . $slug;
$db->query('OPTIMIZE TABLE `redirect`');
}
}
$result = $db->query('SELECT slug, url FROM redirect ORDER BY date DESC, slug DESC LIMIT 1');
if ($result && $result->num_rows > 0) {
$slug = !empty($customSlug) ? $customSlug : getNextShortURL($result->fetch_object()->slug);

if ($db->query('INSERT INTO redirect (slug, url, date, hits) VALUES ("' . $slug . '", "' . $url . '", NOW(), 0)')) {
header('HTTP/1.1 201 Created');
echo SHORT_URL . $slug;
$db->query('OPTIMIZE TABLE `redirect`');
}
}
}

?>