Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

http://lordrich.com

« Newer Snippets
Older Snippets »
Showing 1-10 of 10 total  RSS 

Banning bad bots

The following code is the contents of /banme/index.php. This file is linked to from my main website but invisible to web browsers and disallowed in robots.txt. Therefore, only bad bots will ever follow this link and when they do so they will get banned in .htaccess and their ip address will be emailed to webmaster@example.com.

<?php
$i = getenv('REMOTE_ADDR');
$handle = fopen("../.htaccess", "a");
fwrite($handle, "Deny from $i\n");
fclose($handle);
echo "You've just got $i banned from this domain.  You are a very bad person.";
mail("webmaster@example.com", "Banned IP", "Deny from $i");
?>

Googleit WordPress Plugin

// description of your code here

<?php
/*
Plugin Name: Googleit
Plugin URI: http://lordrich.com/archives/2005/04/02/just-google-it/
Description: Link to google for the current title.  Usage: google_it();
Version: 0.1
Author: Richard Kirkcaldy
Author URI: http://lordrich.com
*/

function google_it(){
	$google = '<a href="http://www.google.com/search?q='.get_the_title().'">Google It</a>';
	echo $google;
	}
?>

Cerberus recent requesters

Display a list of email addresses for people who have filed tickets in the past 30 days.

<?php
$database = 'cerberus';
$username = 'cerberus';
$password = 'cerberus';
$hostname = 'localhost';

$sql = "
SELECT distinct address.address_address
FROM ticket, requestor, address
WHERE  DATE_SUB(CURDATE(),INTERVAL 30 DAY) <= last_update_date
AND ticket_status='resolved'
AND ticket.ticket_id=requestor.ticket_id
AND requestor.suppress='0'
AND requestor.address_id=address.address_id";

mysql_connect($hostname,$username,$password) or die('error connecting to the database');
@mysql_select_db($database) or die('unable to select database');
$result = mysql_query($sql) or die(mysql_error());
$num=mysql_numrows($result);
mysql_close();

$i = 0;
while($i < $num) {
	$address_address = mysql_result($result,$i,"address.address_address");
	echo "$address_address<br/>";
	$i++;
}
?>

Random Flickr Photo

// description of your code here

<?php

    // Displays a single random photo from recent flickr photos with a given tag.
    // Original code stolen from many sources including http://www.thebishop.net/geodog/archives/2004/09/29/fun_hacking_with_flickr_making_a_homemade_flickr_tag_badge_with_magpierss.html and http://prwdot.org/archives/002468.html


    // USER CONFIGURATION SECTION

    // MagpieRSS Configuration
    // This is an example based on my system;
    // you will need to customize it for your system
    // and your preferences. You can remove it entirely
    // if you have done it elsewhere
    // refer to http://magpierss.sourceforge.net/
    require_once('/var/www/bradford/magpierss-0.61/rss_fetch.inc');
    error_reporting(E_ERROR);
    define(MAGPIE_CACHE_ON, true);
    define(MAGPIE_CACHE_DIR, '/var/www/bradford/magpie_cache');
    define(MAGPIE_CACHE_AGE, 300);
    define(MAGPIE_CACHE_FRESH_ONLY, false);
    define(MAGPIE_DETECT_ENCODING, true);
    define(MAGPIE_DEBUG, 0);
    define(MAGPIE_FETCH_TIME_OUT, 15);
    define(MAGPIE_USE_GZIP, true);    

    // flickr configuration
    // How many photos you want to display
    $num_photos = 2; // for some reason it doesn't like 1
    $tag = 'Bradford';
    // URL for the flickr feed you want to use
    $flickr_feed_url ='http://www.flickr.com/services/feeds/photos_public.gne?tags='.$tag.'&format=rss_200';
?>

