Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Thursday, June 10, 2010

Submit a form without refreshing the page with Jquery and PHP

Lately, I’ve been chancing on quite a number of posts at various places asking about how to perform a web action without the webpage reloading/refreshing? For example, dynamically updating a list on a page without a reload or submitting a form to PHP without leaving the webpage the form sits on.

I guess this is as good a time to start branching into some posts on PHP and Javascript, or more specifically, jQuery.

To be honest, I’ve never been partial to using Javascript (ie client-side programming) in my web applications, prefering instead to rely on server-side processing for all my programming needs. I guess this has to do with my frustrations of Javascript incompatibility between different browsers back in the day. However, with a javascript library (or framework) like jQuery, I’m starting to use more client-side actions to complement all the server-side PHP stuff. Here’s 6 reasons why you should use JavaScript Libraries & Frameworks.

You can download my example source code if it helps you understand how the whole thing works.

Download: download icon

And here’s a demo of what we’re trying to do.

The traditional way of doing form submissions
Back in the “old” days, in order to perform a form submission, you need to do something like this.

When you click the “Submit” button on form.php, the web server knows to send the name and email values using the POST method to the php script called process.php. The web server will loadprocess.php page and the PHP script will start to read in the form values posted from form.php, maybe perform some validation to check that the information received is correct, then perhaps do something with the form values such as storing it in a database or sending it via email and output a “thank you” message.

What if something goes wrong, for example, the person submitting the form wrote in a badly-formed email address, the validation at process.php will throw a nicely worded error message and stop running the rest of the script. The person then would need to go back to the form to correct the email address and he would submit the form again.

This might have been an OK way of doing things 10 years ago, but in this era of Facebook and Twitter, that’s a pretty antiquated and tedious method.

The jQuery way of doing form submissions
Here’s the jQuery way, which is made possible by something called AJAX (which stands forAsynchronous JavaScript and XML). AJAX is bascially the technology that makes it possible to exchange data with a server, and update parts of a web page – without reloading the whole page. jQuery includes the necessary functions to implement AJAX into your web application.

The diagram looks quite similar to the “old” way of doing things, except that process.php is now represented by a ‘circle’. This is because process.php is now hidden for lack of a better word. In the traditional method, when you click the submit, your browser will load process.php and it will jump from form.php to process.php.

With the jQuery/AJAX way, process.php becomes a background process which the web server will call on, and when you click on the “Submit” button, form.php pushes the data to process.php, but your browser will remain showing form.php. Once the process.php has done what it needs to, it will return to form.php some output to be displayed.

Here’s the source code for form.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html>
<head>
	<title>JQuery Form Example</title> 
	<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
	<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
	<script type="text/javascript">
	$(document).ready(function(){
		$("#myform").validate({
			debug: false,
			rules: {
				name: "required",
				email: {
					required: true,
					email: true
				}
			},
			messages: {
				name: "Please let us know who you are.",
				email: "A valid email will help us get in touch with you.",
			},
			submitHandler: function(form) {
				// do other stuff for a valid form
				$.post('process.php', $("#myform").serialize(), function(data) {
					$('#results').html(data);
				});
			}
		});
	});
	</script>
	<style>
	label.error { width: 250px; display: inline; color: red;}
	</style>
</head>
<body>
<form name="myform" id="myform" action="" method="POST">  
<!-- The Name form field -->
    <label for="name" id="name_label">Name</label>  
    <input type="text" name="name" id="name" size="30" value=""/>  
	<br>
<!-- The Email form field -->
    <label for="email" id="email_label">Email</label>  
    <input type="text" name="email" id="email" size="30" value=""/> 
	<br>
<!-- The Submit button -->
	<input type="submit" name="submit" value="Submit"> 
</form>
<!-- We will output the results from process.php here -->
<div id="results"><div>
</body>
</html>




and the source code for process.php



<?php
	print "Form submitted successfully: <br>Your name is <b>".$_POST['name']."</b> and your email is <b>".$_POST['email']."</b><br>";
