A simple Javascript Submit and Validation example

The following HTML script illustrates a simple Javascript validation and submit script that checks inputs on the PC before it is submitted to the server.  You might use this method on a web site before submission to the PHP script.  The Javascript displays a nice error message on submission if there are any errors and it is quite easy to add more tests when other text boxes are added.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Submit a form using Javascript with input validation</title>

<script language=”javascript” type=”text/javascript”>
<!–

//——————————————–
//Javascript that will submit the form when all entries are valid
function button_onclick(frmCreate) {

var themessage = “Error in entries : “;
var isOK = true;

if ( frmCreate.txtItem_Number.value == “” ) {
themessage = themessage + “\n” + “* Enter PayPal item code”;
isOK = false;
}

if ( frmCreate.txtItem_Name.value == “” ) {
themessage = themessage + “\n” + “* Enter PayPal item name”;
isOK = false;
}

if ( isOK == false ) {
window.alert(themessage);
} else {
frmCreate.submit(frmCreate);
}

}

//——————————————–
//Checks if the entry is numeric
function isNumeric(inputVal) {
numeric = true;
inputStr = inputVal.toString();
for (var i = 0; i< inputStr.length; i++) {
var oneChar = inputStr.charAt(i);

if (oneChar < “0” || oneChar > “9”) {
return false;
}

}

if (numeric == false) {
return false; }
else {
return true; }

}

//——————————————–
function LowerLimit_onblur(frmCreate) {
if ( !isNumeric( frmCreate.txtLowerLimit.value ) ) {
window.alert(“Enter a integer number”);
frmCreate.txtLowerLimit.value = “”;
frmCreate.txtLowerLimit.focus();
}
}

//–>
</script>

</head>
<body>

<!– START OF MAIN FORM –>
<form name=”frmCreate” method=”post” action=”test.html”>

<input type=”button” name=”Create” value=”Create” language=”javascript” onClick=”return button_onclick(frmCreate)” />

<br/><br/>
<table>
<tr>
<td>
<strong>Product Item Reference</strong>
</td>

<td>
<input type=”text” name=”txtItem_Number” />
</td>
<tr>

<tr>
<td>
<strong>Product Item Name</strong>
</td>

<td>
<input type=”text” name=”txtItem_Name” size=”50″ /><br/>
</td>
</tr>

<tr>
<td>
<strong>Enter lower limit</strong>
</td>
<td>
<input type=”text” name=”txtLowerLimit”  value=”5″ size=”3″  LANGUAGE=”javascript” onBlur=”return LowerLimit_onblur(frmCreate)” />
</td>

</table>
</form>
<!– END OF MAIN FORM –>

</body>
</html>

PHP File Handling Tutorial

PHP File handling Tutorial

The kinds of things that you will do with files include:

•    Reading and writing text in files.
•    Creating and deleting directories and file manipulation.

Part 1 – File permissions on the server

If you have to write data to a text file on a web server, or you have to copy, rename, delete or do any kind of file manipulation, the file or folder will require correct permissions.

To change file or folder permissions in Dreamweaver, open the site up in the remote view and right click on the file or folder.  Select permissions and then choose the kind of permissions that you want.  This would be 666 if you want to write and manipulate files.

This may not be necessary, as it may already be set on your web server.

Part 2 – Working with files

The typical way in which you will work with a text file is something like:

•    Open the file that you are going to work with by associating a file handle
•    Read or write to the file using the file handle
•    Close the file using the file handle.

Task 1 – Opening a file

(1)   In your text editor create a new PHP web page called file.php.  If you are using Dreamweaver, remove all the html code from the page.

(2)  Enter the following:

<?php

//file.php
$filename = “data.txt”;

if  (  !$fp = fopen($filename, “r”) )
{
die (“cannot open file $filename”);
}

fclose($fp);

?>

The $fp is the file pointer which is used for reading and writing operations.

(3)  Upload the file to your web space and run it in your web browser and see what happens.

(4)   Create a text file called data.txt and upload it to the web space and run file.php in your browser again.

The fopen() function

fopen() takes two arguments.  The first argument is the file name.  The file name can be relative to the location of this PHP file, or absolute with the full path name of the file in the form “/myfiles/www/data.txt” or it can be a url or an ftp path name to a different server.

The second argument is the mode which can be:

