Category Archives: Affiliate Programs

PHP Affiliate Jump Scripts

We all know that the big Affiliate Networks including Commission Junction, Linkshare and Tradedoubler are having problems with their links being blocked by third party programs such as Norton Antivirus. This is causing major problems in the Affiliate Marketing World as computers which run these program can not access click through links or banners, therefore not being able to produce a sale for Merchants who are promoted through these networks. By using a ‘Jump Script, we can bypass this issue.

 

<?PHP
// This script is to be used with the Affiliate Jump Tutorial at www.stevedawson.com/articles.php
/************************************************************************/
/* PHP Affiliate Jump Script                                             */
/* ===========================                                          */
/*                                                                      */
/*   Written by Steve Dawson - http://www.stevedawson.com               */
/*   Freelance Web Developer - PHP, MySQL, HTML programming             */
/*                                                                      */
/* This program is free software. You can redistribute it and/or modify */
/* but please leave this header intact, thanks                          */
/************************************************************************/
/*
Save this page as jump.php and when linking to this script use the following:
<a href="jump.php?m=XXXXXX">XXXXXX</a>
Where XXXXXX is your merchant.
*/

$m = $_GET['m'];
if ($m == "") {$link = "http://www.stevedawson.com/mobiles/";} // Default Blank
if ($m == "Just Phones") {$link = "http://www.awin1.com/awclick.php?mid=97&amp;id=38362";}
if ($m == "UKPhoneShop") {$link = "http://tracker.tradedoubler.com/click?p=985&amp;a=949731&amp;g=5119";}

/*
To add more jump links, just copy and paste one of
the lines above and modify the $m and $link values
*/


header("Location: $link"); // Jump to the hiddden affiliate URL above
exit();
?>



&amp;nbsp;

Simple PHP Password Protect Script

Do you want to have a hidden page on your website which only people who you give the password to can access it? Most probably you do as we all have something that we want to hide from prying eyes, that is were this PHP password protect page will come in useful Surprisingly, there are still quite a few hosts that do not allow you to use .htaccess and .htpasswd files to create password protected areas on your website. To overcome this, we can use basic PHP to protect a page and keep our content hidden.The beauty of this script is that it can be included into any page design and be used to protect just certain areas of a webpage or a full page.The Simple Password Protect script is written in PHP and will run on any server which supports this. You do not need to use a database, just the simple PHP code which is included in the zip file.

 