?>




Here’s what’s happening


I included jQuery’s form validation because it provides a more real world example. Usually, most sites will perform processes like form validation at the client-side before the form is submitted. It’s just more intuitive and a much better user experience. In fact if you can offload as much workload as you can to the browser, it will greatly reduce the hit on your server.



So here’s a quick high-level walk through what’s happening on the jQuery part.





I call the validate method (make sure you have included the jquery validate plugin – see form.php Line 6) on my form #myform, and proceed to define what to validate. In this case, we’re checking that the name field is ‘required’, and we’re checking the email field is not only ‘required’, but must be an email format. I also define the custom error message I want to display if the validation fails.



Lastly, the submitHandler is what gets processed if the validation is successful. In this case, I’m doing an ajax post method, sending my form data to process.php, and get back any results as HTML data which will be displayed into #results.



Over at process.php, I’m simply printing out the data received to show you the information was sent and returned.



That’s basically it. If you want to know more, do check out the jQuery website to get more details on how to do AJAX and Validation.



Feel free to comment your thoughts or suggestions.

read more...

Monday, June 7, 2010

Top 10 free PHP and Perl Forum Scripts

PHPBB

Since its creation in 2000, PhPBB has become the most widely used Open Source forum solution. Like its predecessors, PhPBB 3.0 "Olympus" has an easy to use administration panel and a user friendly installation process, which allows you to have a forum set up in minutes. With a large and highly customisable set of key features coupled with a standards compliant interface, PhPBB will grow with, and complement your website. With millions of installations worldwide, it is no wonder PhPBB is one of the most popular ways to create and support a community.

Documentation: Good documentation covering all aspects and customizing of PHPBB forum.

Community: Community is rather large and active. You can find lot of themes created by users,

License: GPL.

Last releases: 3.0.5.

Size:2.3mB.

Project example: Aprelium

Simple Machines Forum

Simple Machines Forum - SMF in short - is a free, professional grade software package that allows you to set up your own online community within minutes. Its powerful custom made template engine puts you in full control of the lay-out of your message board and with our unique SSI - or Server Side Includes - function you can let your forum and your website interact with each other.

Documentation: Good.

Community: Community includes several active forums and chat.

License: Simple Machines License

Last releases: 1.1.9

Size:1.4mB

Project example: Dynamic Systems Portal

PunBB

PunBB is a fast and lightweight PHP-powered discussion board. Its primary goals are to be faster, smaller and less graphically intensive as compared to other discussion boards. PunBB has fewer features than many other discussion boards, but is generally faster and outputs smaller, semantically correct XHTML-compliant pages

Documentation: There is large wiki with documentation.

Community: Laarge community includes several forums, wiki and international support.

License: GPL.

Last releases: 1.3.4

Size:302kB

Project example: Movie Discussion

Vanilla

Vanilla is an open-source, standards-compliant, multi-lingual, fully extensible discussion forum for the web.

Documentation: Compact and clear documentation

Community: One but large and active forum.

License: GPLv2

Last releases: 1.1.8

Size:509kB

Project example: OpenDNS Forums

SEO-Board

SEO-Board is a forum software that's fast, free, and search engine friendly. It is the perfect solution for small and medium-sized sites.

Documentation: Compact manual describing all basic functions of forum.

Community: Several forums.

License: License statements described in the manual.

Last releases: 1.1.0

Size: 98kB

Project example: The Armenian Church

aterr

aterr is an open source threaded forum system; allowing registered visitors to express their opinions, discuss topics, and debate with other visitors. A threaded forum system differs from regular, flat forum systems in that once posted, a thread can fork, allowing visitors to reply directly to other posts. aterr also provides a customisable permissions system, the ability to nest forums, and moderation tools.

Documentation: Weak. Small instruction how to install forum.

Community: Community includes support forum and IRC channel

License: GPLv2

Last releases: 0.9.3

Size: 78kB

Project example: Neoteric Hovercraft Forums

