Tuesday, March 3, 2009

Get function prototype from wsdl

<?php
$ws = "http://www.xmethods.net/sd/2001/TemperatureService.wsdl";
$client = new SoapClient($ws);
var_dump($client->__getFunctions());
?>

Open directory and File download

<?php
$folder = $DOCUMENT_ROOT."/files/"; // the folder which you want to open

function select_files($dir) {
global $PHP_SELF;
$teller = 0;
if ($handle = opendir($dir)) {
$mydir = "<p>These are the files in the directory:</p>\n";
$mydir .= "<form name=\"form1\" method=\"post\" action=\"".$PHP_SELF."\">\n";
$mydir .= " <select name=\"file_in_folder\">\n";
$mydir .= " <option value=\"\" selected>... \n";
while (false !== ($file = readdir($handle))) {
$files[] = $file;
}
sort($files);
foreach ($files as $val) {
if ($val != "." && $val != "..") {
$mydir .= " <option value=\"".$val."\">";
$mydir .= (strlen($val) > 30) ? substr($val, 0, 30)."...\n" : $val."\n";
$teller++;
}
}
$mydir .= " </select>";
$mydir .= "<input type=\"submit\" name=\"download\" value=\"Download\">";
$mydir .= "</form>\n";
closedir($handle);
}
if ($teller == 0) {
echo "No files!";
} else {
echo $mydir;
}
}
if (isset($download)) {
$fullPath = $folder.$_POST['file_in_folder'];
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "png":
header("Content-type: image/png");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\"");
break;
case "zip":
header("Content-type: application/zip");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
break;
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
}
header("Content-length: $fsize");
header("Cache-control: private");
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
exit;
}
?>

How to Add, Edit & Update All in one Form

How to Add, Edit & Update All in one Contact Management Form
Here is a fun example on how to use functions to squeeze the most out of one page. This page lists users, adds users and edits users.
<?
/* CREATE TABLE `kids` (
`id` int(10) NOT NULL auto_increment,
`first_name` varchar(30) NOT NULL default '',
`last_name` varchar(50) NOT NULL default '',
`email` varchar(75) default NULL,
`contact_status` tinyint(1) NOT NULL default '0',
PRIMARY KEY (`id`)
) TYPE=MyISAM ;
*/
?>
<html>
<head>
<title>Manage contact's data</title>
</head>
<body>
<?php
/* control code for application */

//submit button was pressed so call the process form function
if (isset($_POST['submit']))
{
process_form();
die();
}//end if


//call the get_data function
if (isset($_GET['id']))
{
get_data();
}//endif


//nothing chosen so list the kids
if ((empty($_POST))&&(empty($_GET)))
{
list_users();
die();
}//end if


//request to add a new contact so call the show_form function
if ((isset($_GET['action']))&&($_GET['action']=='add'))
{
show_form();
}//endif



/* get the data for an individual contact */

function get_data()
{
//validate the id has been passed at that it is a number
if ((empty($_GET['id']))||(is_nan($_GET['id'])))
{
//there was a problem so list the users again
list_users();
//kill the script
die();
}else{
//all is ok and assign the data to a local variable
$id = $_GET['id'];
}//end if
$sql = "select * from contacts where id = $id";
$result = conn($sql);
if (mysql_num_rows($result)==1){
//call the form and pass it the handle to the resultset
show_form($result);
}else{
$msg = "No data found for selected contact";
confirm($msg);
//call the list users function
list_users();
}//end if
}//end function


