preventing multiple form submission with php

preventing multiple form submission with php

A dynamic web aplication contains atleast a web form that stores data in any database. major issue is data redundancy . we discussed already in my previous post preventing multiple form submission with javascript.
even though it works partially ,we can prevent it by server side also .
we use two methods to prevent multiple form submission

Redirecting user to another page

when a form submitted to server, we process the input and send user to another success full or error page.

using hidden field

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php 
session_start();
$rand_string=md5(uniqid(rand(), true));
$_SESSION['s_form']=$rand_string;
 $errors="";
if(isset($_POST['Submit']) 
and $_POST['s_form_randomizor']==$_SESSION['s_form']){
if($_POST['names']==""){
$errors="Names field required.";
}else{
$_SESSION['s_form']=$rand_string;
}
}
?>

HTML part

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Prevent multple form submission</title>
</head>
 
<body>
<?php echo (isset($_POST['Submit']) and $errors!="")?$errors:'';?>
<form id="s_form" name="form1" method="post" action="">
  <input name="names" type="text" id="names" />
  <input type="submit" name="Submit" value="Submit" />
  <input type="hidden" name="s_form_randomizor" value="<?php echo $rand_string;?>"/>
</form>
</body>
</html>

Download Source Code

prevent-multlple-form-submission

javascript setintervel

Calling a Javascript function in regular interval

Generelly we need to work or call a javascript function . for that we user setInterval function .below example shows how we use it.
setInterval function takes two parameters ,first parameter function handler and second parameter the time in milli seconds.
below example show a simple counter that executes the function in every second interval.

javascript setinterval example and tutorial

javascript setinterval example and tutorial

Download Source Code

javascript-setinteval-source code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<html>
<head>
<title>javascript setInterval();</title>
</head>
 
<body>
<script type="text/javascript">
var timer;//stores the timer varible for a function
var count=0;
function start(){
timer=setInterval(sethtml,1000);
}
function sethtml(){
document.getElementById('timer').innerHTML=count++;
}
 
function stoptimer(){
clearInterval(timer);
}
</script>
<a href="#start" onclick="start();">Start</a> <a href="#stop" onclick="stoptimer();">Stop</a>
<div id="timer"></div>
</body>
</html>

Download Source Code

javascript-setinteval-source code

preventing multiple form submission with javascript

Prevent or stop multiple form submission with JavaScript

A dynamic web application contains at least one user form and the big issue is data redundancy (duplicate data). The main reason is multiple form submission. when a form is being sent to the server,the user can send the form data multiple times by pressing Enter (return ) key or clicking the submit button.in this example we disable this features while form being submitted.but it fails when user refreshes or click the F5 button . To prevent Refresh event we use Server side check or redirect to another page .

Down load Source Code

prevent-multiple-form-submission

Example for client side check

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Prevent multiple form submission with javascript</title>
<script type="text/javascript">
/*
This function validates the form data for rules.
Don't allow multiple form submission.
remember remember
if user refreshes while sending it fails.
for that we check for server side also
*/
var form_submited=false;
function validate(){
if(form_submited==true){alert('Form already submitted.');return false;}
	var name=document.ex_form.names.value;//access name value
	if(name==''){
		alert('Name is required.');
		return false;
	}
		form_submited=true;
		document.ex_form.Submit.disabled='disabled';//set form submitt button disabled
		document.ex_form.Submit.value='Processing..';//set form submit button text is processing.
	return true;
}
</script>
</head>
<body>
<form id="ex_form" name="ex_form" method="post" action="" onSubmit="return validate();">
  <input name="names" type="text" id="names" />
  <input type="submit" name="Submit" value="Submit"  />
</form>
</body>
</html>

Down load Source Code

prevent-multiple-form-submission

css sprites image preloding

Image pre loading with css and image sprites

We discussed image pre loading with javascript in my previous post.but it can’t be use full when javascript disabled browsers (off course use disables).So i got one idea how to implement without javascript for image preloading .

With Hidden Div Element

here the trick ,we know that browser loads all the assets (images,audio,embed elements ) as they appear in the HTML document.So we create a dive and hide and make it null style element .put the images which you want to load .

