PHP Site Plugboard

February 27th, 2005 | 1 Comment

This Site Plugger Tutorial was contributed by Azekeal.
Right then – the following code should work – and it sets up the tables, you just need to fill in the variables in the database function

I’ve got it running at http://www.ofserin.com/pub/siteplug/ if you want to check it out.

//===== put in db.php =====================
<?php
class DB
{
var $link;
var $connected;

function DB()
{
register_shutdown_function( array( &$this, "_DB" ) );
$this->connected = false;
}

function connect()
{
$this->connected = true;

//***** Fill in your db stuff here *****
$host    = "localhost";
$db    = 'database';
$user    = 'username';
$pass    = 'p4Ssw0rD';

$this->link = mysql_connect($host, $user, $pass)
or die("Could not connect : ($host, $user) "
. mysql_error());
mysql_select_db($db) or die("Could not select
database");
}

function query($SQL, $singleResult = false)
{
if(!$this->connected)
$this->connect();

$result = mysql_query($SQL);
if($result === false)
{
$returnError = mysql_error();
echo "<b>Query failed : $returnError ($SQL)
[".__LINE__." | ".__FILE__."]</b><br>n";
return array();
}

// make an  array of data - mmm, nice code
for($data = array(); ($line = @mysql_fetch_array
($result, MYSQL_ASSOC)); $data[] = $line);

@mysql_free_result($result);

return ($singleResult===true && isset($data[0])
? $data[0] : $data);
}
function _DB() // destructor
{
if($this->connected)
@mysql_close($this->link);
}
}
$DB = new DB();

?>
//===== put in jsoutput.php =================
<?php

//---- javascript output functions
class JsOutput
{
var $data,
$func = '';

function JsOutput()
{
//header("Content-type: text/javascript");
ob_start();
}

function format($text)
{
return join("\n"+rn"",split("(rn|n)",
addslashes($text)));
}

function setFunc($func)
{
$this->func = $func;
}

function end($addData)
{
$this->data = ob_get_contents(); ob_end_clean();
echo '__data = "'.$this->format($this->data).'";';
if($this->func != '')
echo $this->func.($addData ? "(__data);" : ';');
}
};

?>
//===== put in siteplug.php ===================
<?php
include('jsoutput.php');
include('db.php');
$JsOutput = new JsOutput();

// number of sites to store
$numSites = 5;

// INITIALISE THE TABLES
$DB->query("
CREATE TABLE IF NOT EXISTS plugged_sites (
timestamp    DATETIME,
auth        VARCHAR(32),
addr        TINYTEXT,
IP            VARCHAR(15),
`desc`        TEXT,
img            TEXT
)
");

$DB->query("
CREATE TABLE IF NOT EXISTS pluggers_banned (
IP            VARCHAR(15)
)
");
// handy util func - gets from whatever method..
function getFormVar($var){ return isset($_POST[$var]) ?
$_POST[$var] : (isset($_GET[$var]) ? $_GET[$var] : false); }

// remove old sites where there are more than $numSites
$dat = $DB->query("SELECT * FROM plugged_sites ORDER BY
timestamp");
//print_r($dat);
$dat = $DB->query("SELECT * FROM plugged_sites ORDER BY
timestamp LIMIT $numSites,1",true);
if(!empty($dat))
$DB->query("DELETE FROM plugged_sites WHERE
timestamp<'$dat[timestamp]'");

//===== Show Listing =========================
if(getFormVar('listing') !== false) // asking for the listing?
{
$dat = $DB->query("SELECT * FROM plugged_sites ORDER BY
TIMESTAMP DESC");
echo "<div style='border: 1px solid black; padding: 5px;
width: 200px;'>";
foreach($dat as $site)
{
extract($site);
$imghref = (!empty($img)) ? "<img xsrc='$img'
border='0'>" : '';
$ahref = "<a xhref='".(strpos($addr,"http://")
!= 0 ? "http://$addr" : $addr)."'>$addr</a>";

//************** YOU CAN EDIT THIS BIT ******************
?>
<div style='border: 1px dotted black'>
<?= $imghref ?><br>
<span><?= $ahref ?></span>  <span>by <?= $auth ?></span><br>
<span style="font-size: x-small;"><?= $desc ?></span>
</div><br>
<?php
//******************** UP TO HERE ********************
    }
    echo "</div>";
}else{

    //===== Show/Update Form =====================
    $dat = $DB->query("SELECT * FROM pluggers_banned WHERE
 IP='$_SERVER[REMOTE_ADDR]'", true);
    if(empty($dat)) // not banned
    {
        $addr = getFormVar('addr');
        if($addr !== false) // did they submit a form?
        {
            $addr    = str_replace('\\','/',strtolower
($addr)) . "/";
            $addr    = eregi_replace("(http://)?(www.)?
([^/?+ ]+)(/+)","\\3",$addr);

            $dat = $DB->query("SELECT * FROM plugged_sites
 WHERE addr='$addr'", true);
            $img    = addslashes(getFormVar('img'));
            $auth    = addslashes(getFormVar('auth'));
            $desc    = addslashes(getFormVar('desc'));
            if(empty($dat) && !empty($addr))
            {
                // add site to list
      $dat = $DB->query("INSERT INTO plugged_sites
 (addr,auth,IP,`desc`, img, timestamp)
VALUES('$addr','$auth',
'$_SERVER[REMOTE_ADDR]','$desc', '$img',NOW())", true);
            }else{
            // already plugged their site (it's on the list)
                echo "your site has already been plugged
 (check listing).<br>\n";
            }
        }else{
            // show form
//************** YOU CAN EDIT THIS BIT *********************
- don't play around with the onclick function tho ^_~
?>
<form action="" method="get">
    Author: <input type="text" name="auth"><br>
    Img (optional): <input type="text" name="img"><br>
    Site URL: <input type="text" name="addr"><br>
    Description:<br>
    <textarea name="desc"></textarea><br>
    <input type="button" onClick="loadScript
('siteplug.php?auth='+escape(this.form.auth.value)

+'&addr='+escape(this.form.addr.value)
+'&img='+escape(this.form.img.value)+'&desc='+escape(this.
form.desc.value));" value="Submit">
</form>
<?
//******************** UP TO HERE **********************

        }
    }else{
        echo "sorry, you have abused the system and may no
longer plug your site.<br>\n";
    }

    $JsOutput->setFunc("setText('submitDiv',__data);loadScript
('siteplug.php?listing=true');");
    $JsOutput->end(false);
    exit();
}

$JsOutput->setFunc("setText('listingDiv',__data)");
$JsOutput->end(false);
?>

phew, that’s it for the PHP site – now, for the clientside…
put the following into dynload.js

 

//dynload.js

function getText(objId)
{
    obj = document.getElementById(objId);
    if(obj == null) error(obId + " doesn't exist");
    return (obj != null) ? obj.innerHTML.replace
(/^\s*|\s*$/g,"") : '';
}

function setText(objId, text)
{
    obj = document.getElementById(objId);
    if(obj != null)
        obj.innerHTML = text;
    else
        error(objId+" cannot be found");
}

function Engine()
{
    this.menumode = (navigator.userAgent.toLowerCase().
indexOf('safari') != -1);
    // create IFRAME NODE
    this.iframe = document.createElement("iframe");
    this.iframe.id = "__loadFrame";
    this.iframe.style.visibility    = "hidden";
    this.iframe.style.width            = "0px";
    this.iframe.style.height        = "0px";
    document.body.appendChild(this.iframe);

    this.Load = function(file)
        {
            tag = 'loadScript';
            if(arguments.length > 1)
                tag = arguments[1];

            if(!this.menumode)
            {
                scriptTag = document.getElementById(tag);

                bd = document.body;
                if(scriptTag)
                    bd.removeChild(scriptTag);
                script = document.createElement('script');
                script.type    = 'text/javascript';
                script.src    = file;
                script.id    = tag;

                bd.appendChild(script);
            }else{
                // iframes..
                obj = document.getElementById('__loadFrame');
                if(obj != null)
                    obj.src = file;
                else
                    error("can't find iframe __loadFrame to
 load page: "+ file);
            }
        };

    this.loadHTML = function(file)
        {
            // iframes..
            obj = document.getElementById('__loadFrame');
            if(obj != null)
                obj.src = file;
            else
                error("can't find iframe __loadFrame to load
 HTML: "+ file);
        };
}

var Engine = new Engine();

function loadScript(file)
{
    Engine.Load(file);
}

Almost there!… now, for the actual page you’re going to use it in – should
be very easy, put the following:

<script language="JavaScript" type="text/javascript"
 src="dynload.js" defer></script>

<div id="listingDiv">***Listing shows up here****</div>
<script language="JavaScript" type="text/javascript"
 src="siteplug.php?listing=true" defer></script><br><br>

<div id="submitDiv">***form shows up here***</div>
<script language="JavaScript" type="text/javascript"
 src="siteplug.php" defer></script>

that should now work! ^_^ – any problems?
dammit I’m getting slow in my old age – took me 2 hours to write and debug..

  • Share/Bookmark

Category: MySQL, PHP, Web Design

In Pink Pillows

February 18th, 2005 | Comments

Another great CLAMP series, Chobits, has the cutest and most adorable characters I’ve seen from CLAMP. This one features Chii and Freya.

made by licorne
Title: In Pink Pillows
Made by : Licorne
Series: Chobits
[ 800 x 600 ] [ 1024 x 747 ]

  • Share/Bookmark

Simple PHP Email Form

February 3rd, 2005 | Comments

Receive comments and feedback on your site the easy way by using just one file!

The following uses the PHP mail function to send emails easily via your website. Just copy and paste the code below and save it as email.php. Comments are written on the code itself. Make sure you have a PHP enabled host and that it supports the PHP mail function. If you are unsure you can always ask your host.

<?php

//your site header
include("header.php");

//what is the date when the form was submitted
$thedate = date("F j, Y");

//the email address where you want the emails sent to
$mailto="youremail@yourdomain.com";

//The subject of your email form
$subject="My Feedback Form";

//the title of your site
$sitename="Title of your Site";

//if the form has been submitted, handle it
if ($submitted) {

//if all the required fields were filled in,
if ($name && $mailfrom && $comments) {

//format the email message
$body="Hello! You have received the following information on your
site, $sitetitle!nn";
$body.="Name: $_POST[name]n";
$body.="Email: $_POST[mailfrom]n";
$body.="Date: $thedaten";
$body.="Comments: $_POST[comments]n";

$headers = "From: My Contact Form at $sitename
<youremail @yourdomain.com>n";
$headers .= "Reply-To: $_POST[email]";

//email the form
if (mail($mailto, $subject, $body, $headers)) {

//print out the success message
print ("<p>Congratulations! Your email has
been sent successfully! The Administrators will get back to you as soon
as possible. Thank you!</p> ");
}
//if there was a problem

else {

//print the error message
print ("  <p>Your email was not successfully sent due to a system
error!</p> ");
}
}
//if one of the required fields is missing
else {

//print out the error message
print ("
<p>You forgot to fill out a required field. Please go back
and try again!</p> ");
}
}
?>

//if form is not submitted, show the HTML form
<form action="email.php" method="post">

Name: <input name="name" size="40" type="text" />
Email address: <input name="mailfrom" size="40" type="text" />
Comments/Questions:<textarea name="body" rows="10" cols="40"></textarea>
<input name="submitted" value="true" type="hidden" />
<input name="submit" value="submit!" type="submit" />

</form>

//your site footer
include("footer.php");
?>
  • Share/Bookmark

Category: PHP, Web Design