Welcome to my Weblog


I will be using this site to post on a number of subjects including time saving scripts, technological investigations and topical issues on a number on platforms including Windows and MacOSX.

Any comments or suggestions are welcome!


Batch File – For Loop

February 9th, 2009 No comments

I will commonly write small batch files to automate tasks that are repetitive, due to this I find myself using the for loop a lot. Below are a few examples of when and where the for loop can be used effectively.

Looping through entries in a file

This example will take a standard text file (MyTextFile.txt) and then loop through all lines until the end of the file is reached. For each of the lines the first word (represented by %%A) will be printed out to the screen and ping’ed.

FOR /F “tokens=1″ %%A IN (C:\MyTextFile.txt) DO (

echo %%A

ping %%A

)

An example of the text file is simply:

COMPUTER01
COMPUTER02
COMPUTER03
COMPUTER04

By changing the tokens value, which word on a line that is used will change. By setting the value of tokens from 1 to 1,2 both the first and second words per line will be available via the parameters %%A and %%B. When using the following input file, within the loop %%A will be the computer name and %%B will be the IP address.

COMPUTER01 192.168.1.100
COMPUTER02 192.168.1.101
COMPUTER03 192.168.1.102

To ignore selected lines, i.e. lines that are actually comments use the eol parameter, the following for loop will ignore all lines that start with a colon:

FOR /F “tokens=1 eol=:” %%A IN (C:\MyTextFile.txt) DO (

echo %%A

)

If the input file has a number of header lines that should not be included the skip parameter should be used, for following will exclude the first 3 files of the input file:

FOR /F “tokens=1 eol=: skip=3″ %%A IN (C:\MyTextFile.txt) DO (

echo %%A

)

To override the default delimiters (space and tab) the delims parameter should be used. The following will ignore the space delimiter and instead delimiter by comma:

FOR /F “tokens=1 delims=,” %%A IN (C:\MyTextFile.txt) DO (

echo %%A

)

PHP – Email Advanced

February 8th, 2009 No comments

For a simple introduction to the mail() function see the PHP_Advanced article. This article describes some of the more advanced features that can be achieved through the mail function.

Assign Names to email addresses

When receiving an email you will notice that the To field often contains a name rather than the email address it was send to.

<HTML>
<BODY>
<?PHP
mail(‘bob@email.com’, ‘Test email’,
‘This is a test email’,
“To: Bob Jones <bob@email.com>\n” .
“From: Jane Jones <jane@email.com>\n” .
“cc: Another Person <another@email.com>\n” .
“Bcc: Yet Another <more@email.com\n>”);
?>
</BODY>
</HTML>

HTML Emails

The next stage is sending HTML email messages, this allows for standard HTML tags to be used when composing the message content. When sending a message in HTML it must be declared that is it HTML in the header of the email, this is done through both the Content-type: and MIME-Version headers’:

<HTML>
<BODY>
<?PHP
mail(‘bob@email.com’, ‘Test email’,
‘<html><body><b>Hello! World</b> \n <i>this is a test email</i></body></html>’,
“MIME-Version: 1.0\n” .
“Content-type: text/html; charset=iso-8859-1″);
?>
</BODY>
</HTML>

The MIME-Version (Mulitpurpose Internet Mail Extensions) header indicates that the email follows the internet standards, following that the Content-type header can declare the format being used; text/html; followed by the character set being used charset=iso-8859-1

Mixed Format Emails

Although the majority of email clients support HTML email messages, there are some that don’t. The mixed format ensures that the email clients that do support it see the HTML formatted message, where as the ones that don’t see a plain text version.

The technique involved is to actually send two versions of the message and rely on the email client to read and understand Content-Type: multipart/alternative; header which will make the client only display the supported version.

*** PHP code not fully completed yet ***

Emailing Attachments

Emailing file Attachments work in the same way that mixed format email messages do. The header Content-Type: multipart/mixed; is used and the message split into two parts; one the message and the other the file attachment(s).