/* show the input / edit form*/
function show_form($handle='',$data='')
{
//$handle is the link to the resultset, the ='' means that the handle can be empty / null so if nothing is picked it won't blow up

//set default values
$first_name = '';
$last_name = '';
$email = '';
$status = '';
$id = '';
$value = 'Add'; //submit button value
$action = 'add'; //default form action is to add a new kid to db

//set the action based on what the user wants to do
if ($handle)
{
//set form values for button and action
$action = "edit";
$value = "Update";

//get the values from the db resultset
$row = mysql_fetch_array($handle);
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$email = $row['email'];
$status = $row['contact_status'];
$id = $row['id'];

}//end if

//error handling from the processing form function
if($data != '')
{
$elements = explode("|",$data);
$first_name = $elements[0];
$last_name = $elements[1];
$email = $elements[2];
$id = $elements[3];
}
?>
<body>
<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>?action=<?php echo $action?>">
<table width="400" align="center" border="0" cellspacing="0" cellpadding="0">
<tr>
<td colspan="2" align="center" style="font-size:18px; font-weight:bold;">Manage Contact's Data Form</td>
<input type="hidden" value="<?php echo $id?>" name="id">
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td align="right">First Name: </td>
<td><input name="first_name" type="text" value="<?php echo $first_name?>"> </td>
</tr>
<tr>
<td align="right">Last Name: </td>
<td><input name="last_name" type="text" value="<?php echo $last_name?>"> </td>
</tr>
<tr>
<td align="right">Email Address: </td>
<td><input name="email" type="text" value="<?php echo $email?>"> </td>
</tr>
<tr>
<td align="right">Stop Contact? </td>
<td><input name="status" type="checkbox" value="1" <?php if ($status==1){ echo " checked=CHECKED "; } ?>> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td colspan="2" align="center"><input name="submit" type="submit" value="<?php echo $value?>"> <input name="reset" type="reset" value="Clear Form"></td>
</tr>
</table>

</form>
</body>

<?
}//end function


/* list all the contacts in the db */
function list_users()
{
$y = 0; //counter

$sql = "select * from contacts "; //may want to add the option where clause to only take kids with an active status
$result = conn($sql);

echo "<table width='400' align='center' cellpadding='0' cellspacing='0'>
<tr><td colspan='2' align='center' style='font-size:18px; font-weight:bold;'>Manage Contacts Data Form</td></tr>
<tr><td colspan='2'> </td></tr>
<tr><td colspan='2'><a href='".$_SERVER['PHP_SELF']."?action=add'>Add a new contact</a></td></tr>
<tr><td colspan='2'> </td></tr>";

if (mysql_num_rows($result)){
//show a list of kids with name as a link to the prepopulated form with their data in it
while($rows = mysql_fetch_array($result)){

//change row background color
(($y % 2) == 0) ? $bgcolor = "#8FBC8F" : $bgcolor=" #9ACD32";

//build strings to make life easier
$name = $rows['first_name'].' '.$rows['last_name'];
$status = $rows['contact_status'];
$id = $rows['id'];

//convert status to readable string from 1 or 0
($status == 0) ? $status = "Available to contact" : $status = "Do not contact at present.";

//echo out the row
echo "<tr style='background-color:$bgcolor;'><td><a href='".$_SERVER['PHP_SELF']."?id=$id'>$name</a></td><td>$status</td><tr>";
$y++; //increment the counter
}//end while
echo "</table>";
}else{
//handle no results
echo "<tr><td colspan='2' align='center'><b>No data found.</b></td></tr>";
}//endif
}


/* add / update the contact's data*/
function process_form()
{
$fname = '';
$lname = '';
$email = '';
$id = '';
$action = '';
$status = 0; //default value

$fname = @$_POST['first_name'];
$lname = @$_POST['last_name'];
$email = @$_POST['email'];
$id = @$_POST['id'];
$action = @$_GET['action'];
$status = @$_POST['status'];

//if no status is set, defaults to 0 (allow contact)
if ($status == ''){$status = 0; }

if (($fname=='')||($lname=='')||($email==''))
{
$msg = "Some data from the form was forgotten. Please fill in the entire form.";
confirm($msg);
$data = "$fname|$lname|$email|$id";
show_form('',$data);
die();
}//end if

//You could add some validation of the data ( I recommend it and its a great way to get your feet wet with php )


if ($action == "add")
{
$sql = "insert into contacts (first_name, last_name, email, contact_status) values('$fname','$lname','$email',$status)";
$msg = "Record successfully added";
}elseif($action=="edit"){
$sql = "update contacts set first_name = '$fname', last_name = '$lname', email = '$fname', contact_status = '$status' where id = $id";
$msg = "Record successfully updated";
}
$result = conn($sql);
if (mysql_errno()==0)
{
confirm($msg);
list_users();
}else{
$msg = "There was a problem adding the user to the database. Error is:".mysql_error();
confirm($mag);
}//end if

}