using css image sprites

for tri state button we need three image for each state (normal, hover, focus) by default we load normal image back ground. when we hove first time the second image loaded . so we use images sprites. as shown

Sample Sprite image for tri state buttons

Sample Sprite image for tri state buttons

Download Example Source code

image-preloading-with-css-sprites source code

Example for HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Image Preloading With CSS and Sprites</title>
</head>
<body>
<!--
please visit for detailed tutorial http://www.maheshchari.com
Here we use simple trick ,it work even without javascript
first create a div element with given style attributes specified above.
include the images  which to be preloaded.
remember put this div after the body tag,
since this element is first rendered,
all the images are loaded before they used
 -->
 image-preloading-with-css-sprites
<div id="preloader_div"> <img src="amphi-thetre.jpg" /> <img src="amphi-thetre1.jpg" /> <img src="amphi-thetre2.jpg" /> <img src="amphi-thetre3.jpg" /><img src="ex-sprite.png" /></div>
<div id="wrapper">begin your work here.</div>
<h3>Preloading with images sprites example tri state button.</h3>
<ul id="tributtons">
  <li><a href="http://www.maheshchari.com/">button1</a> </li>
  <li><a href="http://www.maheshchari.com/">button2</a> </li>
  <li><a href="http://www.maheshchari.com/">button3</a> </li>
</ul>
</body>
</html>

Css sample

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<style type="text/css">
<!--
 
#preloader_div {
	display: none; 
	height: 0px;
	width: 0px;
	margin: 0px;
	padding: 0px;
	position: absolute;
}
<!-- tri state buttons -->
#tributtons {
	list-style-type: none;
}
#tributtons a,a:visited {
	display: block;
	background-image: url(ex-sprite.png); 
	background-repeat: no-repeat;
	background-position: 0px 0px;
	width: 150px;
	height: 24px;
	text-decoration: none;
	text-align: center;
	text-transform: capitalize;
}
#tributtons a:hover {
	background-position: 0px -24px;
}
#tributtons a:focus {
	background-position: 0px -48px;
}
 
-->
</style>

Download Example Source code

image-preloading-with-css-sprites source code

increase php file upload limit

Increase file size upload limit using php.ini or htaccess

Any php web application or server configured with default values set in php.ini and .htacess. Generally almost web hosting providers configures the web application to optimum settings, which effects server bandwidth, server memory limit, server disk space, and peak security measures. For file uploading and PHP script execution there is default configuration in PHP.ini. However almost hosting providers give chance to developer to customize this default configuration by override php.ini or. htaccess . some settings can be configured by ini_set() method at run time of script.

Default PHP.ini

;;;;;;;;;;;;;;;;
; File Uploads ;
;;;;;;;;;;;;;;;;

; Whether to allow HTTP file uploads.
file_uploads = On

; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
upload_tmp_dir = "${path}\tmp\"

; Maximum allowed size for uploaded files.
upload_max_filesize = 2M

;;;;;;;;;;;;;;;;;;;
; Resource Limits;
;;;;;;;;;;;;;;;;;;;

max_execution_time = 30     ; Maximum execution time of each script, in seconds
max_input_time = 60	; Maximum amount of time each script may spend parsing request data
;max_input_nesting_level = 64 ; Maximum input variable nesting level
memory_limit = 128M      ; Maximum amount of memory a script may consume (128MB)

Increasing file upload size by php.ini

File upload size affected by mainly below PHP settings.
file_uploads = On
This setting must be on. It allows running uploads through HTTP.
Ensure this value is on the value can be On/Off or 1/0 or true/false.
upload_max_filesize = 20M
This value limits the size of uploaded single file. Give it value what ever your requirements.
post_max_size = 40M
This value limits the size of all the uploaded content. For example upload_max_filesize is for single file, if we upload 3 files simultaneously each 15mb total 45mb so it exceeds post_max_size.
Remember post_max_size must be larger about 40% of upload_max_filesize.