r   Read only access
r+ Read and write access
w Write access only
w+ Read and write access, any existing data will be lost if the file does not exit and PHP will attempt to create the file
a Appending only.  Write to the end of the file, if the file does not exist then PHP will attempt to create the file
a+ Open for reading and appending. Data is written to the end of the file, if the file does not exist, then PHP will attempt to create it.

Task 2 – Writing to the file

(1)  In file.php, change the mode from r to w+

(2)  Before the fclose() line enter the following:

(3)  fwrite($fp, “this is some text);

(4)  Your file will now look like:

<?php

//file.php

$filename = “data.txt”;

if  (  !$fp = fopen($filename, “w+”) )
{
die (“cannot open file $data.txt”);
}

fwrite($fp, “this is some text”);

fclose($fp);

?>

(5)  Upload the file to your web server, and run file.php in your web browser.  When you examine the data.txt file you should see the extra text.

Task 3 – Reading from the file

There are a number of ways of reading the contents of file.  One method is to read a block of characters into an array until the end of the file is reached

while ( !feof($fp) ) {
$lines[] = fgets($fp, 1024);
}

fgets($fp, 1024) means to read a line with up to 1024 bytes or until an end of line is found.

(1) Modify file.php with the above code added and an extra bit of code to display the text in the array.

The file.php code will now look like:

<?php

//file.php

$filename = “data.txt”;

if  (  !$fp = fopen(“data.txt”, “w+”) )
{
die (“cannot open file $data.txt”);
}

fwrite($fp, “this is some text\r\n”);
fwrite($fp, “this is some more text\r\n”);
fwrite($fp, “this is even more text\r\n”);

while ( !feof($fp) ) {
$lines[] = fgets($fp, 1024);
}

fclose($fp);

foreach ($lines as $key => $value) {
echo($value . “<br/>”);
}
?>

(2) Upload the file to the web server and run it in your web browser.  It should display the text that has been entered into the file.
Part 3 – File and folder manipulation

There are a number of PHP functions that can be used to work with files and folders.

Some of these functions may need permissions to be modified on the server to allow.

copy() copy a file
rename() rename a file
file_exists() shows if the file exists
basename() returns the base part of a file name

Simple transaction example using PHP and mysql_query

<?php
// A simple transaction example using PHP and mysql_query

//——————————————–
@mysql_connect(“localhost”,”myusername”, “mypassword”) or die(mysql_error());
@mysql_select_db(“mydatabase”) or die(mysql_error());
$query = “INSERT INTO mytable (firstname, lastname) values (‘Fred’,’Bloggs’)”;

begin(); // begin transaction
$result = @mysql_query($query);

if(!$result) {
rollback(); // failed so roll back transaction
echo “Rolled back”;
exit;
}
else
{
commit(); // Committ transaction
echo “Transaction completed”;
}
//——————————————–

//——————————————–
function begin() {
@mysql_query(“BEGIN”);
}

//——————————————–
function commit() {
@mysql_query(“COMMIT”);
}

//——————————————–
function rollback() {
@mysql_query(“ROLLBACK”);
}

?>

The above code illustrates the use of transactions with mysql_query code.

About htpasswd – The file to store passwords

The htpasswd file is used when password protecting a website or a directory using HTTP Authentication and Apache’s htaccess files.

The htpasswd file contains username in plain text (unencrypted) and a hashed (encrypted) password.

Each line contains a username and a password separated by a colon “:”. You can not see the actual passwords as they are hashed (encrypted) using a complex algorithm. The default algorithm is different from platform to platform. On Windows the passwords are hashed using MD5, and on Linux its based on a system function called “crypt()”.

Normally the htpasswd file is named .htpasswd, but you can name your password file what every you like. You could call it “passwords.txt”, however, Apache is usually configured to prevent access to .ht* files – starting with “.ht”. If you name your password file “passwords.txt”, a user could access it, and retrieve all valid usernames. Since the passwords are hashed he can’t use them directly, but it will help him gain access using brute force.

It is therefore recommended to name a password file .htpasswd.

Hashed passwords can be generated with the command-line tool htpasswd (htpasswd.exe on Windows) which is part of a normal Apache installation. You can also create passwords yourself using PHP.

get_magic_quotes_gpc in PHP6

In PHP6, get_magic_qu0tes_gpc will be depreciated, but you may still want to be able to test for it if you do not know which version of PHP it will be running on.

Here are two possible ways of how this might be done.  Both of these create a new function called is_get_magic_quotes_gpc to make it easier to search and replace in a number of files.