/* db connection function */
function conn($sql)
{

$host = "localhost";
$user = "user";
$pass = "pass";
$db = "my_db";


//echo "commnecing connection to local db<br>";

if (!($conn=mysql_connect($host, $user, $pass))) {
printf("error connecting to DB by user = $user and pwd=$pass");
exit;
}
$db3=mysql_select_db($db,$conn) or die("Unable to connect to local database");

$result = mysql_query($sql) or die ("Can't run query because ". mysql_error());

return $result;

}//end function

/* alert box popup confimation message function */
function confirm($msg)
{
echo "<script langauge=\"javascript\">alert(\"".$msg."\");</script>";
}//end function
?>

How to Calling a Function Dynamically

<html>
<head>
<title>Calling a Function Dynamically</title>
</head>
<body>
<?php
function sayHello(){
print "hello<br>";
}
$function_holder = "sayHello";
$function_holder();
?>
</body>
</html>

How to Creates three SELECT form fields Month Day and Year

<?php

function DateSelector($inName, $useDate=0)
{
/* create array so we can name months */
$monthName = array(1=> "January", "February", "March",
"April", "May", "June", "July", "August",
"September", "October", "November", "December");

/* if date invalid or not supplied, use current time */
if($useDate == 0)
{
$useDate = Time();
}

/* make month selector */
echo "<SELECT NAME=" . $inName . "Month>\n";
for($currentMonth = 1; $currentMonth <= 12; $currentMonth++)
{
echo "<OPTION VALUE=\"";
echo intval($currentMonth);
echo "\"";
if(intval(date( "m", $useDate))==$currentMonth)
{
echo " SELECTED";
}
echo ">" . $monthName[$currentMonth] . "\n";
}
echo "</SELECT>";

/* make day selector */
echo "<SELECT NAME=" . $inName . "Day>\n";
for($currentDay=1; $currentDay <= 31; $currentDay++)
{
echo "<OPTION VALUE=\"$currentDay\"";
if(intval(date( "d", $useDate))==$currentDay)
{
echo " SELECTED";
}
echo ">$currentDay\n";
}
echo "</SELECT>";

/* make year selector */
echo "<SELECT NAME=" . $inName . "Year>\n";
$startYear = date( "Y", $useDate);
for($currentYear = $startYear - 5; $currentYear <= $startYear+5;$currentYear++)
{
echo "<OPTION VALUE=\"$currentYear\"";
if(date( "Y", $useDate)==$currentYear)
{
echo " SELECTED";
}
echo ">$currentYear\n";
}
echo "</SELECT>";

}
?>

<HTML>
<BODY>
<FORM>
Choose a Date: <?php DateSelector( "Sample"); ?>
</FORM>
</BODY>
</HTML>

Parsing a Query String

<?php
$str = "first=value&arr[]=foo bar&arr[]=baz";
parse_str($str);
echo $first; // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz

parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

?>

How to use session-variables

<?php
# -------------------------------------------------------------------
# This Include handle Session based variable handling
#
# Please feel free and use it. If you make it more functional
# it would be nice to send me a copy.
#
# Don't forget - Mysql_connect !
#
# The database structure
# Table structure for table 'session'
#
# CREATE TABLE session (
# id int(11) DEFAULT '0' NOT NULL auto_increment,
# sid varchar(20) DEFAULT '' NOT NULL,
# val blob,
# times timestamp(14),
# PRIMARY KEY (id),
# KEY sid (sid),
# UNIQUE sid_2 (sid)
# );
#
# You'll miss here a cron job to delete the old sessions from db
# -------------------------------------------------------------------

