check ajax request

how to find the given request from ajax with php

In my recent project ,i have to restrict a page from direct accessing from browser with typing address on browser .this page must only accessible with ajax only.thank god there is a solution to find this with php server global variable that works with php5.then i made it a simple following function.

1
2
3
4
function is_Ajax() {
return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'));
}

css image rollover

image rollover effect with css background image

Here we use basic css back ground image to get rollover effect.the logic is simple and we can find it in comments in script itself.

  • we create a empty link
  • set back ground as test1.jpg and display to block and height and width to 150px.
  • build a suido selctor hover to link and set back ground image to test2.jpg
  • this works even javascript disabled browsers also

Download Script

image-rollover-css

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<html>
<head>
<title>image rollover with css</title>
<style type="text/css">
<!--
#imagerollover a {
	background-image: url(test2.JPG);
	display: block;
	background-repeat: no-repeat;
	height: 150px;
	width: 150px;
}
#imagerollover a:hover{
	background-image: url(test1.JPG);
}
-->
</style>
</head>
<body>
<div id="imagerollover"><a href="#test">&nbsp;</a></a></div>
</body>
</html>

Download Script

image-rollover-css

multifile upload

Multiple file uploading tutorial with php

We already discussed about increasing file upload size and simple file upload in my previous posts.now we discuss about the logic behind the multiple file upload.
Here we create unlimited file fields on the fly with javascript ,so that there is no limit.
uploader.php:-we process all the uploaded files and show the results of uploaded files. remember to validate and filter the file types please view my previous post.

Please Download Source Code To View it

handling-multiple-file-upload-php

Javascript Code

1
2
3
4
5
6
7
8
9
function add_file_field(){
var container=document.getElementById('file_container');
var file_field=document.createElement('input');
file_field.name='images[]';
file_field.type='file';
container.appendChild(file_field);
var br_field=document.createElement('br');
container.appendChild(br_field);
}

HTML Code

1
2
3
4
5
6
7
8
<form action="uploader.php" method="post" enctype="multipart/form-data" name="mutiple_file_upload_form" id="mutiple_file_upload_form">
  <h1>Advanced Multiple File Upload Script Example</h1><div id="file_container">
    <input name="images[]" type="file"  />
    <br />
  </div>
  <a href="javascript:void(0);" onClick="add_file_field();">Add another</a><br />
  <input type="submit" name="Submit" value="Submit" />
</form>

PHP 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
if (isset($_POST['Submit'])) {
    $number_of_file_fields = 0;
    $number_of_uploaded_files = 0;
    $number_of_moved_files = 0;
    $uploaded_files = array();
    $upload_directory = dirname(__file__) . '/uploaded/'; //set upload directory
    /**
     * we get a $_FILES['images'] array ,
     * we procee this array while iterating with simple for loop 
     * you can check this array by print_r($_FILES['images']); 
     */
    for ($i = 0; $i < count($_FILES['images']['name']); $i++) {
        $number_of_file_fields++;
        if ($_FILES['images']['name'][$i] != '') { //check if file field empty or not
            $number_of_uploaded_files++;
            $uploaded_files[] = $_FILES['images']['name'][$i];
            if (move_uploaded_file($_FILES['images']['tmp_name'][$i], $upload_directory . $_FILES['images']['name'][$i])) {
                $number_of_moved_files++;
            }
 
        }
 
    }
    echo "Number of File fields created $number_of_file_fields.<br/> ";
    echo "Number of files submitted $number_of_uploaded_files . <br/>";
    echo "Number of successfully moved files $number_of_moved_files . <br/>";
    echo "File Names are <br/>" . implode(',', $uploaded_files);
}

Download Source Code

handling-multiple-file-upload-php

Screen Shots

handling-multiple-file-upload-examplehandling-multiple-file-upload-result

captcha php tutorial

A simple php captcha image tutorial

Captcha is a test for user if he is real human or computer. In this example we use PHP GD2 functions to create the image on the fly. To test this functionality we need following files.We already discussed about anti spam web contact form in my provious post.this is one of methods.
Php_captcha.php :- in this file we create the captcha image and store the data in PHP session.
Captcha_test.phpl :- in this file we run the user form and validate the user for is he bot or not.
captcha.JPG :- this image is used as back ground for generated PHP captcha. This file must have at least read permission on the main server.

You can download the source code here and you can test in your local server. Remember your PHP must have GD extension to run this example. You can read comments on the script for detail explanation.

Example source Code

php_captcha_example_tutorial_source code

Example source Code

php_captcha_example_tutorial_source code

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

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.

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)

Installing Apache ,PHP,Mysql on Windows

Installing Apache,Php,Mysql servers on system

PHP and MySQL are usually associated with LAMP (Linux, Apache, MySQL, PHP). However, most developers prefers Windows when developing the PHP application. So at this point we will cover only the WAMP ( Windows, Apache, MySQL, PHP ). You will learn how to install Apache, PHP, and MySQL under Windows platform.
it so hard task for beginners to install them on system.Thank god we have open source packages like Easyphp ,xamp,wamp server ,where we can install all the server environment with single mouse click.They are pre configured server packages.You can follow these use full links. i prefer for easyphp most of them as per my experience.