Unclassified NewsBoard

The Unclassified NewsBoard (short UNB) is an open-source, PHP-based internet bulletin board system, mostly like those you may already know. But the difference is in a lot of details that make your life with this board, both as administrator and user, much easier.

Documentation: Medium. Documentation covers only basic operations with forum.

Community: Several active forums.

License: GPL

Last releases: 1.6.4

Size: 780kB

Project example: Deutsche Abandonware Gruppe

bbPress

bbPress is plain and simple forum software, plain and simple. It's easy to use, easy to administrate, fast and clean. But don't let its simplicity deceive you; underneath the gleam, it's got some powerful features and is highly customizable.

Documentation: Documentation is clear and compact.

Community: You can find developers s blog and active forum on the bbPress site. Also there is a mailing list and IRC channel.

License: GPL2

Last releases: 0.9.0.5

Size: 343kB

Project example: Atsutanes forums.

FluxBB

FluxBB is a free open source forum application designed to be fast, light and user friendly. FluxBB's code, written in PHP, has a proven track record of stability and security.

Documentation:Wiki with documentations and tutorials.

Community: Several forums and wiki.

License: GPL.

Last releases: 1.2.21

Size: 159kB

Project example: Arcade History

ikonBoard

Ikonboard is a comprehensive web bulletin board system. It transcends the limits imposed by other bulletin board software, allowing you to create a truly unique community on your website. From it's extensive template and skins features to it's complete multi-lingual support, your members will keep coming back for more.

Documentation: Short installation gude.

Community: Several forums and knowledge base.

License: Free and commercial.

Last releases: 3.1.5

Size: 1.6mB

Project example: Lynx Airways Worldwide Headquarters

read more...

Thursday, May 27, 2010

All Time Top 10 User Rated PHP Classes

Yestutor Picks the All time Top 10 User Rated PHP Classes from PHP Classes.These classes are rated 1 to 10 according to user likeness and voting.

The list include

1. Image Processor (CSS)

2. MIME E-mail message sending,

3. REST Server

4 Forms generation and validation

5 SMTP E-mail sending class

6 Constant Management class

7 EmbeVi

8 CCValidator

9 MIME E-mail message parser

10 IDNA Convert

Image Processor (CSS)

This class can be used to draw images defined with CSS like properties.
It can create an empty image or open and existing image from a file.
The class can draw different types of primitives using CSS like style strings to define the parameters of those primitives.
Currently it can draw text strings, other images like watermarks, lines, rectangles, circles, ellipses, etc..
The generated image can also be cropped and resized before it is saved to a file.

MIME E-mail message sending

Class that may be used to compose and send e-mail messages.

It features:

- User definable headers and body parts.
- MIME encoding of text and HTML body parts with user defined character encoding using quoted-printable.
- Addition of file parts (attachments) with automatic content type detection.
- Forwarding of messages received from somebody else as intact attachments
- Support for multipart/related messages (eg. HTML messages with embedded images, stylesheets, frames, etc..)
- Support for multipart/alternative messages (eg. text and HTML versions in the same message).
- Encoding of message headers with user defined character encoding using q-encoding.
- Definition of the error delivery address setting the Return-Path header calling sendmail program directly.
- Several sub-classes for sending messages by different methods: PHP mail() function, sendmail, qmail, SMTP (with support for authentication and direct delivery mode), maildrop in Microsoft IIS or Exchange Pickup folder.
- Wrappers that emulate the mail() function using the SMTP, sendmail and qmail delivery sub-classes.
- Support for sending personalized bulk mail by replacing the contents of the message parts that differ for each recipient.
- HTML and plain text message parts can be composed using template engines. An example that works with Smarty template engine is provided.
- Retrieving the composed message data or size without sending the message

REST Server

This package can be used to implement REST Web services servers.
It uses a model-view-controller (MVC) implementation to route REST GET, POST, DELETE and URL to controllers classes.
It also provide helpers for handling HTTP requests, response, headers, MIME types and authentication.
It uses decoration instead of inheritance, so do not have to extend any classes to implement your servers.
No configuration files, custom .htaccess files or naming conventions are necessary.

