October 31st, 2011 at 1:44 pm
There are lots of URL redirecting services – all of them do the job. But if you still want to do redirects yourself from your own domain (especially if you have a short domain name
), you may want to have your own little service for that. And, it just feels nice to have the power over redirects in your own hands.
I have created such a service for this website, so have a try right away: lxg.de/r/eff.
The URL should be as short as possible. Also, you don’t want the URL shortener to conflict with your other web stuff. Therefore, you should create a subdirectory r/ in your document root and put a .htaccess file with the following content there.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /r/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /r/index.php [L]
</IfModule>
Now create the file index.php with the following content:
<?php
$req = preg_replace('|[^a-z0-9\-\_\.]|i', '', strrchr($_SERVER['REQUEST_URI'], '/'));
$list = file(__DIR__.'/list.php', FILE_IGNORE_NEW_LINES & FILE_SKIP_EMPTY_LINES);
$url = '';
foreach ((array)$list as $line)
{
if (strpos($line, "$req\t") !== 0)
continue;
$url = trim(strrchr($line, "\t"));
break;
}
if ($url)
{
header("Location: $url", true, 302);
printf('If your browser doesn\'t redirect you, click here: <a href="%1$s">%1$s</a>.', $url);
}
else
{
echo 'Sorry, no redirect found. Please check the spelling of the URL.';
}
exit;
?>
The actual mapping of redirection identifiers to target URLs is in the file list.php:
<?php die('Error') ?>
eff http://www.eff.org/
aclu http://www.aclu.org/
The first line of this file is important to make sure that nobody can simply download the list (this is also why we use a PHP file and no plain TXT). The other lines consist of arbitrary identifiers and the target URLs, separated by one or more tab characters. The identifiers may contain latin letters, numbers, and the dot, minus and underscore characters. It may be advisable to make them human readable, but you may also optimize them for length.
0
Code
htaccess, PHP
August 29th, 2011 at 9:57 pm
I’ve seen horrible things today. Somebody (the file didn’t carry an author … good for him or her) tried to get the first element of a PHP array – using array_shift. Of course, array_shift modifies the source array, so he worked on a copy of his original array, as (of course) he didn’t want to alter the array itself. Looked something like this:
$copyOfArray = $array;
$firstElementOfArray = array_shift($copyOfArray);
That is obviously a waste of memory and CPU cycles. Usually not noticable, of course. But with large arrays or when frequently executed, it will add stress to the system.
There’s a very “cheap” way to get the first value of any given array. The reset function does just that. (end returns the last element.)
$firstElementOfArray = reset($array);
Now, reset will set the internal array pointer to the first value. However, unless your doing crazy things or writing sloppy code, you shouldn’t care about that anyway.
0
Code
array, PHP
February 24th, 2009 at 8:48 pm
There are some handy functions in PHP you would sometimes like to have in JavaScript, too. Why not reimplement them? It’s not hard. Take for example in_array() and explode():
function explode(delim, val_to_split)
{
return (val_to_split.indexOf(delim))
? val_to_split.split(delim)
: [val_to_split];
}
function in_array(needle, haystack)
{
hlength = haystack.length;
for (var i=0; i<length; i++)
{ if (needle == haystack[i])
{ return true; } }
return false;
}
Hint: On many pages of PHP functions, there are comments which describe how to reimplement a function (e.g. PHP 4 implementations of PHP 5 functions) — in PHP though, but it’s easy to adapt them for JavaScript.
0
Code
JavaScript, PHP
November 27th, 2008 at 12:53 pm
What is a dynamic variable, or a variable variable, as they are sometimes called? When you create a variable, you give it a name. Consider this PHP example:
<?php
$foo = 'test';
echo $foo;
?>
The first line will create the variable $foo and assign the string value ‘test’ to it. In the second line, the content of the variable $foo will be printed. So far, nothing exciting. But now consider this:
<?php
$bar = 'foo';
$$bar = 'test';
echo $foo.$bar;
?>
(Note the double $ sign at the beginning of the second line.) What happens here? First, the value ‘foo’ is assigned to the variable bar. In the second line, a variable is created, and this variable’s name will be the content of the variable $bar. This means, the variable $foo is created. Hence, the third line will output testfoo. You can also have dynamic variables in arrays and objects, even as function aliases:
<?php
$foobar = $foo[$bar];
$foobar = $foo->$bar;
// want to match case sensitive or not?
$stripos_func = ($casesensitive) ? 'strpos' : 'stripos';
var_dump( $stripos_func('ABC', 'ab') ); // true if $casesensitive==false
?>
0
Code
dynamic, PHP, variable
November 19th, 2008 at 12:29 pm
Here’s a snippet of PHP code that can create passwords. It can create passwords of different lengths, it can use different sets (uppercase and lowercase letters as well as numbers), and it can be told to exclude potentially confusing characters.
<?php
function passgen($length=8, $reqsets='uln', $noconfusing='true')
{
$length = (int)$length;
if ($length > 20 || $length < 3) $length = 8;
// some characters look alike. let's optionally exclude them.
$confusing = ($noconfusing === 'true') ? 'O01Il' : '';
$randchars = $token = '';
$sets = array(
'u' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'l' => 'abcdefghijklmnopqrstuvwxyz',
'n' => '0123456789'
// you can even add an own set
);
if ($reqsets)
{
$reqsets = str_split($reqsets);
foreach ( array_keys($sets) as $availset )
if ( in_array($availset, $reqsets) )
$randchars .= $sets[$availset];
}
if (!$randchars)
$randchars = implode($sets);
for ($i=0; $i<=$length; $i++)
{
do
{
$lpos = mt_rand( 0, strlen($randchars)-1 );
$letter = substr($randchars, $lpos, 1);
}
while ( in_array($letter, str_split($confusing) ) );
$token .= $letter;
}
return $token;
}
echo passgen($_GET['length'], $_GET['sets'], $_GET['noconfusing']);
?>
If you intend to use this in a script, please keep in mind that mt_rand() needs to be seeded/initialized properly.
0
Code
generator, password, PHP
December 18th, 2007 at 10:07 am
Here’s a simple HTML “compressor” in PHP, which will reduce the size of HTML served to the client by 10 to 20 percent, depending on your indentation style and commenting. If many of your readers have lousy bandwidth, the slight overhead of this method is worth it.
<?php
function compress($content)
{
$content = preg_replace('/[\n\t\s]+/s', ' ', $content);
$content = preg_replace('/<!--.*?-->/s', '', $content);
return $content;
}
ob_start();
require "/var/www/htdocs/somefile.php";
$content = ob_get_contents();
ob_end_clean();
echo compress($content);
?>
By the way, if you have a rather hungry dynamic application (e.g. WordPress with certain plugins) on a rather weak server, consider using a caching solution, so you don’t have to regenerate the pages everytime somebody retrieves them. And, of course, consider using output gzip compression – be it via webserver modules such as mod_gzip/mod_deflate or based on your web application.
0
Code
Compression, HTML, Loading Speed, PHP
December 11th, 2007 at 7:17 am
Sometimes you need to calculate the V.A.T. (for Germans: MwSt.) from a given total price. This is, for example, if you charge an arbitrary total price, but need to display the V.A.T. percentage along with the V.A.T. amount. For this purpose, you can use the following code:
<?php
function calc_vat_amount_from_total($total, $vat)
{
$total = (float)$total;
$vat = (float)$vat;
if (!$total || !$vat) return false;
$net = $total / (float)('1.'.$vat);
$vatAmount = $total - $net;
return sprintf("%01.2f", $vatAmount);
}
$total = '35.00'; // It's a string, but could also be a float or int.
$vat = '19'; // dito
$vat_amount = calc_vat_amount_from_total($total, $vat);
echo "The ticket fare of $total € contains $vat% V.A.T. ($vat_amount €).";
?>
0
Code
PHP, total, V.A.T.