max_execution_time = 30
Generally image uploading and manipulating with GD or Imagemagic consumes much time. So it may exceeds 30 seconds. You can modify whatever your requirements. When a script execution time exceeded by this limit the server stops the scripts or gives fatal error.

memory_limit = 128M
Generally image uploading and manipulation with GD or Imagemagic consumes much server memory. When it exceeds this memory the server stops executing the script, then we see empty page or no response from server or we get a fatal error.

Completed example, to increase 10Mb
upload_max_filesize = 10M ;
post_max_size = 20M ;
memory_limit = 128M

Copy the above settings into your php.ini and put it in your web root directory.

Increasing file upload size by .htaccess

php_value upload_max_filesize 10M
php_value post_max_size 20M
php_value memory_limit 128M

Copy the above settings into your .htaccess file and put it in your web root directory.
Almost all web host providers give to override the .htacces ,so you can use above method.

javascript image preloading

Image Preloading with JavaScript

Now a days web visitor prefers to see fancy page designing .when designing most attractive web page ,it becomes must use lot of images ,back grounds ,animation effects.
When page becomes more attractive with lot of images, it takes time to load all the images and it consumes the user bandwidth.
Generally each embedded page elements like images, audio, video objects are loaded when browser makes HTTP request to server. When it comes to tri state buttons, mouse over image, loading large images, the user wait to see effects at first time. After loading first time browser will cache the image.

Image Object

So over come this first time loading of image we use JavaScript image object for loading.
We create an image object instance before web page body loaded, so the browser will make HTTP request before the required mouse over, image hover effect, tri state buttons.
Most advanced browser now a days use DOM, so it works on all browser.

CSS and Sprites

for javascript disabled browsers we can use css & sprite image preloading.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>image preload</title>
<script type="text/javascript">
function preload_images(){
	img_length=preload_images.arguments.length;
	for(var i=0;i<img_length;i++){
		src=preload_images.arguments[i];
		img=new Image();
		img.src=src; //here we make http request
	}
}
// we are calling the function there by making HTTP request for images before page body loads
//here we use function argument property for multiple images
//remember all the image paths can be absolute or relative
preload_images('myimg.gif','urimg.jpg');
</script>
</head>
<body>
</body>
</html>

download source code

image-preloading-javascript-source-code

protecting web contact forms from spam bots

Protecting web forms from spam bots using PHP

Spam bot is a program that submits the data to server by guessing form fields with html code.
For detailed article please refer my previous post.

Here some methods of preventing Spam bots that automatically submits.

  • Using captcha
  • Using random hidden field
  • Using hidden input text box.
  • Email header injecting.
  • Checking referrer page
  • Following basic rules

We can prevent the Spam bots with some basic rules
Prevent email harvesting on your web pages, see my previous post anti email harvesting.
Generally Spam bots looks for form tag and contained input, check box, radio boxes, option element (Hhhh all the form elements), fills their data with their spam data so we can take this as advantage, some spam bots stores this information and sends with proxy without resubmitting the web contact form, so we can prevent this type of technics.
Use deferent form fields than usually, like use ‘ xyz_nm’ instead ‘name’.Change the form field’s name in regular interval, like put ‘zmon_nm’ on ‘Monday’, ‘ztue_nm’ on ‘Tuesday’.
Use random named hidden input field with a default value is empty on every form submission like captcha, if the default value of the hidden field changed other than default, it is sure Spam.
Put one input text box element with random name and hide it with CSS style, since it won’t visible to general user, the default value could not changed, if any changes made to this value of input it is definitely Spam.
Don’t put email address in the form elements, instead put it in sever side variable.
Check for page referrer, however some server’s firewalls don’t allow this information, they strips the data.
Use captcha like methods or services that are available present , but this captcha has some inconvenience to the user.
Disabling or filtering HTML message in form elements, since maximum spam bots try to fill HTML data.
Make sure to access all the forms for login users and track down their messaging and ban certain user.
protect-web-form-from-spams-maheshcharicom

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<?php 
#function that validate the user email
function is_valid_email($email){
$eregpat="^[A-z][A-z0-9_-]+([.]([A-z0-9_-])+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$";
return eregi($eregpat,$email );
}
 