Forms generation and validation

Class that generates HTML forms supporting:

- Multiple inputs may be interconnected in such way that client side events that occur on one input can trigger actions on the context of other inputs. Developers may use input interconnection support without writing Javascript code.
- Can be extended with new types of input controls plug-in classes.
- Custom input plug-in classes can be used to support for handling client site events on the server side without submitting the form or redrawing the whole form page
- Some control plug-in classes are made available:
* AJAX based form submission (without reloading the whole page)
* Auto-complete text inputs
* Select a location on a map using Google Maps API
* Calendar date input
* CAPTCHA test to prevent automated access by robots
* Linked select input to switch select options when the value of another input changes. An unlimited number of selected can be linked in cascade. Additional plug-in subclasses are provided to retrive option groups from a MySQL database or many other SQL databases using the Metabase PEAR::MDB2 PHP database abstraction layer APIs
* Manage animations that apply visual effects to the page form elements, like: fade-in, fade-out, show, hide, update content, etc..
- XHTML compliant output.
- Load submitted form field values even with register_globals option Off and strip slashes when magic_quotes_gpc option is On.
- Keyboard navigation support:
* Attachment of labels with activation keys to each form field.
* Tab navigation order index.
- Built-in server side (PHP based) and client side (Javascript 1.0 or better) field validation for:
* E-mail address
* Credit card numbers (Visa, Mastercard, American Express, Discover, Diners Club, Carte Blanche, enRoute, JCB, any of these or even determined by a select field).
* Regular expressions.
* Field not empty.
* Field equal to another (useful for password confirmation fields).
* Field different from another (useful for reminder fields that must not be equal to the actual password).
* As set (for check boxes, radio buttons and select multiple fields).
* As integer number (with range limitation).
* As floating point number (with range limitation).
* Programmer defined client and server validation functions.
- Highlight invalid fields rendering them distinct CSS styles
- Security attack prevention by optionally discarding invalid values passed in fields that could not be edited by users but may be spoofed by attackers.
- Option to define a value that, when used in a field, it is accepted without performing any of the validations defined for the field.
- Ability to stop the user from submiting a form more than once inadvertdly.
- Sub form validation (validate only smaller set of field depending on the submit button that was used).
- Composition and generation of the form HTML output with fields displayed as fully accessible or in read-only mode.
- Generation of Javascript functions (useful to set to the page ONLOAD event):
* Set the input focus to a field.
* Select the text of a field.
* Set the input focus and select the text of a field.
* Enable and disable input fields
- Automatic capitalization of the text of a field:
* Upper case.
* Lower case.
* Word initials
- Replacement of text field expressions to perform adjustments like trimming whitespace or auto-complete values based on rules defined by regular expressions
- Compose forms with templates using plain HTML files with embedded PHP code or using the Smarty template engine with a supplied pre-filter plugin
- Etc.

SMTP E-mail sending class

Class that connects to a SMTP mail server to send messages.
It features:
- Relaying message delivery to a programmer defined SMTP server.
- Programmer defined server address, server port, connection timeout, origin host address.
- Support for authentication methods PLAIN and LOGIN.
- Support for POP3 based authentication before delivery.
- Direct delivery to one or more recipients with e-mail addresses with the same domain, so you do not need to relay on a own or your ISP SMTP server.
- Setting sender and recipient address as a separate step from the sending the headers and the body of the message.
- Returns message delivery success.
- Detects extensions supported by the SMTP server.
- Takes advantage of the SMTP PIPELINING extension to buffer SMTP commands, therefore minimizing SMTP dialogue between the class and the server in order to provide a much faster queueing of messages to be delivered to a large amount of recipients ( bulk mail ).
* Note: this class is better used in conjunction with the class “MIME E-mail message composing and sending class”. See in the Email group.

Constant Management class