This is more complicated than previous email examples, all the steps required are explained below. The examples assume that the email details including the file to be emailed have been submitted to the PHP page from another page.

$to = $_POST['to'];
$from = $_POST['from'];
$subject = $_POST['subject'];
$message = $_POST['message'];

Attributes of the file attachment

The first stage is to extract the required attributed from the file that has been passed. The file details in PHP are stored in an array named $_FILES which are extracted to variables.

// example: /tmp/phpfile12345 – tmp file name and loc where uploaded
$file_loc = $_FILES['fileatt']['tmp_name'];
// example: text/text – will vary depending on file type
$file_type = $_FILES['fileatt']['type'];
// example: mywork.txt – always the name of the file
$file_name = $_FILES['fileatt']['name'];

Extract data from file attachment

The data within the file is required to be placed into a variable then used Base64 encoding to convert (possible) binary data into text. The is_uploaded_file function is used to ensure that the file was in fact uploaded by an http get command, this helps to ensure no malicious activity.

if (is_uploaded_file($file_loc)) {
// Read the file in ‘rb’ read binary
$file = fopen($file_loc,’rb’);
$filedata = fread( $file (comma) filesize ($file_loc));
// Base64 encode the file data
$filedata = chunk_split(base64_encode($filedata));

The data is now in a format that is ready to be emailed, the next stage is producing the standard mail parameters.

Producing mail function

The basic mail parameters are set in the same manor, the diffrences come in the header and message parameters

The header parameter contains the MIME version, the Content-Type: multipart/mixed; declares that there will be an attachment, finally the boundary string (containing random text) is used as a marker to split the message into the two sections.

“\nMIME-Version: 1.0\n” .
“Content-Type: multipart/mixed;\n” .
” boundary=\”==Multipart_Boundary_x45985365x\”";

The message section starts with a declaration which MIME compatible email clients will not show, next is the Multipart Boundary string denoting the beginning of the first section. Following this the usual header information is declared, following by the desired message text.

“This is a multi-part message in MIME format. you should not see this\n\n” .
“–==Multipart_Boundary_x45985365x\n” .
“Content-Type: text/plain; charset=\”iso-8859-1\”\n” .
“Content-Transfer-Encoding: 7bit\n\n” .
“This is the message contents, there should be a file attached to this message”

After the text of the message, the next part is the message attachment which follows the same format as above.

“–==Multipart_Boundary_x45985365x\n” .
“Content-Type: {$file_type};\n” .
” name=\”{$file_} \n” .
“Content-Disposition: attachment;\n” .
” filename=\”{$file_name}\”\n” .
“Content-Transfer-Encoding: base64\n\n” .
$filedata . “\n\n” .
“–==Multipart_Boundary_x45985365x–\n”;

Then message should always have the message boundary string followed by to signify the end.

To see the fully working source code, please see here

For more information on different MIME types see here
Many thanks to the tutorials where this information came from, W3Schools & PHP & sitepoint

Categories: How to Tags: , ,

PHP – Advanced

February 8th, 2009 No comments

This article will guide you through some of the more complex features of PHP. a more basic introduction article is also available.

User Data

When browsing the internet you will come across some websites that store information about you or your visits to the site. There are two main methods of storing this data, these are through Cookies and Sessions.

Cookies

Cookies are the older of the two methods, it consists of a client side file that the browser writes to. With PHP you can create new cookies and also retrieve existing values, examples of both are below

To create new cookies the setcookie function is used, the main parameters are:

  • Name – The Name of the cookie
  • Value – Data that the cookie is to store
  • Expire – Time & Date when the cookie will expire

When creating cookies in PHP you must call the setcookie function before any HTML tags are used in the page, an example is shown below:

<?PHP
setcookie(“yeltuor”, “MyValue”, time()+86400);
?>
<HTML>
<BODY>
The cookie named yeltuor has been ’set’
It will expire 24 Hours (86400 seconds) from now.
</BODY>
</HTML>

With the cookie now created, the next stage is to read back the values stored in it. The values in the cookie can be called in the same way variables are:

<HTML>
<BODY>
<?PHP
//Check whether the cookie named yeltuor is set
if (isset($_COOKIE["yeltuor"]))
echo “Welcome back ” . $_COOKIE["yeltuor"] . “<br>”;
else
echo “Welcome newbe <br>”;
?>
</BODY>
</HTML>

Sessions

A Sessions is a server side file that is written to, again PHP support the creation and retrieval of session data. When a session is created a unique session ID is used to reference it, this is all taken care within the underlying PHP code.

The advantage of using sessions is that the user can’t view or edit the data within them; unlike the client side cookie’s. Before using sessions on a PHP page, the session_start(); function must be called, after this a session can be created, however like the cookie functions all session calls must be done before any HTML code on the page:

Below is an example of setting up a server side session:

<?PHP
//start session
session_start();
//if session variable total doesn’t exist create one
if(!isset($_SESSION['total']))
$_SESSION['total'] = ‘0′;
?>
<HTML>
<BODY>
The session variable total set to 0, unless it already existed.
</BODY>
</HTML>

To reference existing session variables and dispose of variables that are no longer required, the following code can be used:

<?PHP
//start session
session_start();
?>
<HTML>
<BODY>
<?PHP
echo “The total is ” . $_SESSION['total'];
//Finished with session variable, disposing of it
unset($_SESSION['total']);
?>
</BODY>
</HTML>

For the security minded individuals, a list of more advanced session functions that are available can be seen here.

Files

PHP supports various file related operations, some examples are below:

Opening a file is done with the fopen( ); function, the first parameter is the filename, the second is the mode to open the file in:

Mode Description
r Read Only, pointer at the beginning of the file
r+ Read and Write, pointer at the beginning of the file
w Write Only, existing file will be truncated or new file will be created.
w+ Write and Read, existing file will be truncated or new file will be created.
a Write Only, Places pointer at end of the file or new file will be created.
a+ Write and Read, Places pointer at end of the file or new file will be created.
x Write Only, If the file already exists the fopen( ) function will return FALSE, or a new file will be created.
x Write and Read, If the file already exists the fopen( ) function will return FALSE, or a new file will be created.

Some examples of using the fopen( ) function are below:

<HTML>
<BODY>
<?PHP
//Open file hello.txt, in the case of an error exit
$f=fopen(“hello.txt”,”r”) or exit(“Cant open file”);
//if reached the end of the file
if (feof($f))
echo “End of file”;
//Loop through file 1 char at a time, echo value
while (!feof($f))
{
$x=fgetc($f);
echo $x;
}
//Close file handle when finished
fclose($f) ;
?>
</BODY>
</HTML>

This function below accepts a parameter of a filename and location and returns the file data as a variable called contents:

function fileContents($filename){
// get contents of a file into a string
$f = fopen($filename, “r”);
$contents = fread($f, filesize($filename)) ;
fclose ($f);
return $contents;
}

Functions

Functions are used in the same way that procedures are used in other programming languages, they are used to aid with the re-use of code. examples of using functions can be seen below:

<HTML>
<BODY>
<?PHP
function echoHelloWorld($name)
{
echo “Hello World my name is ” . $name;
}
//Using the created function
echoHelloworld(“Borris”)
?>
</BODY>
</HTML>

Functions can also return values as an output by the return command from within the function.

<HTML>
<BODY>
<?PHP
function addnum($num1,$num2)
{
$tot = $num1 + $num2;
return $tot;
}
//Using the function addnum
echo “1 + 2 = ” . addNum(1,2);
?>
</BODY>
</HTML>

Require

The require function works in the same way as a function, except that it is used to call another file which is inserted into the current page. This is useful when a header is being used;

<HTML>
<BODY>
<?PHP
require(“header.php”)
?>
<h3>More text here.</h3>
</BODY>
</HTML>

Email

PHP has built in email support by using the mail() function, it requires the usual email parameters;

Parameter Description
to The recipients address in the form of abc@xyz.com
subject Subject of the email
message Content of the email; use the \n command for a new line
headers An optional parameter which may contain and Cc’s of Bcc’s
parameters Additional parameters that the sendmail program accepts i.e. From

An example of the code for a mail function with error checking is shown below, to send emails to multiple recipients, a comma: , should be used as a delimiter.

<HTML>
<BODY>
<?PHP
$to = “bob@email.com”;
$subject = “Test email”;
$message = “Hello! World \n this is a test email”;
$from = “tom@email.com”;
$headers = “From: $from”;
if (mail($to,$subject,$message,$headers))
echo “Mail Sent sucessfully”;
else
echo “Failed to Send Mail”;
?>
</BODY>
</HTML>

This is very basic example of using emailing, however for a more complete guide to PHP emailing please see PHP Mail article.

PHP – Basic

February 8th, 2009 No comments

PHP is a server-side scripting language which allow for the creation dynamic and interactive webpages, standing for PHP: Hypertext Preprocessor

It is the widely-used, free, and efficient alternative to competitors such as Microsoft’s ASP. PHP is perfectly suited for Web development and can be embedded directly into the HTML code of a page.

PHP is often used together with the Apache web server on various operating systems. It also supports ISAPI and can be used with Microsoft’s IIS on Windows.

This article will go through some useful PHP syntax and uses.

Basic Syntax

Basic Syntax included in a PHP page and how in integrates with HTML

A piece of PHP code will always start with the tag <?php and end with ?>

Using the echo ” ” ; tag displays standard HTML that the browser will display. To echo multiple strings of variables (explained later) use a dot . <HTML> <BODY> <?php echo “<h1> Hello World </h1>”; echo “Hello” . “World”; ?> </BODY> </HTML>

Comments

Adding comments in PHP is just as important as any other programming language. within PHP there are two different methods for adding comments, through the // syntax for a single line, or to add a block of comment use /* to start, and */ to finish the block

<HTML>
<BODY>
<?php
//Single Comment
/*
Start of comment block
Still commenting
*/
?>
</BODY>
</HTML>

Variables

Variables are not typed in PHP, when referencing variables in PHP they just start with the $ symbol.

The snippet of code assigns a variable, then uses the echo command to output its value

<HTML>
<BODY>
<?php
$var1=”Hello World”;
echo $var1;
?>
</BODY>
</HTML>

Operators

PHP has the several standard operators which can be used, see table below

PHP Operators
Operator Action
+ Add
- Subtract
* Multiply
/ Divide
% Modulus
++ Increment
Decrement
= Equals
== Is equal to
!= Is NOT equal to
< Less than
> Greater than
<= Less than or equal
>= Greater than or equal
&& and
|| or
! not

Conditional Statements

Conditional statements help make PHP a dynamic language, being able to put if statements into webpages allows for the generation of dynamic HTML. The common statements are described below:

If statement

The most common statement, the syntax for this is shown below

<HTML>
<BODY>
<?php
if ($x==$y)
echo $x . ” does equal ” . $y;
elseif ($x < $y)
echo $x . ” is less than ” . $y;
else
echo $x . ” does not equal ” . $y;
?>
</BODY>
</HTML>

Looping Statements

Loops are used to save repetition of code, instead a piece of code is used once and told to be repeated a number of times, or until a condition is met.

While statement

The While statement should be used when the number of iterations is unknown, the syntax is shown below

<HTML>
<BODY>
<?php
while ($x != $y)
{
$x++;
echo “X is ” . $x;
}
?>
</BODY>
</HTML>

The other method of writing a While loop is the dowhile loop. In this example the code is always run once before the do statement is reached.

<HTML>
<BODY>
<?php
do
{
$x–;
echo “X is ” . $x;
}
while ($x > 15);
?>
</BODY>
</HTML>

For Loop

This statement is used when the number of repetitions required is known.

<HTML>
<BODY>
<?php
for ($i=1; $i<=5; $i++)
{
echo “i is ” . $i;
}
?>
</BODY>
</HTML>

Foreach Loop

This is very similar to the For Loop above, however in this case the loop is done through an array which is passed into the loop.

<HTML>
<BODY>
<?php
$arr1=array(“dayone”, “daytwo”, “daythree”);
foreach ($arr1 as $value)
{
echo “Value is ” . $value;
}
?>
</BODY>
</HTML>

Arrays

Arrays are very useful data types which are commonly under used. an array can consist of any type of data that is required, is provides a better way of storing the data and opens up easier ways of using the data when in this format.

There are three different types of array:

  • Numeric Arrays – array where there is a number that references the position in the array when being accessed
  • Associative arrays – array where values are used to reference the location within the array
  • Multidimensional arrays – Simply an array with has more than one array within it

Numeric Array

Two different methods of creating these types of arrays, both yield the same result

<HTML>
<BODY>
<?php
$arr1=array(“dayone”, “daytwo”, “daythree”);

$arr2[0]=vaule1;
$arr2[1]=vaule2;
$arr2[2]=vaule3;

//Referencing the array is done the same way
echo $arr1[0];
echo $arr2[1];
?>
</BODY>
</HTML>

Associative Array

This array type does not use standard numbering that numeric array does (0, 1, 2, 3…), here the array entries are referenced by user defined values. Again there are two different ways of creating this array type.

<HTML>
<BODY>
<?php
$arr1=array(“dayone”=>28, “daytwo”=>25, “daythree”=>20);

$arr2['monday']= “11″;
$arr2['tuesday']=”12″;
$arr2['wednesday']=”13″;

//Referencing the array is done the same way
echo $arr1['dayone'];
echo $arr2['tuesday'];
?>
</BODY>
</HTML>

Multidimensional Array

The Multidimensional array is the most complicated of them all, when implemented a grid like array is formed. When implementing a multidimensional array the sub array of each array item does not have to be the same size, as shown below.

<HTML>
<BODY>
<?php
$streets = array(
“Highstreet”=>array(
“No1″,
“No5″,
“No10″,
),
“MiddleStreet”=>array(
“No100″
),
“LowStreet”=>array(
“No33″,
“No34″,
“No35″
)
);
?>
</BODY>
</HTML>

Forms

With the use of HTML forms and PHP, information can be passed between pages easily through using the different methods available.

A basic HTML form looks like the following:

<HTML>
<BODY>
<FORM action=”page2.php” method=”POST”>
Enter value1: <input type=”text” name=”value1″ />
Enter value2: <input type=”text” name=”value2″ />
<input type=”submit” />
</FORM>
</BODY>
</HTML>

Once submitted to page2.php the values can be shown with the following code:

<HTML>
<BODY>
Hello World<br>
<?php echo $_POST["value1"]; ?><br>
<?php echo $_POST["value2"]; ?>
</BODY>
</HTML>

The syntax $_POST changes to $_GET depending on the form method. The final piece of syntax is $_REQUEST, this contains values for $_GET, $_POST and $_COOKIE (discussed later)

Form Get method displays the data transferred between pages in the address bar, the advantage of this is the new page can be book-marked and each time opened the same data will appear. The disadvantage the limit of 100 characters per variable.

Form Post method does not display the data transferred between pages in the address bar, instead the data is piped directly between pages. in this case the new page can’t be book-marked successfully, however the variable size limit is not enforced.
Many thanks to the tutorials where this information came from, W3Schools & PHP

Dropbear SSH Server & Client

February 8th, 2009 No comments

The Dropbear SSH server and client supports industry standard SSH1 and SSH2 protocols and is available for various Linux distributions. Version 0.45 compiled for Debian PPC can be found here, this is what I have used as the SSH server for my Buffalo TeraStation.

The first step is to copy the files to the TeraStation, then extract them using the tar command

root@HD-HTGL113:/# cd /

root@HD-HTGL113:/# tar -xzf /mnt/array1/share/dropbear.tgz

The next step is optional, however in the interest of security recommended! This is to generate a new SSL public and private key for the server to use. Before we can do this the old keys need to be deleted

root@HD-HTGL113:/# rm /etc/dropbear/dropbear_rsa_host_key

root@HD-HTGL113:/# rm /etc/dropbear/dropbear_dss_host_key

root@HD-HTGL113:/# dropbearkey -t rsa -f /etc/dropbear/dropbear_rsa_host_key

root@HD-HTGL113:/# dropbearkey -t dss -f /etc/dropbear/dropbear_dss_host_key

The final step is to reboot the TeraStation, during startup the Dropbear SSH daemon will start. A recommended free SSH client to use is PuTTy

Categories: How to Tags: ,

Cygwin

February 8th, 2009 No comments

Cygwin is a Windows program that emulates a Linux like environment for your Windows PC, it is easy to install and provides modular approach to adding tools to the environment. The key to Cygwin working is the cygwin1.dll that gets installed, it provides a Linux API emulation layer for the applications that are specifically compiled for the Cygwin environment.

For more in-depth information into how the Cygwin application works see Cygwin

This article some key setup tips and how to configure what I find one the the most useful aspects; the SSH server with Cygwin.

Cygwin Tools in Windows Command Prompt

All of the default tools provided with Cygwin are very useful, however I did find my self trying to use Windows tools whilst in Cygwin and Linux tools whilst in Windows!

To solve this simply add the Cygwin bin folder (C:\cygwin\bin) into your Windows Path environment variable and there you go. From a command prompt you can use both the dir or ls commands depending on your mood.

Right Click on My Computer then select Properties

Choose Advanced then Environment Variables

Under System variables edit the variable Path and add the Cygwin bin folder,
i.e. ;c:\cygwin\bin

Setting-up SSH Access

When accessing you Windows PC remotely, it only supports full GUI access or unencrypted Telnet traffic. With Cygwin you can install the OpenSSH server which is an open source SSH connectivity tool supporting various well known featured including both SSH1 and SSH2 protocols.

The implementation below explains how to setup OpenSSH through Cygwin which will run a service on your Windows PC called CYGWIN sshd

Re-requisites required

When authenticating to your PC via SSH it will use the existing Windows user accounts to authenticate, the user account that you want to use must have a password set.
Ensure that Cygwin is installed along with the package called openssh

Add Environment Variables

Right Click on My Computer then select Properties

Choose Advanced then Environment Variables

Under System variables click New with the name of CYGWIN and a value of ntsec

Under System variables edit the variable Path and add the Cygwin bin folder, i.e. ;c:\cygwin\bin NB do not do this part again if you have already in the previous post.

SSH Host config

Open a Cgywin console and run command

ssh-host-config

When prompted, answer the following:

Privilege Separation answer yes

Create local user sshd answer yes

Install SSHD as a service answer yes

CYGWIN= answer ntsec

NB: The ntesc answer tells Cygwin to authenticate using the local Windows accounts

Start the SSH service to allow connections

The Windows service will default to start automatically every-time Windows starts, to start the service manually run one of the two commands

net start sshd
or
cygrunsrv –start sshd

Synchronise local Windows user information with Cygwin

Run the two commands from within Cygwin

mkpasswd –local > /etc/passwd

mkpasswd –group > /etc/group

Testing SSH Works

Use a SSH client such as PuTTy and then connect to localhost on port 22 (SSH Port)
Alternatively use the Cygwin SSH client:

cygwin# SSH user@localhost

NB: The port used by OpenSSH can be changed in the file c:\cygwin\ssh-host-config under port_number. After changing the port number you must re-start the CYGWIN sshd serivce for changes to come into effect.

Categories: How to Tags: ,