#function that validate user comments
function is_valid_comments($data){
return ($data=="");
}
#function that clean the user data againest 
#email header injection so we clean it
function safe_mail($data){
#clean non standerd alpha numeric and some special symbels
#clean email related headers like header,from,body,'cc','bcc',\r\n etc
$patterns=array('/[^a-zA-Z0-9\.-@_]/','from','header','body','CC','BCC');
return preg_replace($patterns,'',$data);
}
 
 
function send_mail($data){
#do what ever you want here with user data
#like storing into database or sending email to admin
}
 
#clean all data from user contact form and process this to store in mysql and sending email

function process_contactform(){
$data=array();
$data['name']=safe_mail($_POST['sfsf_name']);
$data['email']=safe_mail($_POST['jflsjls_email']);
$data['website']=safe_mail($_POST['kipmp_website']);
$data['comments']=safe_mail($_POST['comments_sfs']);
send_mail($data);
}
 
 
require_once('recaptchalib.php');
 
// Get a key from http://recaptcha.net/api/getkey
$publickey = "6LdVSQYAAAAAAFwb2919Sf8Uhcq3Z55bQc7d8Bx0";
$privatekey = "6LdVSQYAAAAAAIVT-VaJlea6WuOlLqJtt0UUK6xZ";
 
# the response from reCAPTCHA
$resp = null;
#error cacher
$errors = array();
 
if(isset($_POST['Submit'])){
# was there a reCAPTCHA response?
if (isset($_POST["recaptcha_response_field"])) {
        $resp = recaptcha_check_answer ($privatekey,
                                        $_SERVER["REMOTE_ADDR"],
                                        $_POST["recaptcha_challenge_field"],
                                        $_POST["recaptcha_response_field"]);
 
        if ($resp->is_valid) {
                echo "You got it!";
        } else {
                # set the error code so that we can display it
                $errors[] = $resp->error;
        }
}
 
#check the page that submits is belong to our domai or not
#remember some servers don't allow this data or don't have information
if(strpos('localhost', $_SERVER['HTTP_REFERER'])==false){
$errors[] ='This page can be prcessed from this domain only.';
}
 
#check email validation
if(isset($_POST['jflsjls_email']) and !is_valid_email($_POST['jflsjls_email'])){
$errors[]='Invalid email address.'; 
}
 
#check comment validation 
if(isset($_POST['comments_sfs']) and !is_valid_comments($_POST['comments_sfs'])){
$errors[]='Trying to email header injection.';
}
 
#check user is bot or not
if(isset($_POST['owjrj_ran']) and !$_POST['owjrj_ran']==''){
$errors[]='You are spam bot.';
}
 
#check user is bot or not
if(isset($_POST['mpmpm_rwrw']) and !$_POST['mpmpm_rwrw']==''){
$errors[]='You are spam bot.';
}
 
#check all errors and process contact form
if( isset($_POST['Submit']) and count($errors)==0){
process_contactform();
}
 
 
}
 
#if errors display
if(isset($_POST['Submit'])){
if(count($errors)>0){
echo '<ul class="errors" >';
foreach($errors as $k=>$v){
echo '<li>'.$v.'</li>';
}
echo '</ul>';
}
}
?>

HTML code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Contact Form</title>
</head>
<body>
 
<script type="text/javascript">
 
/*
This javascript form validation only for generel users.
the spam bots don't process this type javascript validation so we have to 
validate again on server side.
*/
function validate_form(){
 
var errors='';
 
var fm=document.contactform;
 
if(fm.jflsjls_email.value==''){
errors+='Email required.\n';
}
 
if( !(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(fm.jflsjls_email.value))){
errors+='Invalid email address.\n';
}
 
if(fm.comments_sfs==''){
errors+='Empty comments.\n';
}
 
if(errors!=""){
alert(errors);
return false;
}
return true;
}
</script>
<form action="" method="post" name="contactform" id="contactform" onsubmit="return validate_form();">
  <table width="500" border="1">
    <tr>
      <th colspan="2">Contact Me
        <script>
		//email obfuscation 