$sess_db = 'test';
$sess_table = 'session';

# ----------------------------------------------------
# Session_CheckID - Get or Set the Session-ID
# Parameter.: time how long the cookie will keept
# or null if it's only a session cookie
# Return....: Session-Unique ID
# ----------------------------------------------------
function Session_CheckID( $min )
{
global $sess_sid;

if( !$sess_sid ) {
$sess_sid = uniqid( SC );
if( $min > 0 ) {
SetCookie("sess_sid", $sess_sid, time()+($min*60), "/", "", 0 );
}
else {
SetCookie("sess_sid", $sess_sid, "", "/", "", 0 );
}
return( false );
}
else {
return( $true );
}
}

# ----------------------------------------------------------
# str2arr - build out from a string with eval the new array
# parameter.: string
# returns...: global array
# ----------------------------------------------------------
function str2arr( $ts )
{
global $session;

$vals = split( "&", $ts );
while( list($key,$val) = each($vals) ) {
list( $name, $wert ) = split( "=", $val );
if( $val ) eval( "\$$name = \"$wert\";" );
}
}

# ----------------------------------------------------------
# session_read - reads the session-variables
# Parameter.: none
# returns...: read - ok = true
# ----------------------------------------------------------
function session_read()
{
# Hash array to keep session-variables
global $session;

global $sess_sid, $sess_db, $sess_table, $sess_error;


$sel = "Select val from $sess_table where sid = '$sess_sid'";
$res = mysql_db_query( $sess_db, $sel );
if( mysql_numrows( $res ) ) {
$val = mysql_result( $res, 0, "val" );
str2arr( $val );
mysql_free_result( $res );
return( true );
}
else {
return( false );
$sess_error = mysql_error();
}
}

# ------------------------------------------------------
# Split_Array - reads the session-array into a string
# Parameter.: array
# returns...: string with & separeted array fields
#
# Thanks to Rasmus
# ------------------------------------------------------
function Split_Array( $arr, $a = "", $b = "", $c = "" )
{
while( list( $key, $val ) = each( $arr ) ) {
if( is_array( $val ) ) {
$ts .= Split_Array( $arr[ $key ],
( strlen( $a ) ? $a : $key ),
( strlen( $b ) ? $b : ( strlen( $a ) ? $key : "" ) ),
( strlen( $c ) ? $c : ( strlen( $b ) ? $key : "" ) ) );
}
else {
$ts .= "session";
$ts .= $a ? "[$a]" : "";
$ts .= $b ? "[$b]" : "";
$ts .= $c ? "[$c]" : "";
$ts .= "[$key]=$val&";
}
}
return( $ts );
}

# ---------------------------------------------------
# session_write - writes the session-variable from
# the array session
# parameter.: none
# returns...: write - ok = true
# ---------------------------------------------------
function session_write()
{
# Hash array to keep session-variables
global $session;

global $sess_sid, $sess_db, $sess_table;
global $sess_error;

# if you like to delete a session-cookie
# you must check it before writting the session
# array

if( !$sess_sid ) { session_checkid( 0 ); }

$ts = Split_Array( $session );
if( $ts > "" ) { $ts = substr( $ts, 0, strlen( $ts ) - 1 ); }
$res = mysql_db_query( $sess_db, "Select * from session where sid = '$sess_s'");
if( mysql_numrows( $res ) == 0 ) {
$sel = "Insert into $sess_table ( id, sid, val, times ) ";
$sel .= "values( 0, '$sess_sid', '$ts', NULL )";
}
else {
$sel = "Update $sess_table set val = '$ts', ";
$sel .= "times = NULL where sid = '$sess_sid'";
}
if( !mysql_db_query( $sess_db, $sel ) ) {
$sess_error = mysql_error();
return( false );
}
else { return( true ); }
}