This is a simple class that can be used to define constant values that can be updated.
It can store and retrieve values from global variables with unique names based on a constant name key. If the constant is already defined, the class can update its value

EmbeVi

This class can be used to embed remote videos and audio in HTML pages.
It takes the URL of a video or audio page of a remote site and generates HTML for embedding a player for that video or audio clip in another page.
Currently it supports embedding videos and audio clips from:

- YouTube,- 220.ro,- Google video- Dailymotion- Trilulilu- Metacafe- College Humor- Cnet- Glumbert- Yahoo
- MySpace- LiveLeak- Vimeo- GameTrailers- UStream- ClipsHack- FunnyOrDie- FileBox- Last.fm- Youku- Rediff
- Rambler.ru- Tudou- ku6- TinyPic- Libero.it- ESPN- NFL- Web.de- eksenim.mynet- RuTube- LiveVideo- Vbox7
- Revver- Current- dalealplay- ClipFish.de- Clip.vn- LiveStream- Tangle- Vidiac- 5min- vol.at- WeGame- ikbis
- YouMaker- Snotr- OneTrueMedia- clevver- kewego- Clipser- DailyHaHa- HowCast- Aniboom- Bragster- TeacherTube
- ShredOrDie- TalentRun- Autsch.de- tvbvideo.de- Clipmoon- Viddyou- SpyMac- YouAre.tv- MindBites- JujuNation
- RoofTopComedy- Hamburg1Video.de- Caught-on-Video- Bubblare.se- Jaycut- Spotn.de- TheXvid- Scivee.tv- Tvosz
- DailyComedy- DeutschlandReporter.de- MotorSportMad- RheinVideo.de- SelfCastTV- MyUbo.sk- GettyLoad.de
- ClipHost24- UvuVideo.org- CroVideos- QubeTV.tv- CityTube.de- ConstantComedy- Luegmol.ch- MantouTV
- CloneVideos- Realitatea.net- MTV- RockTube.us- MyPlay- 123Video- 9You- Blastro- Cellfish- Clarin- ClipJunkie
- ClipLife.jp- TheDailyShow- ComedyCentral- ColbertNation- CrunchyRoll- DotSub- DivShare- FanDome- G4TV
- GameSpot- GameTube- Gloria.tv- GotGame- Guzer- Izlesene- Joost- Justin.tv- Koreus- Machinima
- MSNBC- Mail.ru- MadnessVideo.net- Milliyet.tr- MoFile- Mpora- SeeHaHa- MThai- OnSmash- Playlist.com
- RawVegas.tv- ScreenToaster- SevenLoad- ShareView.us- Smotri- SouthParkStudios- Spike- CBSSports- Tagtele
- TM-Tube- TRTube- Videolog.uol.br- U-Tube.ru- Sapo.pt- Videonuz- Vidmax- Vsocial- Goear- IJigg- Jamendo
- JujuNation- Last.fm- Nhaccuatui

CCValidator

This class can be used to validate credit card numbers.

It checks the integrity of the number by using the mod 10 algorithm.
The class can also check a credit card number of a given card type by looking at the number prefix. Currently it can check whether the card type is: VISA, Mastercard, American Express, Diners Club, Discover or JCB.

MIME E-mail message parser

This class can be used to parse and decode MIME e-mail messages.
It supports decoding single RFC 2822 MIME messages or archives that aggregate multiple messages in the mbox format.
The decoded message data is returned as an array that describes one or more messages found in a message file or data string.
The bodies of multipart messages can be decoded into distinct sub-messages.
The message body data can decoded and saved to separate files, so the class can handle messages larger than the available memory.
The parser can tolerate some syntax errors in malformed messages that are not compliant with RFC 2822.
An auxiliar class is provided to parse and extract e-mail address lists from message headers.

IDNA Convert

