My Thoughts and Know-how

Displaying entries tagged with 'www'. Show all

Web Forms

1 May 2011

One of the places where HTML, JavaScript and PHP are in perfect harmony is web forms.

Forms are defined by the form tag and can contain most of the other HTML tags. Out of those, input elements (such as text boxes) pass data to the server. The name attribute of an input element can be thought of as a variable which the web server reads. For example:


<form action="comments.php" method="post" name="myform">
	<input type="text" name="email"/>
	<input type="submit"/>
</form>

will generate a textbox with a button. After the user clicks the button, the server can read the text from within comments.php via $_POST[email].

There are actually two methods which post the data:

  • GET: The variables are appended by the browser to the address such as "script.php?var1=value1&var2=value2
  • POST: The variables are passed via the HTTP protocol rather than as part of the URL.
Both of those are readable in PHP by the $_GET and $_POST global hashes. If the page expects either, $_REQUEST contains their union.

What's sleek about forms is that it is trivial to add client-side error checking in JavaScript. This will not replace proper server-side verification as it is easy to bypass, but might help reduce unneeded server load and annoyance of the user while waiting for the page to refresh. We need to define a boolean-returning function and add onsubmit="return checkEmail()" to the from declaration. If checkEmail() returns true, the form is submitted, otherwise the button click is silently ignored. I used:


function checkEmail()
{
	if(!document.myform.email.value.match("^.+@.+\..{2,4}$")) {
		alert("Please enter a valid email.");
		return false;
	}

	return true;
}

where we use the convenient match() method of the String object to test the string against a Perl regular expression.

This was my web forms in a nutshell. You can see & test the complete implementation in the blog's comments by using them :)


www computers Comment

The Making of a Blog

25 April 2011

How much code does a blog take?

1.8KB. It might be simple but this includes its PHP, HTML and CSS.

My minimalistic blog is quite simple. It uses PHP's built-in parse-ini-file() to parse an .ini file (which stores all blog entries) into a hash. The keys are the sections of the .ini file and the values are themselves hashes that contain the sections' value-pairs.

All that is left is a for-loop that iterates over the top-level hash to generate 3 rows of a HTML table at a time. The upper row contains the heading and the date, the middle one has the body text while the lower is for the comments link.


$contents = parse_ini_file('entries.ini', true);

foreach ($contents as $header => $data) {

	echo "<tr style=\"background: $data[color];\">";

	...

}


www computers Comment
Home Top
visits.