# ---------------------------------------------
# session_del - clears an entry
# parameter.: hash - id
# returns...: none
# ---------------------------------------------
function session_del()
{
global $session, $sess_db, $sess_table, $sess_sid;

$sel = "Delete from $sess_table where sid = '$sess_sid'";
if( !mysql_db_query( $sess_db, $sel ) ) {
$sess_error = mysql_error();
}
$sess_sid = '';
}

?>

[------------------ This is an example ------------------]

<?php
require( "session.inc" );

if( $del ) {
session_del();
}

session_checkid( 0 );

mysql_connect('') or Die("can't connect to db!");

# Normal use ist to read the session-var and assign it to the
# working vars. This example assign after session-read fail the
# new values.
if( session_read() ) {
$hallo = $session[hallo];
$w12 = $session[w12];
$arr = $session[arr];
}
else {
for( $i = 1; $i <= 10; $i++ ) {
for( $j = 1; $j <= 2; $j++ ) {
$arr[$i][$j] = $i+$j;
}
}

$w12 = '10232';
$hallo = 'Ho oh. ';
}

?>
<html>
<head><title>Session/Cookie-Test 1</title>
</head>

<body>

<h2>This Page should show how to handle the "session.inc" library</h2>

<h3>We will use a mask with a record showing routine</h3>

<?php
print "<h4>Show all variables</h4>";
for( $i = 1; $i <= 10; $i++ ) {
print "\$arr: [$i][1-2] = " . $arr[$i][1] . " / " . $arr[$i][2] . "<br>";
}
print "<br>";
print "w12: " . $w12 . "<br>";
print "hallo: " . $hallo . "<br>";

# increment variables
for( $i = 1; $i <= 10; $i++ ) {
for( $j = 1; $j <= 2; $j++ ) {
$arr[$i][$j] += 2;
}
}

$w12++;
$hallo .= "w1";

# -------------------------------------
# reassign session variables
# -------------------------------------
$session[arr] = $arr;
$session[w12] = $w12;
$session[hallo] = $hallo;

# -------------------------------------
# store session variables
# -------------------------------------
if( !session_write() ) {
print $sess_error;
}

?>

<form action=sess1.php3 method=post>
<hr>
<input type=submit name=del value=" reset session ">

If you like to reset the session - click

</form>

</body>
</html>

How to Display a bar chart based on random values

<?

// bars.php3 - Bar chart on gif image
// Note: uses the gd library
// This code will display a bar chart based on random values
// Different colors are used to display bars and a gif images
// is used for the background. Use the following link to include
// the example into your web-site
// <img src="./bars.php3" border="0">
//
// The background image can be found at

Header( "Content-type: image/gif");
Header( "Expires: Mon, 17 Aug 1998 12:51:50 GMT");

$im = imagecreatefromgif( "gradient.gif");

// Allocate colors
$red=ImageColorAllocate($im,255,0,0);
$green=ImageColorAllocate($im,0,255,0);
$blue=ImageColorAllocate($im,0,0,255);
$yellow=ImageColorAllocate($im,255,255,0);
$cyan=ImageColorAllocate($im,0,255,255);

// Determine size of image
$x=imagesx($im);
$y=imagesy($im);

// Initialize random number generator
srand(mktime());

// Create some bars
$v=rand(); $v=$v/32768*200;
ImageFilledRectangle($im,10,200-$v,60,200,$red);
$v=rand(); $v=$v/32768*200;
ImageFilledRectangle($im,70,200-$v,120,200,$green);
$v=rand(); $v=$v/32768*200;
ImageFilledRectangle($im,130,200-$v,180,200,$blue);
$v=rand(); $v=$v/32768*200;
ImageFilledRectangle($im,190,200-$v,240,200,$yellow);
$v=rand(); $v=$v/32768*200;
ImageFilledRectangle($im,250,200-$v,300,200,$cyan);

// Display modified image
ImageGif($im);
// Release allocated ressources
ImageDestroy($im);
?>

