RSS | Newer Entries ►

Handy PHP Shorts

1


I like simple things...things that require little effort on my behalf. Here are some php functions/"shorts" that will probably prove useful somewhere in your future.

Get META tag information from practically any website (works locally, too!)

$thetags = get_meta_tags ( 'PATH OR URL' );print_r ( $thetags);

Get a ton of information about a user's browser: (also check out phpsniff)

echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";$browser = get_browser(null, true);
print_r($browser);

Show the source of a file:

show_source("http://voolia.com");show_source(__FILE__);  //shows source of current file

Highlight source and number lines (great when you're stuck without an editor...no other use, in my opinion):

 
<style type="text/css">.line { float: left; color: gray; text-align: right; margin-right: 6pt; padding-right: 6pt; border-right: 1px solid gray;} </style>
 
<?php
function highlight_num($file)
{  echo '&lt;code class="line"&gt;', implode(range(1, count(file($file))), '&lt;br /&gt;'), '&lt;/code&gt;'; highlight_file($file); }
highlight_num('highlightfile.php');
?>

Create a very hard to guess unique id (impossible?) - php5 only:

 
$better_token = md5(uniqid(rand(), true));

Delay script execution (great for download scripts or advertising):

 
sleep(60); //in seconds.  this script will sleep for 1 minute as is.

Also check out time_sleep_until.

Print files in a directory:

 
$direct = dir('sample_directory/'); // the directory here
if ($direct)
{
while (false !== ($list = $direct-&gt;read())) {
if (!in_array($list, array('.', '..')))
{ echo "<a href='http://sampledomain.com/sample_directory/$list%5C%22'>$list</a>"; }
}
}

Read More


Avoiding sql injection attacks

1


While I'm most certainly no expert on the subject of mysql injection attacks, I do know that, unless you have a ton of valuable information stored in your database, the "hype" of attack prevention is just that: hype. Most scriptkiddies aren't going to waste their time pulling junk information from your database (and besides, you should have a cron job setup to do automatic backups of your databases on a regular basis.

This is all my personal opinion, of course. Any of my sites could suffer possible attack tonight...I wouldn't worry too much about it. Just simply restore the most recent backup and THEN work on prevention (I don't have anything that crucial stored in vulnerable databases)...

Despite the above, here's a very basic php function to possibly deter or prevent an sql injection attack:

Read More


Track outbound link stats easily

1


Ever wonder which links are the most popular on your site? I'm always curious which links receive the most attention and who I'm giving my traffic to so I developed this "quick-n-dirty" outbound link tracking script that runs from a mysql database (if you're still running flat file scripts, time for an update...no one does that anymore and haven't for a long time...shame on you).

tl.php (for tracklink...can be named anything, obviously)

 
<?
//KevinSmithDesigns.com
//connect
mysql_connect("localhost", "un", "pw") or die(mysql_error());
mysql_select_db("") or die(mysql_error());$url = $_GET['ksdurl'];
 
$comment = $_GET['ksdcomment'];
$dateadded = date('Y/m/d'); // 4 dig year, 2 dig month, and 2 dig day -- makes for the easiest and cleanest sorting later on!
 
//Check if url already exists WITH the specific comment...
$exist = mysql_query("SELECT * FROM links WHERE url='$url' AND comment='$comment'");
$doesit = mysql_fetch_object($exist);
if($doesit->url == $url) {
mysql_query("UPDATE links SET clicks=clicks+1 WHERE url='$url' AND comment='$comment'");
header("Location: $url");
} else {
 
//insert vars
$insertlinksquery = "INSERT INTO links (url, created, clicks, comment) VALUES ('$url', '$dateadded', '1', '$comment')";
$runinsertlinksquery = mysql_query($insertlinksquery) or die(mysql_error());
 
header("Location: $url");
}
 
?>
 

Now how to activate this script so that clicks are recorded: If you link to google.com, your new url would be: http://domain.com/tl.php?ksdurl=http://google.com. If you link to google multiple times and want to track each link, add a comment: http://domain.com/tl.php?ksdurl=http://google.com&ksdcomment=from about page Like always, this can be done better and more efficient. However, this is something I've quickly thrown together to track a few links simply to satisfy my curiosity. I'd suggest adding in $_SERVER['HTTP_REFERER'] to automatically track the source AND it would also be a good idea to use htaccess to automatically log links in tl.php...I'm just not going to take the time to do that. ----- You could customize the display of the stats to your own (mine is fairly detailed and complicated compared to the above script). Here's an example:

 
<?
$sortby1 = $_GET['sort'];
if($sortby1 == ''){ $sortby = 'id'; } else { $sortby = $sortby1; }
//don't forget to connect to the db
?>
<html>
<head>
<title>Link Tracker</title>
</head>
<body>
<font size="6" face="Verdana">Link Tracker</font><br>
<font face="Verdana" size="2">Currently sorting by <? echo $sortby; ?>.&nbsp; Reorder by: Sort by: <a href="stats.php?sort=id">ID</A> | <a href="stats.php?sort=url">URL</A> |<a href="stats.php?sort=created">Created</A> |<a href="stats.php?sort=clicks">Clicks</A> |<a href="stats.php?sort=comment">Comment</A></font>
<table border="1" width="850" cellspacing="0" bordercolor="#000000" bordercolorlight="#000000" bordercolordark="#000000">
<tr>
<td width="51" align="center" valign="top" bgcolor="#C0C0C0">
<p align="center"><font face="Verdana" size="1">ID</font></td>
<td width="72" align="center" valign="top" bgcolor="#C0C0C0"><font face="Verdana" size="1">CLICKS</font></td>
<td width="99" align="center" valign="top" bgcolor="#C0C0C0"><font face="Verdana" size="1">ADDED</font></td>
<td width="385" align="center" valign="top" bgcolor="#C0C0C0"><font face="Verdana" size="1">URL</font></td>
<td width="209" align="center" valign="top" bgcolor="#C0C0C0"><font face="Verdana" size="1">COMMENT</font></td>
</tr>
 
<?
$getlinks = mysql_query("SELECT * FROM links ORDER BY $sortby");
while($getlinks1 = mysql_fetch_array($getlinks)){
$id = $getlinks1['id'];
$url = $getlinks1['url'];
$added = $getlinks1['created'];
$comment = $getlinks1['comment'];
$hits = $getlinks1['clicks'];
echo "
<tr>
<td width=51 align=center><font face=Verdana size=1>$id</font></td>
<td width=72 align=center><font face=Verdana size=1>$hits</font></td>
<td width=99 align=center><font face=Verdana size=1>$added</font></td>
<td width=385 align=left><font face=Verdana size=1><a href=\"$url\">$url</a></font></td>
<td width=209 align=left><font face=Verdana size=1>$comment</font></td>
</tr>
 
";
}
echo "</table>
 
";
?>
</body>
</html>
 

And, finally, sample database structure:

CREATE TABLE `links` ( `id` MEDIUMINT(9) NOT NULL AUTO_INCREMENT, `url` TEXT NOT NULL, `created` VARCHAR(20) NOT NULL DEFAULT '', `clicks` VARCHAR(10) NOT NULL DEFAULT '', `comment` VARCHAR(255) NOT NULL DEFAULT '', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
 

Additions, comments, suggestions all welcome.

Read More


Simple 5 Star Rating System PHP/MySQL

9


All existing 5 star rating scripts are unneccessarily complicated. This is my idea (need to insert some form of spam protection -- just haven''t taken the time yet).

 
<?
/*
5 Item Rating Script
Kevin Smith KevinSmithDesigns.com
mozunk@gmail.com
*/
 
$ref = $_SERVER[''HTTP_REFERER'']; ?>
<form name="rate" action="ratedo.php" method="post">
<input type="hidden" name="ref" value="<? echo $ref; ?>" />
<input type="hidden" name="tehrater" value="<? echo $id; ?>">
<input type="radio" value="1" name="rate1">- 1
<input type="radio" name="rate1" value="2">2
<input type="radio" name="rate1" value="3">3
<input type="radio" name="rate1" value="4">4
<input type="radio" name="rate1" value="5">+ 5
<input type="submit" value="Rate!">
</form>
 
<br>
<?
$ratingquery1 = "SELECT AVG(rating) FROM ratings WHERE business='$id'";
$ratingresult1 = @mysql_query ($ratingquery1); // Run the query.
$ratingrow1 = mysql_fetch_array($ratingresult1);
$rating = $ratingrow1[0];
if ($rating >= 0 && $rating <= .4) { $stars = "0"; }
if ($rating >= .5 && $rating <= 1.4) { $stars = "1"; }
if ($rating >= 1.5 && $rating <= 2.4) { $stars = "2"; }
if ($rating >= 2.5 && $rating <= 3.4) { $stars = "3"; }
if ($rating >= 3.5 && $rating <= 4.4) { $stars = "4"; }
if ($rating >= 4.5 && $rating <= 6) { $stars = "5"; }
echo "<img src=\"/images/stars_$stars.gif\"> <b>$stars</b> Stars"; // if you don't want to show images, just remove the image tags
?>
 

-- ratedo.php (no multivote control)

 
<?
/*
5 Item Rating Script
Kevin Smith KevinSmithDesigns.com
mozunk@gmail.com
*/
 
mysql_connect("localhost","","");
mysql_select_db ("");
$rating = $_POST['R1'];
$businessid = $_POST['businessid'];
$ratingquery = "INSERT INTO ratings (rating, business, ip) VALUES ('$rating', '$businessid', '".$_SERVER['REMOTE_ADDR']."')";
$runratingquery = mysql_query($ratingquery);
$ref1 = $_SERVER['HTTP_REFERER'];
if ($ref1 == '') {
$ref = "http://domain.com";
} else {
$ref = $ref1;
?>
 

-- ratedo.php (multivote control)

 
<?
/*
5 Item Rating Script
Kevin Smith KevinSmithDesigns.com
mozunk@gmail.com
*/
 
mysql_connect("","","");
mysql_select_db ("");
$ref1 = $_SERVER['HTTP_REFERER'];
if ($ref1 == '') {
$ref = "http://domain.com";
} else {
$ref = $ref1;
}
$businessid = $_POST['businessid'];
//multiplevote control
$c = "SELECT * from `ratings` WHERE ip = '".$_SERVER['REMOTE_ADDR']."' AND business=$businessid";
$c2 = mysql_query($c);
while($c3 = mysql_fetch_object($c2)) {
$difference = time() - $c3->time;
if($difference < 604800) die("You have already voted.  <a href=\"$ref\">Go Back</a>");
}
$rating = $_POST['R1'];
$time = (time());
$ratingquery = "INSERT INTO ratings (rating, business, ip, time) VALUES ('$rating', '$businessid', '".$_SERVER['REMOTE_ADDR']."', '$time')";
$runratingquery = mysql_query($ratingquery);
?>
<br>
<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
<meta http-equiv="refresh" content="0;url=<? echo $ref; ?>">
<!-- or you could do a php header redirect...depends on what else is on your page / existing headers. -->
 

This code is untested -- if you try it and receive an error, post a comment or hunt it down yourself -- this is very basic stuff. Feel free to make improvements or changes...just don't take full credit.

Read More


Adding Appropriate Suffix to Numerical Value Via PHP

1


Comes in handy.

 
<? function addsuffix($number) {
 
if (!is_numeric($number)) return $number;
$number = floor(abs($number));
$suffixarray = array("th","st","nd","rd");
$numbersuffix = $suffixarray[0];
if (isset($suffixarray[substr($number,-1)]) (strlen($number) < 2 || substr($number,-2,1) != 1)) $numbersuffix = $suffixarray[substr($a,-1)];
return $number.$numbersuffix;
}
?>
 

Converts 1 to 1st, 2 to 2nd, 1837592348739832 to 1837592348739832nd, and so on.

Read More


RSS | Newer Entries ►