IDNA stands for Internationalized Domain Names for Applications. It is a standard described in RFC 3490, RFC 3491 and RFC 3492. It is used to allow language specific characters in domain names, like the umlauts in German, accents in latin languages like French, or even chinese characters.
This class allows you to convert domain names between the encoded Punycode notation and the decoded 8bit (UTF-8) notation. It simplifies the use of domain names defined with IDNA in applications or scripts.

read more...

Wednesday, May 12, 2010

PHP Programming Tricks for beginners

I'll be presenting a couple of nice PHP Programming Tricks in this page. You can take a look at the various tricks in these sub pages.

Force a secure HTTP connection

if (!($HTTPS == "on")) {

header ("Location: https://$SERVER_NAME$php_SELF");

exit;

}

Get the date

$today = getdate();

$month = $today['month'];

$mday = $today['mday'];

$year = $today['year'];

Random Loading

You can load random stuff by using this code. For this example, I load random color code:

$selectnumber = rand (1, 5);

if($selectnumber==1) $pagebg="#990000";

if($selectnumber==2) $pagebg="#0000FF";

if($selectnumber==3) $pagebg="#00AAAA";

if($selectnumber==4) $pagebg="#000099";

if($selectnumber==5) $pagebg="#DDDD00";

Easy Way to List Directory Structure

$path = "/home/user/public/foldername/";

$dir_handle = @opendir($path) or die("Unable to open $path");

while ($file = readdir($dir_handle)) {

    if($file == "." || $file == ".." || $file == "index.php" )

        continue;

        echo "<a href=\"$file\">$file</a><br />";

    }

closedir($dir_handle);

Easy Way to Optimize Database Table

dbConnect()

$alltables = mysql_query("SHOW TABLES");

while ($table = mysql_fetch_assoc($alltables))

{

   foreach ($table as $db => $tablename)

   {

       mysql_query("OPTIMIZE TABLE '".$tablename."'")

           or die(mysql_error());

   }

}

Create a password protect webpage

<?

$username = "someuser";

$password = "somepassword";

if ($_POST['txtUsername'] != $username || $_POST['txtPassword'] != $password) {?>

<h1>Login</h1>

<form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

      <p><label for="txtUsername">Username:</label>

      <br><input type="text" title="Enter your Username" name="txtUsername"></p>

      <p><label for="txtpassword">Password:</label>

      <br><input type="password" title="Enter your password" name="txtPassword"></p>

  <p><input type="submit" name="Submit" value="Login"></p>

</form>

<?} else {?>

    <p>This is the protected page. Your private content goes here.</p>

<?}?>

read more...

Five HTML5 n CSS3 Templates n Frameworks

Here you will find a collection of visually basic templates, but with all of them fully packed and enriched with CSS3 and HTML5 goodness.

HTML5 Basic Template Pack

27109_119561454723199_100000080361933_310659_7985108_n

This template has been heavily inspired by the Smashing Magazine HTML 5 template tutorial, however the (CSS & Design) has been modified in several ways.
This basic template comes in 4 colors (green, blue, purple and orange) with easy to customize CSS and HTML 5, HTML5 mouse over effects, HTML 5 text shadow and much more.

View

Cherry Blossoms HTML5 & CSS3

html5css3_template_03

Home : Demo

Backwards Compatible, One Page Portfolio (Template and Tutorial)

html5css3_template_05

Home : Demo

ZooCroo HTML5 & CSS3

html5css3_template_07

ZooCroo is a fun, playful and colorful template that utilizes HTML5 and CSS3, with a little extra fun thrown in. The nerd images in the content are animated, using CSS3’s transform properties. Hovering over the little nerds will rotate one and slide one right. This is, of course, assuming your browser is able to understand CSS3’s transform code.

Home : Demo

Rockit HTML5 & CSS3

html5css3_template_09

Rockit is a 2 column grungy music-inspired template that makes use of CSS3 transform to create a cool rotating polaroid effect for a set of images. For browsers that understand this effect, hovering over each polaroid image will rotate it to the left a bit. For browsers that aren’t yet up to speed, the images will still have the polaroid-like frame around them, but just won’t rotate on hover

Home : Demo

read more...