First method :

<?php

/**
Returns true if have to make allowances for magic quotes or not
Returns true if magic quotes are on false otherwise
Test which version of PHP you have and make allowences as appropriate
**/
function is_get_magic_quotes_gpc() {

if ( version_compare(phpversion(), ‘6’, ‘<‘) ) {

if ( get_magic_quotes_gpc() ) {
return true;
}
else
{
return false;
}

}
else
{
return false;
}

}
?>

Second method :

<?php

/**
Returns true if have to make allowances for magic quotes or not
Returns true if magic quotes are on false otherwise
Test if the function exists or not and then make allowances as appropriate
**/
function is_get_magic_quotes_gpc() {

if ( function_exists(“get_magic_quotes_gpc”) )
{
if ( get_magic_quotes_gpc() ) {
return true;
}
else
{
return false;
}
}
else
{
return false;
}

}

?>

Both of these can be tested using :

<?php

if ( is_get_magic_quotes_gpc() ) {
echo(“yes”);
}
else
{
echo(“no”);
}

echo(“<p>php version : ” . phpversion() . “</p>”);

?>

Get auto-incremented value with PHP / mySQL

When you do an insert SQL statement which creates a new record, you often want to return the value of the auto-incremented field.

You can do this in PHP by:

$recid = mysql_insert_id(); //Return the number of the automatically incremented field after the insert statement

this is done after your mysql_query($sqlquery); statement

Differences between PHP4 and PHP5

This listing of the differences between PHP4 and PHP 5 is is probably something that is quite common, but it is always worth a review.

PHP5 is a lot different than PHP4 with the main differences being in how it handles objects and classes.

Here are 10 major differences between PHP4 and PHP5 that you need to know:

1. Unified Constructors and Destructors:

In PHP4, constructors had same name as the class name. This used to cause overhead because every time you changed the class name, you had to change all the occurrences of that name.

In PHP5, you simply need to name your constructors as __construct(). (the word ‘construct’ prefixed by double underscores). Similarly you can name your destructors as __destruct(). (the word ‘destruct’ prefixed by double underscores.) In destructors, you can write code that will get executed when the object is destroyed.

2. Abstract Class:

PHP5 lets you declare a class as ‘Abstract’. (i.e. a class whose object cannot be created. You can only extend an abstract class) Also, a class must be defined as abstract if it contains any abstract methods. And those abstract methods must be defined within the class which extend that abstract class. You can include complete method definitions within the abstract methods of abstract class.

3. Final Keyword:

PHP5 allows you to declare a class or method as ‘Final’ now. You just need to use ‘final’ keyword that will indicate that the class cannot be inherited or the method cannot be overridden.

4. Exception Handling:

PHP5 has introduced ‘exceptions’. An exception is simply a kind of error and the ‘exception error’ can be handled in an exception object. By using an exception, one can gain more control over the simple trigger_error notices we were stuck with before.

When you are about to perform something ‘risky’ in your code, you can surround your code with a ‘try…catch’ block. First you surround your code in a ‘try {…….}’ block, then if an exception is thrown, your following ‘catch{……}’ block is there to intercept the error and handle it accordingly. You can write some PHP code in your ‘catch’ block which will get executed when an error occurs in the ‘try’ block. If there is no ‘catch’ block, a fatal error occurs.

5. E_STRICT Error Level:

PHP5 introduces new error level defined as ‘E_STRICT’ (value 2048). This error levels notifies you when you use depreciated PHP code. It is not included in E_ALL, if you wish to use this new level you must specify it explicitly.

6. Autoloading (the __autoload() function):

PHP5 introduces a special function called ‘__autoload()’ (the word ‘autoload’ prefixed by double underscores). This function allows you to avoid writing a long list of includes at the top of your script by defining them inside this function. So you can automatically load object files when PHP encounters a class that hasn’t been defined yet.

Example:

function __autoload ($class_name) {

include $class_name . ‘.php’;

}

7. Visibility:

In PHP5, class methods and properties now have ‘visibility’. There are 3 levels of visibilities:

Public: ‘Public’ is the most visible. Methods are accessible to everyone including objects outside the classes. And properties readable and writable by everyone including objects outside the classes.
Private: ‘Private’ makes class members only available to the class itself.
Protected: ‘Protected’ makes class members accessible to the class itself and any inherited class (subclass) as well as any parent classes.