<?php
    // Fetch the feed
    $flickr = fetch_rss( $flickr_feed_url );
    if ($flickr) {
        $flickr_title = $flickr->channel["title"];
        $flickr_link = $flickr->channel["link"];
?>

<!-- Display the title and link to the feed -->

<?php
    // Pick some random photos
        $random_photos = array_rand($flickr->items,$num_photos);
        foreach ( $random_photos as $random_photo ) {
            $description = explode("\n\n",$flickr->items[$random_photo]["description"]);
?>

    <!-- Display the given photo -->

	<?php echo ereg_replace('<img src=(.*) width=(.*)>', '<img src=\\1 width="150px"/>', $description[1]);
	  die();?> // ok we've got our first photo - lets exit

<?php
        }
      } else {
?>

<!-- Display an error message if things didn't work -->
<p>An error occurred in the MagpieRSS parser:</p>

<p><?php echo magpie_error(); ?></p>

<?php
    } 
?>

PHP Web Crawler

Example output:

-bash-2.05b$ php asp.php
http://www.example.com
http://www.rfc-editor.org/rfc/rfc2606.txt
No links.

-bash-2.05b$ cat links.dat
http://www.example.com
http://www.rfc-editor.org/rfc/rfc2606.txt

<?php
$datafile = "links.dat"; // file to keep the list of links in
$regex = "/<\s*a\s+[^>]*href\s*=\s*[\"']?([^\"' >]+)[\"' >]/isU";  // regex to search for hrefs

$handle = fopen($datafile, "r"); // open the data file
$buffer = fgets($handle, 4096);
$oldlinks[] = $buffer; // read the first link into an array
while (!feof($handle)) {
	$buffer = fgets($handle, 4096);
	array_push($oldlinks,$buffer); // read the rest of the links into an array
}
fclose($handle); // close the data file

foreach($oldlinks as $value) { // for every link in the array
	print $value; // print it out
	$remote = fopen(trim($value), "r") or die(); //open it or fail nicely
	while (!feof($remote)) {
		$html = fread($remote, 8192); // read in the remote page
	}
	fclose($remote); // close it
	if (preg_match_all($regex, $html, $links)) { // if we find new links
		$local = fopen($datafile, "a+"); // open the data file
		foreach($links[1] as $value) { // for every new link
			$value.="\n"; // append a new line
			if(!in_array($value,$oldlinks)) { // if we haven't seen it before (nb - case sensitive)
				print($value); // print it out
				fwrite($local, $value); // and write it to file
			}
		}
		fclose($local); // close the data file
	}
	else {
		print("No links."); // we didn't find any links in the new file
	}
}
?>

Output feedwordpress database for use in Planet

You'll need to change the initial settings as I didn't bother to read them from the Wordpress config file. You may also need to change the table name (wp_links) in the sql query.

<?php
$username = "myuser";
$password = "P455w0rd";
$database = "db_name";
$hostname = "127.0.0.1";

$query = "SELECT link_name, link_rss FROM wp_links WHERE link_category=2";

mysql_connect($hostname, $username,$password);
@mysql_select_db($database) or die("Unable to select database");
$result = mysql_query($query);
$num = mysql_numrows($result);
mysql_close();

$i=0;
while($i < $num) {
        $rss = mysql_result($result,$i,"link_rss");
        $name = mysql_result($result,$i,"link_name");

        echo "[".$rss."]\r\n";
        echo "name = ".$name."\r\n";
        $i++;
}
?>

Feedwordpress mod

A simplified version of update-feeds.php from the Feedwordpress project. This version doesn't bother checking for authentication as there's really no point. It doesn't check whether it's being run at the commandline either, it simply assumes it is being called by wget as a cron job. This is designed to be run with version 0.98

<?php

// Help us to pick out errors, if any.
ini_set('error_reporting', E_ALL & ~E_NOTICE);
ini_set('display_errors', true);
define('MAGPIE_DEBUG', true);