document.write("m"+"y"+"m"+"a"+"i"+"l"+" &#64;"+"y"+"o"+"u"+"d"+"o"+"m"+"a"+"i"+"n"+" &#46"+"c"+"o"+"m");
</script>      </th>
    </tr>
    <tr>
      <td width="295"> Name </td>
      <td width="288"><input name="sfsf_name" type="text" id="sfsf_name" />      </td>
    </tr>
    <tr>
      <td>Email: * </td>
      <td><input name="jflsjls_email" type="text" id="jflsjls_email" /></td>
    </tr>
    <tr>
      <td> Web Site </td>
      <td><input name="kipmp_website" type="text" id="kipmp_website" value="" /></td>
    </tr>
    <tr>
      <td colspan="2">
	  <!-- 
	  hidden field that real user can't see ,only spam bots can process
	  in some spam bots this hidden field don't change the value ,
	  they submit as it is
	   -->
	  <input name="owjrj_ran" type="hidden" id="owjrj_ran" />
	  <!--
	  to overcome we use text field that is hidden from real user.
	  but this field is precessed by spam bots.
	  it is simply .
	   -->
        <input name="mpmpm_rwrw" type="text" id="mpmpm_rwrw" style="display:none" value="" />
        Comments*</td>
    </tr>
    <tr>
      <td colspan="2"><textarea name="comments_sfs" cols="45" rows="5"></textarea></td>
    </tr>
    <tr>
      <td colspan="2" align="left">
	  <!-- 
	  recaptcha text area field
	  this is another guarented check.
	  but it is not user freindly 
	   -->
	  <?php echo recaptcha_get_html($publickey, $errors);?></td>
    </tr>
    <tr>
      <td colspan="2" align="center"><input type="submit" name="Submit" value="Submit" />
        <input type="reset" name="Submit2" value="Reset" /> 
        <small>* Required field </small></td>
    </tr>
  </table>
</form>
</body>
</html>

Download Source Code

web-contact-form-with-anti-spam-methods download link here

email obfuscation

protecting E-mail Address on web pages with php, javascript from E-mail spammers

E-mail Spam is flooding the Internet with many copies of the same message, in an attempt to force the message on people who would not otherwise choose to receive it.Most spam is Commercial advertising, often for dubious products, get-rich-quick schemes, or quasi-legal services. Spam costs the sender very little to send — most of the costs are paid for by the recipient or the carriers rather than by the sender.

How do they catch email address of users? Or how do they email harvesting?

There are many ways to get users email address but here we talk about only two ways.

From web pages:

Spammers have programs which spider through web pages, looking for email addresses, e.g. email addresses contained in mailto: HTML tags [those you can click on and get a mail window opened],a word contains @ symbol ,a word contains mailto:

From various web contact or enquiry forms.

Some sites request various details via forms, e.g. guest books & registrations forms.
Spammers can get email addresses from those either because the form becomes available
on the world wide web, or because the site sells / gives the emails list to others.
some spammers use weak security web forms on certain websites to protect web form from spammers please refer my post

Preventing E-mail harvesting on web pages

e-mail Address munging or e-mail Obfuscation

Address munging is the practice of disguising, or munging, to prevent it being automatically collected by spam bots.
Some examples are

  • no-one at example (dot) com
  • no-one@elpmaxe.com.invalid
  • moc.elpmaxe@eno-on
  • no-one@exampleREMOVEME.com.invalid
  • remove .invalid
  • no-one@exampleNOSPAM.com.invalid
  • n o – o n e @ e x a m p l e . c o m
  • no-one@example.com (as HTML)

Even though the email harvesting reduced in measurable amount, with this method the main user has to predict the original. Now days some spam bots also overcomes this method.

Using javascript

Most of the spam bots don’t execute the javascript and they use regular expression to catch the address.
So we can advance the method of munging with following examples

For static web pages e-mail Obfuscation