PHP4′s method of declaring a variable as ‘var’ keyword is still supported in PHP5. The ‘var’ keyword is now a synonym for the ‘public’ keyword now.

8. Pass by Reference:

In PHP4, everything was passed by value, including objects. Whereas in PHP5, all objects are passed by reference. Take a look at this PHP4 code for example –

$peter = new Person();
$peter->sex = ’male’;

$maria = $peter;
$maria->sex = ’female’;

echo $peter->sex; // This will output ‘female’

As you can see in the code above, if you wanted to duplicate an object in PHP4, you simply copied it by assigning it to another variable (Pass by value). But now in PHP5 you must use the new ‘clone’ keyword. So the above PHP4 code, will now look like this in PHP5 –

$peter = new Person();
$maria = new Person();

$peter->sex = ’male’;

$maria = clone $peter;
$maria->sex = ’female’;

echo $peter->sex; // This will output ‘female’

9. Interfaces:

PHP5 introduces ‘interfaces’ . An interface defines the methods a class must implement. All the methods defined in an interface must be public. An interface helps you design common APIs. It is not designed as a blueprint for classes, but just a way to standardize a common API. A big advantage of using interfaces is that a class can implement any number of interfaces. You can still only ‘extend’ on parent class, but you can ‘implement’ an unlimited number of interfaces.

10. New Functions:

PHP5 introduces new functions which are not found in PHP4. You can find the list of these new functions in the PHP manual.

Simple example of a class in PHP

A simple example of a class in PHP
<?php # person

class person {

public function __construct( $name, $age, $height, $weight )
{
$this->name   = $name;
$this->age    = $age;
$this->height = $height;
$this->weight = $weight;
}

// functions that return information

public function get_name()
{
return $this->name;
}

public function get_age()
{
return $this->age;
}

public function get_height()
{
return $this->height;
}

public function get_weight()
{
return $this->weight();
}

// functions that change the object.

public function change_name( $name )
{
$this->name = $name;
}

public function add_weight( $weight )
{
$this->weight = $this->weight + $weight;
}

public function lose_weight( $weight )
{
$this->weight = $this->weight – $weight;
}

}

//Initialise a person
$paul = new person(‘Paul Gibbs’, 17, ‘6\’1″‘, 210);

$john = new person(‘John Smith’, 36, ‘5\”, 160);

echo(“<br/>”);

print_r($paul);

echo(“<br/>”);

echo(“Loose 10 pounds from this person<br/>”);

$paul->lose_weight(10);

echo(“<br/>”);

print_r($paul);

echo(“<br/>”);

//A possible use :

$people = array($paul, $john);   //Create an array of people

foreach( $people as $person ) {
echo “This persons name is ” . $person->get_name() . “<br/>”;
echo “This person is “.$person->get_age().” years old.<br/>”;
}

class employee extends person {

public function __construct($name, $age, $height, $weight, $salary, $startdate)
{
parent::__construct($name, $age, $height, $weight);

$this->salary = $salary;
$this->startdate = $startdate;

}

public function get_salary()
{
return $this->salary;
}

public function get_startdate()
{
return $this->startdate;
}

}

$pete = new employee(‘Pete Coles’, 22, ‘6’, 200, 20000, 2012-06-04);

echo(“<br/>”);

print_r($pete);

?>

magic_quotes, addslashes(), and stripslashes() and PHP 6

magic_quotes_gpc, when on, automatically adds slashes to all GET/POST/COOKIE data so that you don’t need to use addslashes() before using GET/POST/COOKIE data in MySQL queries, etc. (e.g. with magic_quotes_gpc OR addslashes(), I’m becomes I\\’m). Well, magic_quotes_gpc is no convenience and just complicates things!

Since magic_quotes_gpc can be on or off, you don’t know whether to use addslashes() or not. You don’t want to use addslashes() when magic_quotes_gpc is on because you’ll add too many slashes (e.g. I’m becomes I\\\\’m), which is bad. Use addslashes() if magic_quotes_gpc is off, and don’t if it’s on (you can find out its setting with get_magic_quotes_gpc()). But you can’t use the same code all the time. One workaround is something such as:

if (!get_magic_quotes_gpc()) { $txt = addslashes($txt);

Using magic quotes has always been confusing and in PHP 6 they are apparantly going to remove it.  So it is better to program your scripts without using get_magic_quotes_gpc at all.