// Are we running from a web request or from the command line?
                $update_feeds_display = 'text/plain';
                $update_feeds_invoke = 'post';
                $update_feeds_verbose = false;

require_once ('../wp-blog-header.php');

function update_feeds_mention ($feed) {
        global $update_feeds_display;

        if ($update_feeds_display=='text/html') :
                echo "<li>Updating <cite>".$feed['link/name']."</cite> from &lt;<a href=\""
                        .$feed['link/uri']."\">".$feed['link/uri']."</a>&gt; ...</li>\n";
        else :
                echo "* Updating ".$feed['link/name']." from <".$feed['link/uri']."> ...\n";
        endif;
        flush();
}

# -- Don't change these unless you know what you're doing...
define ('RPC_MAGIC', 'tag:radgeek.com/projects/feedwordpress/'); // update all

// Query secret word from database
$rpc_secret = get_settings('feedwordpress_rpc_secret');

header("Content-Type: {$update_feeds_display}; charset=utf-8");


        // Henceforward, we can proceed on the assumption that we have an authenticated user
        $uri = (isset($_REQUEST['uri']) ? $_REQUEST['uri'] : RPC_MAGIC.$rpc_secret);

        if ($update_feeds_display=='text/html') :
                echo <<<EOHTML
<?xml version="1.0" encoding="utf-8"?>
<html>
<head>
<title>update-feeds :: FeedWordPress</title>
</head>

<body>
<h1>update-feeds: make FeedWordPress check for new syndicated content</h1>

EOHTML;
        endif;

$feedwordpress =& new FeedWordPress;

if ($update_feeds_display=='text/html' or $update_feeds_verbose) :
        add_action('feedwordpress_check_feed', 'update_feeds_mention');
endif;

if ($update_feeds_display=='text/html') : // HTTP GET or HTTP POST: add some web niceties


        echo "<form action=\"\" method=\"POST\">\n";
        echo "<select name=\"uri\">\n";
        echo "<option value=\"".RPC_MAGIC.$rpc_secret."\">All feeds</option>\n";
        foreach ($feedwordpress->feeds as $feed) :
                echo "<option value=\"{$feed['link/uri']}\"";
                if ($feed['link/uri']==$_REQUEST['uri']) : echo ' selected="selected"'; endif;
                echo ">{$feed['link/name']}</option>\n";
        endforeach;
        echo "</select> ";
        echo "<input type=\"submit\" name=\"update\" value=\"Update\" />\n";
        echo "</form>\n";
endif;