Simple php file uploader

A simple php file uploader

upload.php


<?


// Code Snippet:
php

// Upload Form

function display_upload_form()
{
echo <<<DISPLAY_UPLOAD_FORM

<html>
<head>
<title>Yet Another Upload Form</title>
<style type="text/css" media="screen">
<!--
html body
{background:#fff; font: 76%/1.5em arial, helvetica, sans-serif; color:#333;}

input
{color:#333;}
-->
</style>
</head>

<body>

<form method="post" action="{$_SERVER['PHP_SELF']}" enctype="multipart/form-data">

<p>Select a file.<br />
<input type="file" name="myfile" tabindex="1" /></p>

<p><input type="hidden" name="execute" value="1" /></p>

<p><input type="submit" value="Upload File" tabindex="2" />

</form>

</body>
</html>

DISPLAY_UPLOAD_FORM;}

// File Upload

function execute_upload()
{
// root path
$path = $_SERVER['DOCUMENT_ROOT'];

// upload directory. path will originate from root.
$dirname = '/uploads';

// permission settings for newly created folders
$chmod = 0755;

// create file vars to make things easier to read.
$filename = $_FILES['myfile']['name'];
$filesize = $_FILES['myfile']['size'];
$filetype = $_FILES['myfile']['type'];
$file_tmp = $_FILES['myfile']['tmp_name'];
$file_err = $_FILES['myfile']['error'];
$file_ext = strrchr($filename, '.');

// check if user actually put something in the file input field.
if (($file_err == 0) && ($filesize != 0))
{
// Check extension.
if (!$file_ext)
{
unlink($file_tmp);
die('File must have an extension.');
}

// extra check to prevent file attacks.
if (is_uploaded_file($file_tmp))
{
/*
* check if the directory exists
* if it doesnt exist, make the directory
*/
$dir = $path . $dirname;

if (!is_dir($dir))
{
$dir = explode('/', $dirname);

foreach ($dir as $sub_dir)
{
$path .= '/' . $sub_dir;
if (!is_dir($path))
{
if (!mkdir($path, $chmod))
{
unlink($file_tmp);
die('<strong>Error:</strong> Directory does not exist and was unable to be created.');
}
}
}
}

/*
* copy the file from the temporary upload directory
* to its final detination.
*/
if (@move_uploaded_file($file_tmp, $dir . '/' . $filename))
{
// success!
echo "
<p>Success!</p>
<p><strong>View File:</strong> <a href=\"$dirname/$filename\">$filename</a></p>
";
}
else
{
// error moving file. check file permissions.
unlink($file_tmp);
echo '<strong>Error:</strong> Unable to move file to designated directory.';
}
}
else
{
// file seems suspicious... delete file and error out.
unlink($file_tmp);
echo '<strong>Error:</strong> File does not appear to be a valid upload. Could be a file attack.';
}
}
else
{
// Kill temp file, if any, and display error.
if ($file_tmp != '')
{
unlink($file_tmp);
}

switch ($file_err)
{
case '0':
echo 'That is not a valid file. 0 byte length.';
break;

case '1':
echo 'This file, at ' . $filesize . ' bytes, exceeds the maximum allowed file size as set in <em>php.ini</em>. '.
'Please contact your system admin.';
break;

case '2':
echo 'This file exceeds the maximum file size specified in your HTML form.';
break;

case '3':
echo 'File was only partially uploaded. This could be the result of your connection '.
'being dropped in the middle of the upload.';

case '4':
echo 'You did not upload anything... Please go back and select a file to upload.';
break;
}
}
}

// Logic Code

if (isset($_POST['execute']))
{
execute_upload();
}
else
{
display_upload_form();
}


?>

Error Handler

Error Handler

<?php

// redefine the user error constants - PHP 4 only
define ("FATAL",E_USER_ERROR);
define ("ERROR",E_USER_WARNING);
define ("WARNING",E_USER_NOTICE);

// set the error reporting level for this script
error_reporting (FATAL | ERROR | WARNING);

// error handler function
function myErrorHandler ($errno, $errstr, $errfile, $errline) {
switch ($errno) {
case FATAL:
echo "<b>FATAL</b> [$errno] $errstr<br>\n";
echo " Fatal error in line ".$errline." of file ".$errfile;
echo ", PHP ".PHP_VERSION." (".PHP_OS.")<br>\n";
echo "Aborting...<br>\n";
exit(1);
break;
case ERROR:
echo "<b>ERROR</b> [$errno] $errstr<br>\n";
break;
case WARNING:
echo "<b>WARNING</b> [$errno] $errstr<br>\n";
break;
default:
echo "Unkown error type: [$errno] $errstr<br>\n";
break;
}
}

// function to test the error handling
function scale_by_log ($vect, $scale) {
if ( !is_numeric($scale) || $scale <= 0 )
trigger_error("log(x) for x <= 0 is undefined, you used: scale = $scale",
FATAL);
if (!is_array($vect)) {
trigger_error("Incorrect input vector, array of values expected", ERROR);
return null;
}
for ($i=0; $i<count($vect); $i ) {
if (!is_numeric($vect[$i]))
trigger_error("Value at position $i is not a number, using 0 (zero)",
WARNING);
$temp[$i] = log($scale) * $vect[$i];
}
return $temp;
}

// set to the user defined error handler
$old_error_handler = set_error_handler("myErrorHandler");

// trigger some errors, first define a mixed array with a non-numeric item
echo "vector a\n";
$a = array(2,3,"foo",5.5,43.3,21.11);
print_r($a);

// now generate second array, generating a warning
echo "----\nvector b - a warning (b = log(PI) * a)\n";
$b = scale_by_log($a, M_PI);
print_r($b);

// this is trouble, we pass a string instead of an array
echo "----\nvector c - an error\n";
$c = scale_by_log("not array",2.3);
var_dump($c);

// this is a critical error, log of zero or negative number is undefined
echo "----\nvector d - fatal error\n";
$d = scale_by_log($a, -2.5);

?>

Email Validation

Email Validation

<?
function is_valid_email($email) {
if(ereg("([[:alnum:]\.\-]+)(\@[[:alnum:]\.\-]+\.+)", $email)) {
return 1;
} else {
return 0;
}
}
?>

Dynamic Calendar

Dynamic Calendar (easiest ever)

<style type="text/css"?>
<!--
td
{
font-size:12pt;
line-height:14pt;
font-family:Helvetica,Arial;
}
//-->
</style>


<?

## change to the previous month
if ($command == "prev_month")
{
if (--$month == 0)
{
$month = 12;
$year--;
}
}
## change to the next month
else if ($command == "next_month")
{
if (++$month == 13)
{
$month = 1;
$year++;
}
}

## if no month has been passed
if ($month == "")
{
$year= date("Y");
$month= date("n");
$month_name = date("F",mktime(0,0,0,$month,1,$year));
}
## use current date if no month is passed
else
{
$year= date("Y",mktime(0,0,0,$month,1,$year));
$month= date("n",mktime(0,0,0,$month,1,$year));
$month_name = date("F",mktime(0,0,0,$month,1,$year));
}


$dow = date("w",mktime(0,0,0,$month,1,$year)); //which day 1 falls on in the week
(0 = Sun)
$dim = date("d",mktime (0,0,0,$month+1,0,$year)); //days in the current month
## modification to only print the number of weeks in a month
$wim = ceil(($dim+$dow)/7); //weeks in month

$ct=0;

echo "<br>
<table border='0' cellpadding='1' cellspacing='1' width='425' align='center'>
<tr>
<td align='center'><h1><a href='index.php?
command=prev_month&month=$month&year=$year'><<</a> $month_name $year <a href='index.php?command=next_month&month=$month&year=$year'>>></a></h1></td>
</tr>
</table>
<table border='1' cellpadding='1' cellspacing='1' width='425' align='center'>
<tr>
<td align='center'><b>Sun</td>
<td align='center'><b>Mon</td>
<td align='center'><b>Tue</td>
<td align='center'><b>Wed</td>
<td align='center'><b>Thu</td>
<td align='center'><b>Fri</td>
<td align='center'><b>Sat</td>
</tr>
";

## print only the number of weeks needed
for($row=1;$row<$wim+1;$row++)
{
echo "<tr height='60'>";

## prints week (Sun to Sat)
for($week=1;$week<8;$week++)
{
$ct++;
$value=mktime(0,0,0,$month,$ct-$dow,$year);

## if $value is part of current month
if (date("m",$value)==$month)
{
echo "
<td align='center' class='body' width='85' valign='top'>
<div align='right'><b>".date("j",$value)."</a></b></div><br>
</td>";
}
## print previous and next month dates, but grayed out
else
{
echo "<td align='center' class='body' width='85' valign='top'
bgcolor='#CCCCCC'><div
align='right'><b>".date("j",$value)."</a></b></div><br></td>";
}
}

echo "</tr>";
}


echo "</table>";

?>

Beginners Array Functions

Beginners Array Functions

I have in the past searched for an area that shows how to use arrays and shows why they do what they do. But only found full scripts or lengthy articles about them, but did not explain in plain english.

------------------------------------------------------------
Below are 3 items that will be used in the first example. I use this method for Admin User maitenance areas of my sites.

[#] is the KEY of the array
"..." is the VALUE of the array

$access_level[0] = "Public";
$access_level[5] = "Clan Member";
$access_level[10] = "Administrator";

To display these items in a drop menu of a form:

echo "\n";
?>
------------------------------------------------------------
When using arrays in a form element such as a checkbox, you simple place a [] after the element name. Inside the [] will be the KEY of the array and you can place any value in the brackets such as ID numbers or leave empty. Not all actions require a KEY by most will need a VALUE.

name=\"fieldname[]\"

echo "\n";
?>

To use this feature in a query such as update or delete.

foreach ($userID as $user_value) {
$sql = mysql_query("UPDATE tablename SET field1='$field1', field2='$field2' WHERE userID = $user_value") or die (mysql_error());
}
header("Location: index.php");
?>

How to Authenticate user: Database based




<?php

   function authenticate_user() {

      header('WWW-Authenticate: Basic realm="Secret Stash"');

      header("HTTP/1.0 401 Unauthorized");

      exit;

   }



   if (! isset($_SERVER['PHP_AUTH_USER'])) {

      authenticate_user();

   else {

      mysql_pconnect("localhost","authenticator","secret"or die("Can't connect to database server!");

      mysql_select_db("java2s"or die("Can't select authentication database!");



      $query = "SELECT username, pswd FROM user WHERE username='$_SERVER[PHP_AUTH_USER]' AND pswd=MD5('$_SERVER[PHP_AUTH_PW]')";



      $result = mysql_query($query);



      // If nothing was found, reprompt the user for the login information.

      if (mysql_num_rows($result== 0) {

         authenticate_user();

      }

   }

?>





           

       

How React to Form action



<HTML>
<BODY>

<FORM METHOD="POST" ACTION="GetFormValue.php">
    <H2>Contact List</H2>
    <BR>Nickname:
    <BR><INPUT TYPE="TEXT" NAME="Nickname">
    <BR>
    <BR>Full Name:
    <BR><INPUT TYPE="TEXT" NAME="Fullname">
    <BR>
    <BR>Memo:
    <BR><TEXTAREA NAME="Memo" ROWS="4" COLS="40" WRAP="PHYSICAL">
    </TEXTAREA>
    <BR>
    <BR>
    <INPUT TYPE="SUBMIT">
</FORM>
</BODY>


<!-- GetFormValue.php
<?php
  echo "<BR>Nickname=$Nickname";
  echo "<BR>Fullname=$Fullname";
  echo "<BR>Memo=$Memo";
?>
-->