1
2
3
4
5
6
<script type="text/javascript">
var name = 'user';
var at = '@';
var domain = 'example.com';
document.write(name + at + domain);
</script>
1
2
3
4
<script>
document.write(‘m’+’y’+’m’+’a’+’i’+’l’+&#64;+’y’+’o’+’u’+’d’+’o’+’m’+’a’+’i’+’n’+&#46+’c’+’o’+’m’);
</script>
//In the above example we use html equivalent ASCII chars &#64 for  symbol and &#46 for ‘.’ Character.

For dynamic web pages with PHP server side language e-mail Obfuscation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function safe_asciimail($email){
$length=strlen($email);
	if($length==0)return '';
	$email=strtolower(trim($email));
	$email_array=str_split($email);
	$ascii_email_array=array();
	for( $i=0;$i<count($email_array);$i++){
		$c=$email_array[$i];
		$ascii_email_array[]='&#'.ord($c).';';
	}
return '<script> document.write("'.implode('',$ascii_email_array).'");</script>';
}
 
//We can call this method as follow 
//safe_asciimail(‘mymail@yourdomain.com’);

simple PHP file upload tutorial

A simple PHP file upload tutorial

This PHP file upload tutorial is concentrated on mainly for beginners. Generally we face many problems in file uploading. Like checking fie extensions on client and server side, processing file as our requirement.
For this we need two files called uploader.html and uploader.php
In uploader.html we do form validation and checking file extensions.
In uploader.php we do check for user submitted file extensions.

Some observations<

  • Always-set form method to POST
  • Always-set form encodedtype to multipart/form-data
  • Check file type on client side and server side also.
  • Increase the script time limit and memory limit to upload large file.
  • Don’t use web method (this method) to upload larger than 500mb,instead use ftp upload interface.

Generally the default maximum upload file size less than 8mb.
To upload the larger or bigger files read increase file upload limit

Add a simple Form to page as shown below

<form id="uploadform" action="uploader.php" enctype="multipart/form-data" method="post">
  <label>Upload File
  <input id="filefield" name="filefield" type="file" />
  </label>
  <label>
  <input id="Upload" name="Upload" type="submit" value="Upload" />
  <!--
  This hidden input will force the  PHP max upload size.
  it may work on all servers.
   -->
  <input name="MAX_FILE_SIZE" type="hidden" value="100000" />
  </label>
</form>

Add validation script to page as shown below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<script type="text/javascript">
	function validatefile(){
		var myform=document.uploadform;   //reference to form 
		var file_field_value=myform.filefield.value; //access form value with dom model
		var error="";
			if(file_field_value==''){
				error+="Please Select A file.\n";
			}
		var allowed_extensions=/(jpg|jpeg|bmp|giff|doc|docx|pdf)$/; //check for allowed extension it is simple regular expression
 
			if(!file_field_value.match(allowed_extensions)){
				error+="Please select only jpeg or jpg or bmp or giff or doc or pdf .";
			}
 
			if(error!=''){  //check for any errors
				alert(error);   //if error alert error
				return false;   //return to form don't submit to action page
			}
 
	return true;   // every thing going fine return true allow form to submit the data.
	}
 
	</script>

Check file status and process the page on server side.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
if (isset($_POST['Upload'])) {  //check if form submitted
    if (!empty($_FILES['filefield'])) { //check for image submitted
        if ($_FILES['filefield']['error'] > 0) { // check for error re file
            echo "Error: " . $_FILES["filefield"]["error"] . "<br />";
        } else {
            print_r($_FILES);  //every thing fine file successfully uploaded to server
        }
 
 
    } else {
        die('File not uploaded.'); // exit script
    }
}
 
?>

now a simple validation and uploading the file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
 if (!isset($_POST)){die('You can"t access this file directly');}//avoid direct accessing to this file.
 
 if (isset($_POST['Upload'])) {  //check if form submitted
    if (!empty($_FILES['filefield'])) { //check for image submitted
        if ($_FILES['filefield']['error'] > 0) { // check for error re file
            echo "Error: " . $_FILES["filefield"]["error"] . "<br />";
        } else {
            $file=$_FILES['filefield'];  //every thing fine. file successfully uploaded to server
        }
 
 
    } else {
        die('File not uploaded.'); // exit script
    }
}
 
 $upload_directory='uploaded/';
 $ext_str = "gif,jpg,jpeg,mp3,tiff,bmp,doc,docx,ppt,pptx,txt,pdf";
 $allowed_extensions=explode(',',$ext_str);
 $max_file_size = 10485760;//10 mb remember 1024bytes =1kbytes
 $overwrite_file = false;
 /* 
 upload directory check 
  */
 $status = true;
 if (!is_dir($upload_directory)) { //check if upload directory exists or not
            if ($mkdir) {
                if (!mkdir($upload_directory)) { //if directory doesn't exists try to create it,if fails warn user
                    $status = false;
                } else {
                    if (!chmod($upload_directory, 0777)) $status = false; //change file permisson to write,read,execute
                }
            } else {
                $status = false;
            }
} 
if(!$status){  //if can't make a directory warn the user and exit
die('There is no uploade directory or i can" create the upload directory');
}
 
/* 
check allowed extensions here
 */ 
$ext = substr($file['name'], strrpos($file['name'], '.') + 1); //get file extension from last sub string from last . character
if (!in_array($ext, $allowed_extensions) ) {
die('only'.$ext_str.' files allowed to upload'); // exit the script by warning
 
/* 
check file size of the file if it exceeds the specified size warn user
 */
 
if($file['size']>=$max_file_size){
die('only the file less than '.$max_file_size.'mb  allowed to upload'); // exit the script by warning
}
 
/* 
check if the file already exists or not in the upload directory
 */
 
if(!$overwrite_file and file_exists($upload_directory.$file['name']) ){
 die('the file  '.$file['name'].' already exists.'); // exit the script by warning
}
 
if(!move_uploaded_file($file['tmp_name'],$upload_directory.$file['name'])){
 die('The file can"t moved to target directory..'); //file can't moved with unknown reasons likr cleaning of server temperory files cleaning
}
 
 
/* 
Hurrey we uploaded a file to server successfully.
 */

Download Source Code

Download Source Code Link(3kb)

Work To GET method on CodeIgniter

Enable GET method on CodeIgniter Frame Work with SEF urls

CodeIgniter is a powerful PHP framework with a very small footprint,built for specially PHP coders.It has many advantages like SEF URL ,light weight, high level Security,MVC model ,more libraries .
But it has strictly followed SEF segments ,it unsets or delets the global $_GET array to prevent Security Hacks when it initializes .To Enable or Create Custom GET method
open config.php file in aplications/config/ folder

set uri protocal

 $config['uri_protocol']	= "PATH_INFO";

code sample

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 
/*
|--------------------------------------------------------------------------
| URI PROTOCOL
|--------------------------------------------------------------------------
|
| This item determines which server global should be used to retrieve the
| URI string.  The default setting of "AUTO" works for most servers.
| If your links do not seem to work, try one of the other delicious flavors:
|
| 'AUTO'			Default - auto detects
| 'PATH_INFO'		Uses the PATH_INFO
| 'QUERY_STRING'	Uses the QUERY_STRING
| 'REQUEST_URI'		Uses the REQUEST_URI
| 'ORIG_PATH_INFO'	Uses the ORIG_PATH_INFO
|
*/
$config['uri_protocol']	= "PATH_INFO";

add a line of code in your control method to recreate the GET array
for example codeigniter default welcome.php controller in Codeigniter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Welcome extends Controller {
 
	function Welcome()
	{
		parent::Controller();	
	}
 
	function index()
	{	
		parse_str($_SERVER['QUERY_STRING'],$_GET); //converts query string into global GET array variable
		print_r($_GET); //test the $_GET variables
		$this->load->view('welcome_message');
	}
}

if you run your code with following URL


http://localhost/index.php/welcome/?var1=1&var2=2&var3=3

The result will be

Array
(
    [var1] => 1
    [var2] => 2
    [var3] => 3
)

Here parse_str function converts string to array with given deliminator.To know more about parse_str go to php.net
Even though we can achieve this result, i suggest you to stick to segments because it more user friendly.