if ($update_feeds_invoke != 'get') : // Only do things with side-effects for HTTP POST or command l
ine
        if ($update_feeds_display == 'text/html') : echo "<ul>\n"; endif;
        $delta = @$feedwordpress->update($uri);
        if ($update_feeds_display == 'text/html') : echo "</ul>\n"; endif;

        if (is_null($delta)) :
                if ($update_feeds_invoke == 'cmd') :
                        $stderr = fopen('php://stderr', 'w');
                        fputs($stderr, "update-feeds (".date('Y-m-d H:i:s')."): ERROR: I don't synd
icate <$uri>\n");
                elseif ($update_feeds_display == 'text/plain') :
                        echo "update-feeds (".date('Y-m-d H:i:s')."): ERROR: I don't syndicate <$ur
i>\n";
                else :
                        echo "<p><strong>Error:</strong> I don't syndicate <a href=\"$uri\">$uri</a
></p>\n";
                endif;
        elseif ($update_feeds_display=='text/html' or $update_feeds_verbose) :
                $mesg = array();
                if (isset($delta['new'])) : $mesg[] = ' '.$delta['new'].' new posts were syndicated
'; endif;
                if (isset($delta['updated'])) : $mesg[] = ' '.$delta['updated'].' existing posts we
re updated'; endif;
                if ($update_feeds_display=='text/html') : echo "<p>"; endif;
                echo "Update complete.".implode(' and', $mesg);
                if ($update_feeds_display=='text/html') : echo "</p>"; endif;
                echo "\n"; flush();
        endif;
endif;

if ($update_feeds_display=='text/html') : // HTTP GET or HTTP POST: close off web niceties
        echo <<<EOHTML

<p><a href="../wp-admin">&larr; Return to WordPress Dashboard</a></p>
</body>
</html>
EOHTML;
endif;
?>

Random quotes

Called as quotes.php it will display a single random quote. Called as quotes.php?all=1 it will display all quotes in an unordered list. No database is required, and it should be fairly obvious how to add new quotes.

<?php
$quotes[] = "Boys like hugs too.";
$quotes[] = "Ooh! Train!";
$quotes[] = "La rue est a nous.";
$quotes[] = "The future is unwritten.";

if($all==1) {
        echo "<ul>";
        for($i=0; $i<=count($quotes)-1; $i++) {
                echo "<li>".$quotes[$i]."</li>";
        }
        echo "</ul>";
} else {
        srand ((double) microtime() * 1000000);
        $randomquote = rand(0,count($quotes)-1);
        echo $quotes[$randomquote];
}

?>

Textpattern - display log by hostname


<html>
<head>
<link href="/textpattern/textpattern.css" rel="Stylesheet" type="text/css" />
</head>
<body>
<?php
require_once("textpattern/config.php");
mysql_connect($txpcfg['host'], $txpcfg['user'], $txpcfg['pass']) or die(mysql_error());
mysql_select_db($txpcfg['db']) or die(mysql_error());

// Quote variable to make safe
function quote_smart($value)
{
   // Stripslashes
   if (get_magic_quotes_gpc()) {
       $value = stripslashes($value);
   }
   // Quote if not a number or a numeric string
   if (!is_numeric($value)) {
       $value = mysql_real_escape_string($value);
   }
   return $value;
}
$sql = "SELECT * FROM " .$txpcfg['table_prefix'] ."txp_log WHERE host LIKE '%" .quote_smart($_GET['host']) ."%' ORDER BY 'time' DESC LIMIT 0, 30 ";
$result = mysql_query($sql) or die(mysql_error());
echo "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" id=\"list\" align=\"center\">";
echo "<tr><td><b>Time</b></td><td><b>host</b></td><td><b>page</b></td></tr>";
while($row = mysql_fetch_array($result))
{
 echo "<tr><td>".$row['time']."</td><td>".$row['host']."</td><td>".$row['page']."</td></tr>";
}
echo "</table>";
?>
</body></html>


Test message for valid PGP encryption

This code is designed to check whether the parsed text is a valid PGP encrypted message. It's relatively easy to fool, but not much can be done about that.

<?php
# vim: ft=php

function is_pgp($my_string) {

$begin =  strpos($my_string, "-----BEGIN PGP");
if ($begin === false) {
 return false;
}

$sign = strpos($my_string, "----BEGIN PGP SIGN");
if ($sign !== false) {
 return false;
}

$blank = strpos($my_string, "\r\n\r\n");
if ($blank === false) {
 return false;
}

$end = strpos($my_string, "----END");
if ($end === false) {
 return false;
}
if ($end < $begin) {
 return false;
}

return true;
}
?>

<html>
<head><title>is_php</title></head>
<body>
<p>

<?php
if ($_POST['message'] != "") {
if(is_pgp($_POST['message'])==true) {
 echo "I think the following text is a valid pgp encrypted message";
 } else {
 echo "The following text does not validate as a pgp encrypted message";
 }
} else {echo "use the following form to test whether text is pgp encrypted"; }
?>

</p>
<form action=pgp.php method="post">
<textarea name="message"  rows="20" cols="60" wrap="virtual">
<?php echo($_POST['message']); ?>
</textarea>
<input type="submit" value="validate text">
</form>
</body>
</html>

« Newer Snippets
Older Snippets »
Showing 1-10 of 10 total  RSS