<?php
/************************************************************************/
/* PHP Simple PasswordProtect v1.0                                      */
/* ===========================                                          */
/*                                                                      */
/*   Written by Steve Dawson - http://www.stevedawson.com               */
/*   Freelance Web Developer - PHP, MySQL, HTML programming             */
/*                                                                      */
/* This program is free software. You can redistribute it and/or modify */
/* but please leave this header intact, thanks                          */
/************************************************************************/
##########################################################################
$password = "admin";  // Modify Password to suit for access, Max 10 Char.
##########################################################################
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Simple Password Protect - PHP PasswordProtect</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
<!--
P { FONT-SIZE: 8pt; COLOR: #000000; FONT-FAMILY: Verdana, Tahoma, Arial}
TD { FONT-SIZE: 8pt; COLOR: #000000; FONT-FAMILY: Verdana, Tahoma, Arial}
-->
</style>
</head>
<body>
<?php
print "<h2 align=\"center\">PHP Simple Password Protect</h2>";
// If password is valid let the user get access
if (isset($_POST["password"]) &amp;&amp; ($_POST["password"]=="$password")) {
?>
<!-- START OF HIDDEN HTML - PLACE YOUR CONTENT HERE -->

<p align="center"><br><br><br>
<b>Congratulations</b><br>you have gained access to the Protected and Secret Area!</p>

<!-- END OF HIDDEN HTML -->
<?php
}
else
{
// Wrong password or no password entered display this message
if (isset($_POST['password']) || $password == "") {
print "<p align=\"center\"><font color=\"red\"><b>Incorrect Password</b><br>Please enter the correct password</font></p>";}
print "<form method=\"post\"><p align=\"center\">Please enter your password for access<br>";
print "<input name=\"password\" type=\"password\" size=\"25\" maxlength=\"10\"><input value=\"Login\" type=\"submit\"></p></form>";
}
print "<br><br><p align=\"center\">Written by <a href=\"http://www.stevedawson.com\">SteveDawson.com</a></p>";
?>
<BR>
</body>
</html>

 

 

Sam scripts for received its first visitors

Samscripts received its first visitors today after my script ‘gimmeCache’ appeared on the phpclasses website. A bit of a shock to see the number of visitors go from 1 (myself) to several hundred in a few hours, but all good really.Over the next few weeks I will start adding more scripts and articles to this site, but right now I am concentrating on getting my template system working.

 

 

<?php
session_start();
require_once(dirname(__FILE__).'/samswhois/secureimagecode.class.php');


$secure = new secureimagecode();
$img = $secure->GenerateImage();
header("content-type: image/png");
imagepng($img);
exit();
?>

&amp;nbsp;

Scripts for commercial e-books or outright scam

“Stalemate” asked in http://www.phpcentral.com/40-e-books-php.html for links to free PHP e-books, so I started digging around a bit for him hoping to be helpful. The vast majority of the leads were to commercial e-books or outright scam pages set up for SEO purposes, but then I came across a post in Sam’s Blog. He’s basically already done the work I hoped to do, and he did it very well. His post is a good sized listing of titles and descriptions of free PHP e-books, with direct links for downloading them at no charge. I thought his excellent work deserved a thread of its own, and I have quoted the e-book titles/descriptions but you will have to visit Sam’s entry to get the links.

 

 

<?php
/*

File: samswhois.inc.php
Purpose: simple interface to using the samswhois.class.php file

Copyright (c) 2004, 2008 Sam Yapp
http://www.phpace.com/scripts/sams-whois

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/


/***********************************************
Section 1 - Initialization...
************************************************/


/*
include the samswhois class file. You can use this class directly in your scripts if you want
more control...
*/


require_once(dirname(__FILE__).'/samswhois.class.php');

/* create a new samswhois object */

$whois = new SamsWhois();

/*
initialize any of the variables that we use.
You can set any of these values in the script that includes this one to override
the values below.
*/


if( !isset($swHilite) ) $swHilite = 'no';    // hilight fields in the whois output (eg. status, nameservers, etc)
if( !isset($swClean) ) $swClean = 'no';    // "clean" the whois output of extraneous text
if( !isset($swAuth) ) $swAuth = true;    // check the authoritative whois server for com &amp; net
if( !isset($swOnlyShowAuth) ) $swOnlyShowAuth = false;    // if checking authoritative, should we ignore the registry whois?
if( !isset($swSecure) ) $swSecure = false;    // generate a security code for each whois lookup
if( !isset($swListTlds) ) $swListTlds = false;    // list the supported tlds underneath the lookup form
if( !isset($swTldOptions) ) $swTldOptions = false;    // let the user select the tld from a drop-down list
if( !isset($swAlphabeticalTlds) ) $swAlphabeticalTlds = false;    // list tlds alphabetically?
if( !isset($swTlds) ) $swTlds = '';    // limit the tlds supported to those in a comma separated list eg 'com,net,org'
if( !isset($swDefaultTld) ) $swDefaultTld = 'com';    // the default tld to use / display in the form
if( !isset($swDefaultSld) ) $swDefaultSld = 'domain';    // the default sld to display in the form
if( !isset($swCacheLifetime ) ) $swCacheLifetime = 0; // the length of time in minutes to cache whois lookup results
if( !isset($swOnlyShowAvailability) ) $swOnlyShowAvailability = false;    // only show availability, no whois data

/*
initialize any messages to display that aren't already set in the script that includes this one
*/


if( !isset($swSubmitLabel) ) $swSubmitLabel = 'Check Domain';    // the submit button label for the whois form

if( !isset($swInstructions) ){        // instructions displayed under the form - differ slightly if the user can choose the tld
if( $swTldOptions ){
$swInstructions = 'Enter a domain name and select a tld from the box above.';
}else{
$swInstructions = 'Enter a domain name including extension in the box above.';
}
}

if( !isset($swSecurityError) ){    // error message displayed if the user doesn't enter the security code when required
$swSecurityError = 'For security reasons, you MUST enter the 4 digit code shown above.';
}

if( !isset($swLookupError) ){    // error message displayed if a whois lookup query fails
$swLookupError = 'Sorry, an error occurred.';
}

if( !isset($swSecurityMessage) ){    // message displayed below the form when a security code is required
$swSecurityMessage = 'For security purposes, please also enter the 4 digit code.';
}

if( !isset($swTldError) ){    // message displayed if the user enters a tld that is not supported
$swTldError = 'Sorry, that tld is not supported.';
}

if( !isset($swHeadingText) ){ // displayed above the form - could replace with a logo image or the name of your site
$swHeadingText = 'Whois Lookup';
}

/*
Set any variables in the SamsWhois class that have been set in the script that includes this one.
*/


$whois->SetCacheLifetime($swCacheLifetime);

if( isset($swAvailableMessage) ){    // the message displayed when $whois->GetStatusText() is called and the domain is available
$whois->SetAvailableMessage($swAvailableMessage);
}

if( isset($swRegisteredMessage) ){ // message displayed when $whois->GetStatusText() is called and the domain is registered
$whois->SetRegisteredMessage($swRegisteredMessage);
}

if( isset($swServerText) ){    // message displayed when $whois->GetServerText() is called - {server} is replaced by the server name
$whois->SetServerText($swServerText);
}

if( isset($swAuth) &amp;&amp; $swAuth == true ){ // tell the script whether to lookup com &amp; net at the authoratitive server
$whois->m_redirectauth = true;
}

/*
Security code image
if we are using a secure image code, include the class and create a secureimagecode object for later use
*/


if( $swSecure ){

require_once(dirname(__FILE__).'/secureimagecode.class.php');

$secure = new secureimagecode();
}

/*
limit the tlds to use (if set in the script that includes this one)
$swTlds should be in the form 'com,net,org' where the tlds are the ones to use.
*/


if(  $swTlds != '') $whois->SetTlds($swTlds);

/*
Initialize some variables used in the rest of the script
*/


$tld = $swDefaultTld;    // the tld
$sld = $swDefaultSld;    // the sld
$domain = '';    // this will be displayed as the value of the domain <input> in the form - it is set later on
$nocode = false;    // will be set to true later if the user submits the form without a correct security code (if required)
$dolookup = false;    // set later if the lookup form has been submitted with a valid domain / tld.

/*
Determine whether to automatically clean whois output. If $swClean = 'optional', checks if the user wants this.
*/


switch( $swClean ){
case 'yes': $sw_clean = true; break;
case 'optional': $sw_clean = isset($_REQUEST['clean']) ? true : false; break;
default: $sw_clean = false; break;
}

/*
Determine whether to hilight certain rows of the whois output. If $swHilite = 'optional', checks if the user wants this.
*/


switch( $swHilite ){
case 'yes': $sw_hilite = true; break;
case 'optional': $sw_hilite = isset($_REQUEST['hilite']) ? true : false; break;
default: $sw_hilite = false; break;
}

/*
Check if the user has submitted the lookup form
*/


if( isset($_REQUEST['lookup']) &amp;&amp; isset($_REQUEST['domain'])){

$dn = trim($_REQUEST['domain']);

if( $dn != '' ){

// separate the sld and tld, checking for a submitted tld if $swTldOptions = true
$dot = strpos($dn, '.');
if( $dot !== false ){
$sld = substr($dn, 0, $dot);
$tld = substr($dn, $dot+1);
}else{
$sld = $dn;
if( $swTldOptions &amp;&amp; isset($_REQUEST['tld']) ) $tld = trim($_REQUEST['tld']);
}

$domain = $sld.'.'.$tld;

if( $whois->ValidDomain($domain) ){ // check that it is a valid domain
$dolookup = true;

if( $swSecure ){    // if we are using a secure code, check the user has entered it correctly
if( !$secure->CheckCode($_REQUEST['code']) ){
$nocode = true;
$swErrorMessage = $swSecurityError;
$dolookup = false;
}
}
}else{
$swErrorMessage = $swTldError;
}
}
}

/*
Set the domain variable to the correct value (either with or without tld) for later output in the form
*/


if( $swTldOptions ){
$domain = $sld;
}else{
$domain = $sld.'.'.$tld;
}

/***********************************************
Section 2 - Display the whois lookup form

Depending on what options have been set in the calling script, the form may contain
various messages, a drop-down box to select the tld, and checkboxes.

************************************************/


?>
<div>
<br />
<form id="whoisform" name="whoisform" style="margin: 0px;" action="<?php echo $_SERVER['SCRIPT_NAME'];?>" method="get">
<div>
<div><?php echo $swHeadingText;?></div>
<?php
?>
<input type="text" name="domain" value="<?php echo $domain;?>" onFocus="this.select();" />
<?php
if( $swTldOptions){    // if listing tlds as a <select> box
?><b>.</b> <select name="tld"><?php echo $whois->TldOptions($tld,$swAlphabeticalTlds);?></select><?php
}
if( $swSecure ){ // should we get the user to enter a security code?
$secure->GenerateCode();
?>
<input type="text" name="code" />
<img align="absmiddle" src="swsecureimage.php" />
<?php
}
?>
<input type="submit" name="lookup" value="<?php echo $swSubmitLabel;?>" />
<div>
<?php
if( $swClean == 'optional' ){ // if cleaning is optional, give the user the option...
?>
<input type="checkbox" name="clean" value="1" <?php if( $sw_clean ) echo 'CHECKED';?> />
<b>Clean whois output?</b>
<?php
}
if( $swHilite == 'optional' ){ // if whois output hilighting is optional, give the user the option...
?>
<input type="checkbox" name="hilite" value="1" <?php if( $sw_hilite ) echo 'CHECKED';?> />
<b>Hilight Important Fields?</b>
<?php
}
if( $swHilite == 'optional' || $swClean == 'optional' ) echo '<br />';
echo $swInstructions;
if( $swListTlds){    // list all supported tlds.
echo '<br />Supported Tlds: '.join(', ', $whois->GetTlds($swAlphabeticalTlds)).'.';
}
if( $swSecure ){    // display the message about the security code
echo "<br />".$swSecurityMessage."<br />";
}
?>
</div>
<?php
if( isset($swErrorMessage ) ){     // display any error messages...
?><div><?php echo $swErrorMessage;?></div><?php
}
?>
</div>
</form>
<!--
a little bit of javascript that sets the keyboard focus to either the domain field,
or the security code field if the user has just submitted the form without entering
the correct value.
-->
<script language="JavaScript" type="text/javascript">
<!--
document.forms['whoisform'].<?php echo $nocode == true ? 'code' : 'domain';?>.focus();
//-->
</script>
<?php

/***********************************************
Section 3 - Do the whois lookup
************************************************/


if( $dolookup == true ){ // form submitted, all ok

if( $whois->Lookup($sld.'.'.$tld) ){ // do the lookup
?>
<div>
<table style="border: 0px;" align="center">
<tr>
<td style="font-size: 10pt; font-family: verdana, arial;">
<div>
<?php
echo $whois->GetStatusText(); // display the domain's status
?>
</div>
<?php
/*
Display the whois data, formatting it for display as html
We pass the values for cleaning and hilighting whois output to the GetData() function.
The number argument passed to the GetData() and GetServerText() functions indicates
which lookup result we want for com and net domains where there may be an additional result
from the authoratitive server.
*/


if( !$swOnlyShowAvailability ){

$data = $whois->GetData(0, $swClean, $swHilite);
if( $whois->GetServerCount() == 2 ){
if( $swOnlyShowAuth ){
$output = '<div>'.$whois->GetServerText(1).'</div>'."\n";
$output .='<div>'.nl2br($whois->GetData(1, $sw_clean, $sw_hilite)).'</div>'."\n";
}else{
$output = '<div>'.$whois->GetServerText(1).'</div>'."\n";
$output .='<div>'.nl2br($whois->GetData(1, $sw_clean, $sw_hilite)).'</div>'."\n";
$output .= '<div>'.$whois->GetServerText(0).'</div>'."\n";
$output .='<div>'.nl2br($whois->GetData(0, $sw_clean, $sw_hilite)).'</div>'."\n";
}
}else{
$output = '<div>'.$whois->GetServerText(0).'</div>'."\n";
$output .='<div>'.nl2br($whois->GetData(0, $sw_clean, $sw_hilite)).'</div>'."\n";
}
echo $output;
}
}else{
// an error occurred with the whois lookup...
?>
<div>
<?php echo $swLookupError;?>
</div>
<?php
}
?>
</td>
</tr>
</table>
<?php
}

// and thats it :)

?>
<div style="margin-top: 30px; text-align: center; font-size: 10px; color: #aaaaaa;">Powered by <a style="color: #aaaaaa; text-decoration: none;" target="_blank" href="http://whois.samscripts.com/">Sams Whois</a></div>
</div>

&amp;nbsp;

PHP Scripts for PHP Navigator sam

This is a Web based open source file management system in PHP and AJAX. With Windows XP style & icons. You will feel you are on Windows!Features: – User friendly Explorer style navigation and view. Fully customizable. – Advanced AJAX & DOM to avoid

 

 

<?php
#---------------------------
# PHP Navigator 4.3
# dated: September 25, 2007
# Coded by: Cyril Sebastian,
# Kerala,India
# web: navphp.sourceforge.net
#---------------------------

#----------OTHER FUNCTIONS-------


function upload($dir)
 {
 global $msg,$uploads;
 #-----Calculate Max Upload Size--
$size_str = ini_get('upload_max_filesize');
 $i=0;
 while(ctype_digit($size_str[$i])) {$size.=$size_str[$i]; $i++;}
 if($size_str[$i]=="M"||$size_str[$i]=="m") $size = $size*1024*1024;
 else if($size_str[$i]=="K"||$size_str[$i]=="k") $size = $size*1024;
 else $size = 1024*1024*1024;

 #----Start Upload--
for($i=0;$i<=$uploads;$i++)
 if($_FILES['upfile']['name'][$i]!="")
 {
 if ($_FILES['upfile']['size'][$i]!=0 and $_FILES['upfile']['size'][$i]<=$size)
 {
 $file=$_FILES['upfile']['name'][$i];
 $uploadfile = $dir."/".$file;
 if(move_uploaded_file($_FILES['upfile']['tmp_name'][$i], $uploadfile))
 $msg[]="$file uploaded";
 else
 $msg[]="Upload failed for $file!";
 }
 else
 $msg[]="Upload failed for $file due to exceeding file size limits, or zero length file!";
 }
 }

function view_code($file,$dir)    // calling code editor
 {
 $data=pathinfo($file);
 $ext=strtolower($data["extension"]);
 if($ext=="htm"||$ext=="html"||$ext=="xml"||$ext=="shtml"||$ext=="mht") {
 $lan="html";
 }
 else if($ext=="js") {
 $lan="javascript";
 }
 else if($ext=="php"||$ext=="php3"||$ext=="php4"){
 $lan="php";
 }
 else if($ext=="c"||$ext=="cpp"){
 $lan="generic";
 }
 else if($ext=="css") {
 $lan="css";
 }
 else if($ext=="sql") {
 $lan="sql";
 }
 else if($ext=="java") {
 $lan="java";
 }
 else {
 $lan="text";
 }

 global $msg, $max_edit_size, $deflate;
 if(filesize("$dir/$file")>$max_edit_size)
 print"File size exceeds the limit of $max_edit_size bytes<br>Have the Site Admin edit config.php to customize this";
 else
 {print"<b><center>$dir/$file</center></b>
 <style>body{background-color:ThreeDFace;}</style><center>"
;
 print("<script src=\"code_editor/codepress.js\" type=\"text/javascript\"></script>
 <script language=\"javascript\" type=\"text/javascript\">
 function submitform()
 {
 dataBox.toggleEditor();
 return(true);
 }
 </script>
 <form action='windows.php' method=POST>
 <textarea rows=22 cols=80 class=\"codepress $lan\" id='dataBox' name='data'>"
.htmlentities(file_get_contents("$dir/$file"))."</textarea>
 <input type=hidden name=dir value='"
.base64_encode($dir)."'>
 <input type=hidden name=file value='"
.base64_encode($file)."'>
 <input type=hidden name=action value=Save><br>
 <input type=Submit value=Save onclick=submitform();>
 <input type=button onClick='history.back()' value=Back></form>
 <script language=JavaScript>
 function fixResize(){
 xObj = document.getElementById('dataBox');
 xObj.style.width = document.body.clientWidth-40;
 xObj.style.height = document.body.clientHeight-100;
 }
 fixResize();
 </script></center>"
);
 }
 if($deflate){
 $data= ob_get_clean();
 echo gzdeflate($data);}
 }


function view($file,$dir)    //for unsupported browsers
 {
 global $msg, $max_edit_size, $deflate;
 if(filesize("$dir/$file")>$max_edit_size)
 print"File size exceeds the limit of $max_edit_size bytes<br>Have the Site Admin edit config.php to customize this";
 else
 {print"<b>$dir/$file</b><center>";
 print("<style>body{background-color:ThreeDFace;}</style>
 <form action='' method=POST>
 <textarea rows=22 cols=80 name=data id=dataBox>"
.htmlentities(file_get_contents("$dir/$file"))."</textarea>
 <input type=hidden name=dir value='"
.base64_encode($dir)."'>
 <input type=hidden name=file value='"
.base64_encode($file)."'><br>
 <input type=submit name=action value=Save>
 <input type=button onClick='history.back()' value=Back></form>
 <script language=JavaScript>
 function fixResize(){
 xObj = document.getElementById('dataBox');
 xObj.style.width = document.body.clientWidth-40;
 xObj.style.height = document.body.clientHeight-100;
 }

 fixResize();
 </script></center>"
);
 }
 if($deflate){
 $data= ob_get_clean();
 echo gzdeflate($data);}
 }

function save($file)
 {
 global $msg;
 if(get_magic_quotes_gpc()){
 $data = stripslashes($_POST['data']);
 } else {
 $data = $_POST['data'];
 }
 $f=fopen($file,"w");
 if(fwrite($f,$data)) $msg= "File $file saved!";
 fclose($f);
 }


function fileicon($file)
 {
 $data=pathinfo($file);
 $ext=strtolower($data["extension"]);
 global $thumb, $dir;

 if($ext=="htm"||$ext=="html"||$ext=="xml"||$ext=="shtml"||$ext=="mht"||$ext=="phtml")
 $img="web.gif";
 else if($ext=="cgi"||$ext=="pl"||$ext=="sql"||$ext=="txt"||$ext=="cf"||$ext=="asp"||$ext=="aspx"||$ext=="jsp"||$ext=="py")
 $img="cgi.gif";
 else if($ext=="zip"||$ext=="rar"||$ext=="gz"||$ext=="tar"||$ext=="tgz"||$ext=="bz2")
 $img="zip.gif";
 else if($ext=="exe"||$ext=="bin"||$ext=="bat"||$ext=="sh"||$ext=="com"||$ext=="dll")
 $img="bin.gif";
 else if($ext=="doc"||$ext=="pdf"||$ext=="ps"||$ext=="odf"||$ext=="docx")
 $img="doc.gif";
 else if($ext=="js"||$ext=="vbs")
 $img="js.gif";
 else if($ext=="css")
 $img="css.gif";
 else if($ext=="php"||$ext=="php3")
 $img="php.gif";
 else if($ext=="psd"||$ext=="svg"||$ext=="gd"||$ext=="gd2"||$ext=="gd2part"||$ext=="iff"||$ext=="swf"||$ext=="swc"||$ext=="tif"||$ext=="tiff"||$ext=="xpm")
 $img="image.gif";
 else if($ext=="gif"||$ext=="jpg"||$ext=="jpeg"||$ext=="png"||$ext=="bmp")
 {
 if($thumb)
 {
 $info = @getimagesize($file);
 if(!$info) $img="image.gif";
 else if($info[2]==1||$info[2]==2||$info[2]==3||$info[2]==15)
 {
 $img = "thumb.php?img=".urlencode("$dir/$file");    //thumbnail path
 return $img;
 }
 }
 $img="image.gif";
 }
 else
 $img="file.gif";
 return $img;
 }


 function up($dir)
 {
 $dir = base64_decode($dir);
 global $homedir,$restrict_to_home;

 $dirup = substr($dir,0,-1);
 $pos = strrpos($dir, "/");
 if($pos===false) $pos = strrpos($dir, "\\"); #for windows

 if($pos!=0) $up = substr($dir,0,-(strlen($dir)-$pos));
 else $up="/";
 if(strpos($up,$homedir)!==0) $up=$homedir; #restrict to home dir!
chdir($up);
 }


function printbuttons($dir,$i)
{
 global $homedir;

 if($_COOKIE['navphp_arrange']=="type") $arr_type="selected";
 else if($_COOKIE['navphp_arrange']=="size") $arr_size="selected";
 else $arr_name="selected";

 print"<a href= './'><img src=images/home.gif title=Home></a>
 <a href= 'windows.php?action=Up&amp;dir="
.base64_encode($dir)."'><img src=images/up.gif border='0' title=Up></a>
 <img src=images/reload.gif onClick='gotodir(f)' title='Refresh'>
 <img width=1 height=24>
 <img src=images/copy.gif onClick='copy(f)' title='Copy [Shift+Ctrl+C]'>
 <img src=images/delete.gif onClick='delet(f)' title='Delete [Shift+Ctrl+X]'>
 <img src=images/rename.gif onClick='rename(f)' title='Rename [F2]'>
 <img width=1 height=24>
 <img src=images/newfolder.gif  onClick='newfolder(f)' title='New Folder [Shift+Ctrl+N]'>
 <img src=images/newfile.gif  onClick='newfile(f)' title='New File [Shift+Ctrl+F]'>
 <img width=1 height=24>"
;
 if($i==0) print"<select name='mode' style='margin-top:2px; vertical-align:top;'>
 <option value=0777>777</option>
 <option value=0770>770</option>
 <option value=0755 selected>755</option>
 <option value=0750>750</option>
 <option value=0666>666</option>
 <option value=0660>660</option>
 <option value=0644>644</option>
 <option value=0600>600</option>
 <option value=755>default</option>
 <option value=666>readonly</option>
 <option value=777>readwrite</option>
 </select>
 <img src=images/chmode.gif  onClick='chmode(f)' title='Change Permissions'>
 <img width=1 height=24>
 <select name='arr' style='margin-top:2px; vertical-align:top;' onChange='arrange(this)'>
 <option value=name $arr_name>By Name</option>
 <option value=type $arr_type>By Type</option>
 <option value=size $arr_size>By Size</option>
 </select>"
;
}

function leftdata()
{
global $mode, $deflate;
$ajax="<br>Working in <b>'$mode'</b> mode";
if($deflate) $encoding="deflate"; else $encoding="none";

print"<table cellspacing=0 width=100%>";
print"<tr><td><b>This Folder</b></td><tr>";
print"<tr><td><div id=folderinfo name=folderinfo width=100%></div></td><tr></table><br>";
print"<table cellspacing=0 width=100%><tr><td><b>File Properties</b></td><tr>";
print"<tr><td><div id=info name=info width=100%></div></td></tr>";
print"</table><br>";
print"<table cellspacing=0 width=100%>";
print"<tr><td ><b>File and Folder tasks</b></td><tr>";
print"<tr><td><div   width=100% id=tasks>
<a href='javascript:thumbnail();'><img src=images/view.gif width=16 height=16> <u>View as thumbnail</u></a><br>
<a href='javascript:extract();'><img src=images/extract.gif width=16 height=16> <u>Extract Here</u></a><br>
<a href='javascript:openeditor();' title='Edit HTML [Shift+Ctrl+H]'><img src=editor/images/insertunorderedlist.gif width=16 height=16 > <u>Open in HTML Editor</u></a><br>
<a href='javascript:edit();'><img src=images/edit.gif width=16 height=16> <u>Open in Code Editor</u></a>
</div></td></tr></table><br>"
;
print"<table cellspacing=0 width=100%>";
print"<tr><td onClick='thumbnail();'><b>Thumbnail View</b></td><tr>";
print"<tr><td><div   width=100% id=thumb></div></td></tr></table><br>";
print"<table cellspacing=0 width=100%><tr><td><b>User Info</b></td><tr>";
print"<tr><td><div   width=100%>User IP: ".$_SERVER['REMOTE_ADDR']."$ajax<br>Encoding: <b>$encoding</b><br>
• <a href='javascript:config();'><u>Configure PHP Navigator</u></a><br>
• <a href=server.php target='_blank'><u>View Server Info</u></a><br>
• <a href='javascript:help();'><u>Quick Help</u></a></div></td></tr>"
;
print"</table><br><center>&amp;copy; Cyril Sebastian<br><a href=http://navphp.sourceforge.net><b>navphp.sourceforge.net</b></a>";
}

function filestatus($file)
{
global $dir,$ajax, $action;
$scale = array(" Bytes"," KB"," MB"," GB");
$stat = stat($file);

$size = $stat[7];
for($s=0;$size>1024&amp;&amp;$s<4;$s++) $size=$size/1024;    //Calculate in Bytes,KB,MB etc.
if($s>0) $size= number_format($size,2).$scale[$s];
else $size= number_format($size).$scale[$s];
if(is_editable($file)) $dblclick="opendir()"; else $dblclick="not_editable()";
$spec=filespec($file);

$filename=wordwrap(htmlentities($file,ENT_QUOTES), 15, "<br>\n",1);
$filename_t = base64_encode($file);

if(is_dir($file))
 print " \n<center><a>
 <img src=images/dir.gif info='<b>$filename</b><br>File Folder<br><br>
 Permissions:"
.decoct(fileperms($file)%01000)."<br>
 Modified: "
.date('d-m-y, G:i', $stat[9])."'
 onmousedown=loadfile(this) id=file fname='$filename_t' onDblClick = opendir()  spec='$spec'></a>
 <br><a href=\"javascript:download('$filename_t')\" title='Download as zip'>
 $filename</a>\n"
;
else
 print\n<center><a>
 <img src='images/"
.fileicon($file)."' width=32 height=32
 onmousedown=loadfile(this) fname='$filename_t' id=file
 info='<b>$filename</b><br><br>Size: $size<br>
 Permissions:"
.decoct(fileperms($file)%01000)."<br><br>
 Modified: "
.date('d-m-y, G:i', $stat[9])."<br>
 Accessed: "
.date('d-m-y, G:i', $stat[8])."' onDblClick = '$dblclick' spec='$spec'></a><br>
 <a href='?action=Download&amp;file=$filename_t&amp;dir=$dir' title=download>
 $filename</a>\n"
;
}

function filespec($file)    # Attributes z-zip, t-thumb, d-dir, h-html, e-editable
{
global $HTMLfiles;
$spec="f";

if(is_dir($file)) $spec.="d";
if(is_editable($file)) $spec.="e";
 $data=pathinfo($file);
 $ext=strtolower($data["extension"]);
if($ext=="png"||$ext=="gif"||$ext=="jpg"||$ext=="jpeg"||$ext=="bmp") $spec.="t";
if($ext=="zip") $spec.="z";

foreach(explode(" ", $HTMLfiles) as $type)
 if ($ext == $type) $html=true;
if($html==true) $spec.="h";
return $spec;
}

function authenticate()
{
 $login=false;
 include_once("login.php");
 $login=user_auth();

 if (!$login) {
 header('WWW-Authenticate: Basic realm="PHP Navigator"');
 header('HTTP/1.0 401 Unauthorized');
 print "<h2>You are not authorised to view this file!</h2>";
 exit;
 }

 global $user, $passwd, $dir, $homedir, $action, $file, $change, $msg, $rdonly, $ajax, $mode;

 if(!$dir) $dir=$homedir;
 else $dir=realpath(base64_decode($dir));
 $homedir=realpath($homedir);

 $file = basename(base64_decode($file));
 $change = basename(stripslashes($change));
 $dir=str_replace("\\","/",rawurldecode($dir)); #For Windows
$homedir=str_replace("\\","/",$homedir); #For Windows

 $warning="<img src=images/warning.gif style='margin-top:16px;'>";
 if(strpos($dir,$homedir)!==0)
 {$msg[]="$warning<b>Warning: Access restricted to home dir!</b>"; $dir=$homedir;}    # restrict to homedir!
if(!is_dir($dir)) {$msg[]="$warning<b>Warning: Reference to invalid directory!</b>"; $dir=$homedir;}

 if($rdonly&amp;&amp;($action!="Open")&amp;&amp;($action!="Up")&amp;&amp;($action!="Download")&amp;&amp;($mode=="normal"))
 { $action="rdonly"; $msg="$warning<b>Warning: Working in read-only mode!<br>The operation was not completed!</b><br>";    }
}

function download()    # Download file and folder-zip;
{
global $dir, $file;

if(!is_dir($dir."/".$file))
 {
 header("Content-Disposition: attachment; filename=$file");
 header("Content-Type: file/x-msdownload");
 header("Content-Length: ".filesize($dir."/".$file));
 //echo file_get_contents($dir."/".$file);
 $handle = fopen($dir."/".$file, "rb");
 while (!feof($handle)) echo fread($handle, 8192);
 fclose($handle);
 }
else
 {
 include_once("lib/zip.lib.php");

 $newzip = new zipfile();
 chdir($dir);
 $name=$file;
 add_dir($name,$newzip);

 header("Content-Disposition: attachment; filename=".$name."_navphp.zip");
 header("Content-Type: file/x-msdownload");
 $data=$newzip->file();
 header("Content-Length: ".strlen($data));
 echo $data;
 }
}

function add_dir($dir,$newzip)    # recursive adding of files to zip
{
static $no;
$no=$no+1;
if(($no>10)|| (strlen($newzip->file())>5000000)) die("Too many sub directories (>$no) or Total size > 5MB!<br>Try them by parts. [Some security measures!] ");
if($dh = opendir($dir))
 {
 $newzip->addFile("","$dir/",0);
 while (($file = readdir($dh)))  {$files[] = $file;}

 foreach($files as $file)
 {
 if($file!="."&amp;&amp;$file!=".."&amp;&amp;!is_dir("$dir/$file"))
 {
 $data=file_get_contents("$dir/$file");
 $newzip->addFile($data,"$dir/$file",0);
 }
 }
 foreach($files as $file)
 {
 if($file!="."&amp;&amp;$file!=".."&amp;&amp;is_dir("$dir/$file"))
 {
 add_dir("$dir/$file",$newzip);
 }
 }
 closedir($dh);
 }
}

function expired()
{
header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");    // Date in the past
header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
header ("Cache-Control: no-cache, must-revalidate");  // HTTP/1.1
header ("Pragma: no-cache");
}

// I assume only IE6 and mozilla support AJAX.
// This is called only if client side test fails..

function ajax_enabled()
{
 $agt=strtolower($_SERVER['HTTP_USER_AGENT']);

 $brwsr['ie6']     = (strpos($agt, 'msie 6.') !== false);
 $brwsr['ie7']     = (strpos($agt, 'msie 7.') !== false);
 $brwsr['ie8']     = (strpos($agt, 'msie 8.') !== false);
 $brwsr['firefox'] = (strpos($agt, 'firefox') !== false);
 $brwsr['opera']   = (strpos($agt, 'opera') !== false);

if(($brwsr['ie6']||$brwsr['ie7']||$brwsr['ie8']||$brwsr['firefox'])&amp;&amp;!$brwsr['opera'] )
 return 1;
else return 0;
}

function is_editable($filename)    # Checks whether a file is editable
{
 global $EditableFiles;
 $ext = strtolower(substr(strrchr($filename, "."),1));

 foreach(explode(" ", $EditableFiles) as $type)
 if ($ext == $type)
 return TRUE;

 return FALSE;
}

?>

&amp;nbsp;

PHP Script for FILE UPLOADS

We haven’t yet covered one type of input-uploading files. You can use the file
upload feature of PHP to upload images or related materials, for example.
Because the browser needs to do a little bit more than just send a POST with
the relevant data, you need to use a specially crafted form for file uploads.
Here is an example of such a special form:

<form enctype="multipart/form-data" action="handle_img.php"
➥method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="16000" />
Send this file: <input name="book_image" type="file" /><br />
<input type="submit" value="Upload" />
</form>

&amp;nbsp;

PHP Screipt for Multi Statements

The mysqli extension enables you to send multiple SQL statements in one
function call by using mysqli_multi_query. The query string contains one or
more SQL statements that are divided by a semicolon at the end of each statement.
Retrieving result sets from multi statements is a little bit tricky, as the
following example demonstrates:

<?php
$conn = mysqli_connect("localhost", "test", "", "world");
$query = "SELECT Name FROM City";
$query .= "SELECT Country FROM Country";
if ($conn->multi_query($query)) {
do {
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("Col: %s\n", $row[0];
}
$result->close();

} while ($conn->next_result());
}
$conn->close();

PHP Script for COOKIES

The simple registration we used earlier in this chapter does not make data
persistent across requests. If you go to the next page (such as by clicking a link
or by entering a different URL in your browser’s address bar), the posted data
is gone. One simple way to maintain data between the different pages in a web
application is with cookies. Cookies are sent by PHP through the web server
with the setcookie() function and are stored in the browser. If a time-out is set
for the cookie, the browser will even remember the cookie when you reset your
computer; without the time-out set, the browser forgets the cookie as soon as
the browser closes. You can also set a cookie to be valid only for a specific subdomain,
rather than having the cookie sent by the browser to the script whenever
the domain of the script is the same as the domain where the cookie was
set (the default). In the next example, we set a cookie when a user has successfully
logged in with the login form

<?php
ob_start();
?>
<html>
<head><title>Login</title></head>
<body>
<?php
if (isset ($_POST['login']) &amp;&amp; ($_POST['login'] == 'Log in') &amp;&amp;
($uid = check_auth($_POST['email'], $_POST['password'])))
{
/* User successfully logged in, setting cookie */
setcookie('uid', $uid, time() + 14400, '/');
header('Location: http://kossu/crap/0x-examples/index.php');
exit();
} else {
?>
<h1>Log-in</h1>
<form method="post" action="login.php">
<table>
<tr><td>E-mail address:</td>
<td><input type='text' name='email'/></td></tr>
<tr><td>Password:</td>
<td><input type='password' name='password'/></td></tr>
<tr><td colspan='2'>
<input type='submit' name='login' value='Log in'/></td>
</tr>
</table>
</form>
<?php
}
?>
</body>

PHP Script for HMAC Verification

If you need to prevent bad guys from tampering with variables passed in the
URL (such as for a redirect as shown previously, or for links that pass special
parameters to the linked script), you can use a hash, as shown in the following
script

<?php
function create_parameters($array)
{
$data = '';
$ret = array();
/* For each variable in the array we a string containing
* "$key=$value" to an array and concatenate
* $key and $value to the $data string. */

foreach ($array as $key => $value) {
$data .= $key . $value;
$ret[] = "$key=$value";
}
/* We also add the md5sum of the $data as element
* to the $ret array. */

$hash = md5($data);
$ret[] = "hash=$hash";
return join ('&amp;amp;', $ret);
}

php script for USER I NPUT

Now that you know how to embed PHP code, you probably want to program
some kind of user-specified action. For instance, the book webshop needs a
login and registration system that requires user action, so we will implement
this system as an example. This system requires an HTML form and a place to
store the data collected by the form. Because this chapter does not deal with
storing data in a database, only an API function is provided when data needs
to be stored. After reading some of the later chapters, you will be able to fill
these in yourself.