Twenty first Century Kids Love

What are you little children doing here? I saw these two kids, a girl and a boy of 5 or 6, holding their trousers and trying to fasten in a hurry as I suddenly opened the door of the toilet. They replied nothing but shyly giggled and ran out of the door. This scene created thousands of thoughts in my head. What were those kids doing inside the toilet putting their pants off? Were they sharing kids’ love? Why were they playing in a private place? What game were they playing inside a 3X3 closed toilet with the doors closed? What made them do such an activity? And many more…Not sure what exactly the two little kids were doing but I want to relate this story with the teenage love of this age. A girl of around 16 was pregnant for 35 weeks. She didn’t even share this information with her parents. Suddenly when their parents came to know about her pregnancy they had no idea what to do except panic. Investigation begun. The girl revealed the truth. According to her, The boy liked the girl. Approached her via her friend. Dated her for a couple of days. Finally, after having sex for the first time the boy disappeared. Became contactless. Leaving everyone suffering after 7 months. This is just one example of 21st-century love. Like this, I have heard and seen a couple of dozen cases in Nepal as well as in India where amateur girls got aborted and carved scars for lifetimes. Well, I have no objection to the kids for making their teenage love. One can make as many as one can but the point is are the kids able to cope with the level of tension created due to the amateur relationship they have created? Do their relationships create peace of mind or complications? What mental and psychological effects are they going through? Are our kids getting proper counseling in their school? Do the guardians give good care to their children? How is sex education taken and given to our children? Being a father of a son I am highly concerned about this matter. I am concerned for the future of today’s kids. Kids nowadays are more concerned about friends and relationships rather than their studies and homework. Very few children are focused on their work and career. Also being a social worker I would like to convey a message to all the teachers, caretakers, guardians, and parents to accept the responsibility of their students and children and give them proper care. Be open. Talk to them. Make a friendly environment. Try to reveal their secrets. In order to make a balanced life for our children, periodic counseling is required. What is happening in the children’s life? Like physical health, we also need to take care of the children’s mental health and psychological status. Physical health problems can be cured easily by medical treatment but psychological issues are often complicated and maybe too expensive. Hence, as a teacher and guardians, it is our responsibility to keep track of our children’s activities. By continuously monitoring their behavior and habits we will be able to help them build a healthy careers. And hence a better world.

Good luck. Happy parenting.

थारु को हुन् ?

म सानै छदा कहिले काही हाम्रो घर मा पहाडी केरा को डोको बोकेर  आउनु हुन्थ्यो, एक जना बाजे।  म हजुरबा लाइ सोध्थे को हुन् इनि भनेर।  हजुरबा ले इनि मेरो मित हुन् भन्थे।  हामि केरा खादै रमौंथ्यो र मित बाजे संग गफ गर्थ्योउ। बाजे ले हामि लाइ नेपाली बोल्न सिकाउनु हुन्थ्यो।  बाजे १ हप्ता पछि फर्किनु हुन्थ्यो, १ बोरा चामल त्यहि डोको मा राखेर।     

अहिले म सोचेर दङ्ग पर्छु।  मित बाजे कोसौ टाढा पहाड बाट डोको बोकेर हाम्रो गाउ पैदल आउनु हुन्थ्यो र पैदल नै चामल बोकेर फर्किनु हुन्थ्यो।  मोटर चल्दैनथ्यो त्यति बेला।   हजुरबा ले भन्नु हुन्छ उहा धेरै गरिब हुनुहुन्छ भनेर। पहाड  मा जिउनु गार्हो छ अरे।  

त्यसैले नै होला धेरै पहाडी हरु चामल लिन तराई झर्थे २० साल पहिले।

हजुरबा ले भन्नु हुन्छ, हाम्रो ४० बिघा जमिन थियो।   नवलपरासी का धेरै गाउ हरु मा थारु हरु जमिन्दार थिए। बिस्तारै पहाडी भाग बाट मानिस हरु तराई वोर्लिए।  थारु हरु ले इन्लाई सरह दिए।  

आज एकजाना पहाडी साथि ले को हुन् थारु र के का लागि आन्दोलन गरिरहेका छन् भनेर सोधे। मेरो कुनै जवाब थिएन।  म उसको अनुहार हेरेर मुस्काए मात्र।     

How to implement Heatmap on Websites using PHP, MySQL, jQuery and Ajax?

I was assigned a task when an Interviewer interviewed me and that was a Technical question. I was asked to design a system that can gather click data from a webpage and show it later in form of a Heatmap.

[dfads params=’groups=-1′]

This system can be integrated into any website which records visitor clicks on the page. The goal of of this will be to track visitor’s mouse clicks on various elements of the page and later show them accurately in form a Heatmap. The owner should be able to see aggregated click data in form of an overlay on top of his webpage. The areas in the heatmap that are red more clicks compared to the areas that are white.

After googling through the internet I found some resources which were very interesting. I devoted some time and tried to implement a demo. Please follow the following Steps:

1. Client Code : Create a file index.php and include the following code below. This is the page where users make clicks.

[code]
<script type=’text/javascript’ src="js/jquery-lib.js"></script> <!– jQuery library –>
<script type=’text/javascript’ src="js/hm-dev.js"></script> <!– Log JS –>

<title>99-Websites.com Labs</title>
<body>
<div style="text-align:center">
<img src="99-ws-labs.jpg" />
</div>
</body>

[/code]

2. The Ajax Call : Create a JS file named as hm-dev.js. This file is included in the above index.php page. Add the snippet below:

[code]
/*
Author : Dev
Date : 12/06/2015
*/

jQuery(document).ready(function() {
jQuery(document).click(function(e){
//alert(window.location.href.toString().split(window.location.host)[1]+" — "+e.pageX+" — "+e.pageY);
log_click(window.location.href.toString(), e.pageX, e.pageY);
});
var canvas = document.getElementsByTagName(‘canvas’)[0];
canvas.style.display = "none";
});

function log_click(page, x, y){ // log clicks for heatmap
jQuery.ajax({
type: ‘POST’,
url: ‘log_click.php’,
crossDomain: true,
data: "x_coord="+x+"&y_coord="+y+"&page="+page,
dataType: ‘json’,
success: function(responseData, textStatus, jqXHR)
{
if (responseData== 1){
console.log("Click logged: " + x + ", " + y);

}
else{
console.log("Error – click not logged " + x + ", " + y);
}
},
error: function (responseData, textStatus, errorThrown)
{
console.warn(responseData, textStatus, errorThrown);
alert(‘CORS failed – ‘ + textStatus);
}
});
}
[/code]

3. Log the Clicks : Create a PHP file named with log_click.php and add the following snippet.

[code]

<?php
header(‘Access-Control-Allow-Origin: *’);
header(‘Access-Control-Allow-Methods: POST, GET, OPTIONS’);
header(‘Access-Control-Max-Age: 1000’);
header(‘Access-Control-Allow-Headers: Content-Type’);

//echo json_encode(array("your_request_was" => $_POST[‘page’].$_POST[‘x_coord’].$_POST[‘y_coord’]));

include(‘config.php’); //Create config.php file and define $dbuser, $dbpass & $dbname

if(isset($_POST[‘x_coord’])){
$page = htmlentities($_POST[‘page’]);
if($page == "/"){ $page = "/index.php"; }
$xcoord = htmlentities($_POST[‘x_coord’]);
$ycoord = htmlentities($_POST[‘y_coord’]);
$time = date( ‘Y-m-d H:i:s’);

$conn = mysql_connect(‘localhost’, $dbuser, $dbpass);
mysql_select_db($dbname, $conn);
$page = mysql_real_escape_string($page);
$xcoord = mysql_real_escape_string($xcoord);
$ycoord = mysql_real_escape_string($ycoord);

mysql_query("INSERT INTO clicks (timestamp, page, x, y) VALUES (‘$time’, ‘$page’, $xcoord, $ycoord)");
mysql_close($conn);
echo "1";
}
else
{
echo ‘0’;
}

?>

[/code]

4. Create MySQL Table : Create table with following fields:

[code]

CREATE TABLE IF NOT EXISTS `clicks` (
`timestamp` datetime NOT NULL,
`page` varchar(200) NOT NULL,
`x` int(255) NOT NULL,
`y` int(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

[/code]

That’s it, the first part is over. After implementing the above steps you will be able to log clicks on the MySQL Table. The next and the main part is viewing the heat maps.

5. Create the Admin Page : Create PHP page named with admin.php. This page will lists out all the domains on which the client side code is added. When the links are clicked, their respective heatmaps will be displayed below the same page.  Admin Code is listed below:

[code]

<?php
/*
Author : Dev
Date : 12/06/2015
*/
include("config.php");
$con2 = mysql_connect(‘localhost’, $dbuser, $dbpass);
mysql_select_db($dbname, $con2);
$query = "SELECT distinct page FROM `clicks` WHERE 1";
$result = mysql_query($query);
?>
<html>
<head>
<title>Heatmap Admin</title>
<script type=’text/javascript’ src="js/jquery-lib.js"></script>

<script type=’text/javascript’ src="js/heatmap.js"></script>
<script>
jQuery(document).ready(function(){
var heatmapInstance = h337.create({
container: document.querySelector(‘.display’),
radius: 25
});

jQuery(".showcanvas").click(function(){
//location.reload();
//alert(jQuery(this).attr(‘value’));
var timescale = "day";
var page = jQuery(this).attr(‘value’);
//alert(page);
var postData = "timescale="+timescale+"&page="+page;
jQuery.ajax({
type:"POST",
dataType: "json",
data: postData,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/json;charset=UTF-8");
}
}, url: ‘heatmap.php’,
success: function(data) {

if (data.amount > 0){
for (i=0; i<data.amount; i++){
heatmapInstance.addData({
x: data[i].x,
y: data[i].y,
value: 2
});
}
}
}
});

});
});
</script>
</head>
<body >
<div style="width:100%; border:1px solid; black;">
[Click on the Websites below to View their respective HeatMaps]<br>
<ul style="font-size:12px;">
<?php
while($row = mysql_fetch_assoc($result)){
?>
<li><a href="#" class="showcanvas" value="<?=$row["page"]?>"> <?=$row["page"]?></a></li> <br/>

<?php

}
?>
</ul>
</div>
<div class="display" style="width:100%;height:100%;border:1px solid; black;float:right;">
</div>

</body>
</html>

[/code]

The main logic behind the code is the heatmap.js library. In order to understand in detail you can explore the following references:

1. http://www.patrick-wied.at/static/heatmapjs/example-click-heatmap.html

2. http://rossmarks.co.uk/blog/?p=683

3. http://www.d-mueller.de/blog/cross-domain-ajax-guide/

You can view the Demo here: 

1. Client / Users Page : http://99labs.net where you can make some clicks on the webpage.

2. Admin Page : http://dewendra.com.np/labs/hm/admin.php where you can view the Heatmap.

Also, You can download the whole code from here : Download

[dfads params=’groups=-1′]

PS : The client code can be installed into any website and their logs can be maintained on the remote server. If you go through the client side code you can see the ajax code implemented with CORS (Cross Origing Resource Sharing) using jQuery.

VMware Player unrecoverable error: (vmx)

When I opened my VMware today, following error was displayed:

VMware Player unrecoverable error: (vmx)

Exception 0xc0000006 (disk error while paging) has occurred.

A log file is available in "C:UsersacerDocumentsVirtual MachinesRed Hat Enterprise Linux 6 64-bitvmware.log".

You can request support.

To collect data to submit to VMware technical support, run "vm-support".

We will respond on the basis of your support entitlement.

[dfads params=’groups=-1′]

Solution: Remove the following two files from the VMware installed directory. You can check the installed directory from Player -> Manage -> Virtual Machine Settings -> Options

  1. Red Hat Enterprise Linux 6 64-bit-93cd0331.vmem
  2. Red Hat Enterprise Linux 6 64-bit-93cd0331.vmss

[Source: http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1002347]

Alphabets Kids will Learn in Future

Alphabets kids will learn in Future.

A: Amazon.com
A shopping Website.

B: Blogspot.com
A free blog website from google.com.
Bing.com
A search engine from Microsoft.

C: Cnn.com
CNN News Website

D: Dropbox.com
Share Files on the Cloud

E: Ebay.com
A shopping Website.

F: Flipkart.com
A shopping Website.
Facebook.com
A social networking website.

G: Google.com
A Search Engine

H: Hostgator.com
A Website Hosting Website

I: Instagram.com
Share Pictures online.

J: Jabong.com
A shopping Website.

K: Kakaku.com
A Chinese Website

L: Live.com
Email Website from Microsoft

M: Msn.com
A Search Engine from Microsoft.

N: Naukri.com
A Job Search Website.

O: Olx.in
Sell your old products online

P: Photobucket.com
Share images online

Q: Quikr.com
Sell your old products online

R: Rediffmail.com
An Email Website

S: SurveyMonkey.com
Create Surveys and Get Answers online.

T: Twitter.com
A microblog Website

U: Upload.com
Upload and Share Files

V: Vimeo.com
Upload and Share Videos

W: Wikipedia.org
The Free Encyclopedia

X: Xe.com
Live Exchange Rates.

Y: Youtube.com
Upload and Share Videos

Z: Zomato.com
Search Restaurants Nearby.

Information Compiled from alexa.com (Top 500 Websites on the Web)

Load Testing on Web Servers using Apache Benchmark

ab

After working on many websites, I found one of my site getting too many traffic bringing down the site. I contacted the technical support who fixed the problem. I had never tested load on any of my site. So, I started studying load testing on web servers. This helped me to understand how many users can be handled by my website so that it can run smoothly.

I found a very light and strong linux tool called Apache Benchmark Tool that can test load on Web Servers. This can benchmark Apache, IIS and other web server with apache benchmarking tool called ab. There are also other open source tools that helps to test load on web servers.

[dfads params=’groups=-1′]

I executed following command on my linux terminal:

[code]

ab -c 1000 -n 1000 -t 60 -k http://ignou.ac.in

[/code]

Option -c : This option says there are 1000 concurrent users logged in on the Web Server.

Option -n : This option sends 1000 requests to the Web Server.

Option -t : This option says users will be logged in for 60 seconds.

Option -k : For Keep Alive On

I logged in to the web server and executed the following command to test the actual load.

[code]

top

[/code]

This command helped to track down the load average, CPU and Memory Utilization of the web server.

[dfads params=’groups=-1′]

Difference between PHP4 & PHP5

Here’s a quick overview of what has changed between PH4 and PHP5. PHP5 for the most part is backwards compatible with PHP4, but there are a couple key changes that might break your PHP4 script in a PHP5 environment. If you aren’t already, I stronly suggest you start developing for PHP5. Many hosts these days offer a PHP5 environment, or a dual PHP4/PHP5 setup so you should be fine on that end. Using all of these new features is worth even a moderate amount of trouble you might go through finding a new host!

Note: Some of the features listed below are only in PHP5.2 and above.

Object Model
The new OOP features in PHP5 is probably the one thing that everyone knows for sure about. Out of all the new features, these are the ones that are talked about most!

Passed by Reference
This is an important change. In PHP4, everything was passed by value, including objects. This has changed in PHP5 — all objects are now passed by reference.

PHP Code:
$joe = new Person();
$joe->sex = 'male';
$betty = $joe;
$betty->sex = ‘female’;

echo $joe->sex; // Will be ‘female’

The above code fragment was common in PHP4. If you needed to duplicate an object, you simply copied it by assigning it to another variable. But in PHP5 you must use the new clone keyword.

Note that this also means you can stop using the reference operator (&). It was common practice to pass your objects around using the & operator to get around the annoying pass-by-value functionality in PHP4.

Class Constants and Static Methods/Properties
You can now create class constants that act much the same was as define()’ed constants, but are contained within a class definition and accessed with the :: operator.

Static methods and properties are also available. When you declare a class member as static, then it makes that member accessible (through the :: operator) without an instance. (Note this means within methods, the $this variable is not available)

Visibility
Class methods and properties now have visibility. PHP has 3 levels of visibility:

  1. Public is the most visible, making methods accessible to everyone and properties readable and writable by everyone.
  2. Protected makes members accessible to the class itself and any subclasses as well as any parent classes.
  3. Private makes members only available to the class itself.

Unified Constructors and Destructors
PHP5 introduces a new unified constructor/destructor names. In PHP4, a constructor was simply a method that had the same name as the class itself. This caused some headaches since if you changed the name of the class, you would have to go through and change every occurrence of that name.

In PHP5, all constructors are named __construct(). That is, the word construct prefixed by two underscores. Other then this name change, a constructor works the same way.

Also, the newly added __destruct() (destruct prefixed by two underscores) allows you to write code that will be executed when the object is destroyed.

Abstract Classes
PHP5 lets you declare a class as abstract. An abstract class cannot itself be instantiated, it is purely used to define a model where other classes extend. You must declare a class abstract if it contains any abstract methods. Any methods marked as abstract must be defined within any classes that extend the class. Note that you can also include full method definitions within an abstract class along with any abstract methods.

Interfaces
PHP5 introduces interfaces to help you design common APIs. An interface defines the methods a class must implement. Note that all the methods defined in an interface must be public. An interface is not designed as a blueprint for classes, but just a way to standardize a common API.

The one big advantage to using interfaces is that a class can implement any number of them. You can still only extend on parent class, but you can implement an unlimited number of interfaces.

Magic Methods
There are a number of “magic methods” that add an assortment to functionality to your classes. Note that PHP reserves the naming of methods prefixed with a double-underscore. Never name any of your methods with this naming scheme!

Some magic methods to take note of are __call, __get, __set and __toString. These are the ones I find most useful.

Finality
You can now use the final keyword to indicate that a method cannot be overridden by a child. You can also declare an entire class as final which prevents it from having any children at all.

The __autoload Function
Using a specially named function, __autoload (there’s that double-underscore again!), you can automatically load object files when PHP encounters a class that hasn’t been defined yet. Instead of large chunks of include’s at the top of your scripts, you can define a simple autoload function to include them automatically.

PHP Code:
function __autoload($class_name) {
require_once "./includes/classes/$class_name.inc.php";
}

Note you can change the autoload function or even add multiple autoload functions using spl_autoload_register and related functions.

Standard PHP Library
PHP now includes a bunch of functionality to solve common problems in the so-named SPL. There’s a lot of cool stuff in there, check it out!

For example, we can finally create classes that can be accessed like arrays by implementing the ArrayAccess interface. If we implement the Iterator interface, we can even let our classes work in situations like the foreach construct.

Miscellaneous Features

Type Hinting
PHP5 introduces limited type hinting. This means you can enforce what kind of variables are passed to functions or class methods. The drawback is that (at this time), it will only work for classes or arrays — so no other scalar types like integers or strings.

To add a type hint to a parameter, you specify the name of the class before the $. Beware that when you specify a class name, the type will be satisfied with all of its subclasses as well.

PHP Code:
function echo_user(User $user) {
echo $user->getUsername();
}

If the passed parameter is not User (or a subclass of User), then PHP will throw a fatal error.

Exceptions
PHP finally introduces exceptions! An exception is basically an error. By using an exception however, you gain more control the simple trigger_error notices we were stuck with before.

An exception is just an object. When an error occurs, you throw an exception. When an exception is thrown, the rest of the PHP code following will not be executed. When you are about to perform something “risky”, surround your code with a try block. If an exception is thrown, then your following catch block is there to intercept the error and handle it accordingly. If there is no catch block, a fatal error occurs.

PHP Code:
try {
$cache->write();
} catch (AccessDeniedException $e) {
die('Could not write the cache, access denied.');
} catch (Exception $e) {
die('An unknown error occurred: ' . $e->getMessage());
}

E_STRICT Error Level
There is a new error level defined as E_STRICT (value 2048). It is not included in E_ALL, if you wish to use this new level you must specify it explicitly. E_STRICT will notify you when you use depreciated code. I suggest you enable this level so you can always stay on top of things.

Foreach Construct and By-Reference Value
The foreach construct now lets you define the ‘value’ as a reference instead of a copy. Though I would suggest against using this feature, as it can cause some problems if you aren’t careful:

PHP Code:
foreach($array as $k => &$v) {
// Nice and easy, no working with $array[$k] anymore
$v = htmlentities($v);
}
// But be careful, this will have an unexpected result because
// $v will still be a reference to the last element of the $array array
foreach($another_array as $k => $v) {

}

 

New Functions
PHP5 introduces a slew of new functions. You can get a list of them from the PHP Manual.

New Extensions
PHP5 also introduces new default extensions.

  • SimpleXML for easy processing of XML data
  • DOM and XSL extensions are available for a much improved XML-consuming experience. A breath of fresh air after using DOMXML for PHP4!
  • PDO for working with databases. An excellent OO interface for interacting with your database.
  • Hash gives you access to a ton of hash functions if you need more then the usual md5 or sha1.

Compatibility Issues
The PHP manual has a list of changes that will affect backwards compatibility. You should definately read through that page, but here is are three issues I have found particularly tiresome:

  • array_merge() will now give you warnings if any of the parameters are not arrays. In PHP4, you could get away with merging non-arrays with arrays (and the items would just be added if they were say, a string). Of course it was bad practice to do this to being with, but it can cause headaches if you don’t know about it.
  • As discussed above, objects are now passed by references. If you want to copy a object, make sure to use the clone keyword.
  • get_*() now return names as they were defined. If a class was called MyTestClass, then get_class() will return that — case sensitive! In PHP4, they were always returned in lowercase.

About Your Relationships

Are you in conflict with the people you love most? Do you experience incredible highs followed by invariable lows in your relationships? Have the days of wine and roses become days of whine and neuroses?

Love tainted with selfishness is ‘attachment’; it is only about you. You expect a return for your affection, tangible or intangible. You make demands on people and bind them. You feel insecure, vulnerable and threatened. Your expectations never seem to be met with. The more people do for you, the more you want. The relationship thus becomes conflict-ridden. In the end, it breaks down and you lose the person.

The age-old philosophy of Vedanta steps in with new ways of defining ourselves, others and the world around us — ways that will appeal to the younger generation. It takes dedication, a leap of faith and practice.

Expand your mind. Get attached to a wider circle of people — community, nation, humanity. Work for loka sangraha, for the welfare of the world. As you get attached to the higher you get detached from the lower. True love is born and your relationships become free from the endless strife that prevails now.

In order to fill the haunting sense of emptiness in your life you depend on people for your happiness. Thus the starting point is faulty. Only when you are happy within can you establish meaningful relationships with others. It is absurd to depend on others to fill the void. Vedanta says you are paripurna — totally fulfilled. You do not need anyone to make you happy. Gain knowledge of your fulfilled state.

Love others for what they are, the good as well as the bad. Understand that people behave according to their nature. Do you hate a lion for its ferocity or a deer for its timidity? You love both creatures equally because you understand their nature and accept them for what they are. What prevents you from accepting people as they are? Why do you complain when a partner gets angry or a child is timid?

Look at others as part of yourself and you will focus on their best qualities. You will see opponents as partners, competitors as comrades. You will celebrate others’ victory as if it were your own. Thus your happiness multiplies a billion times! Today you are happy only when good things happen to you. In the end love turns Godword. You worship God in all beings.

Vedanta says there is only One. If you see separateness, it is your delusion. Just as one ray of light refracts into seven different colours, you see distinctions and demarcations because you view the world through the prism of your body, mind and intellect. You see maximum separateness when you identify with your body. See the world through your mind and your circle of love expands to include your family. Rise to the intellect and you see oneness among your compatriots. Merge with Atman, the Spirit within, and all differences vanish.

You exult in the experience of the One in the many. You see yourself in all beings and all beings in the Self, just as you admire your images in different mirrors. Only then will you be free from sorrow and delusion. And you will attain the exalted state of enlightenment.

–Jaya Row

The Speaking Tree, Page No: 20, 09 July 2011

Trusting Others

On this day, Morrie says that he has an exercise for us to try. We are to stand, facing away from our classmates, and fall backward, relying on another student to catch us. Most of us are uncomfortable with this, and we cannot let go for more than a few inches before stopping ourselves. We laugh in embarrassment. Finally, one student, a thin, quiet, dark-haired girl who I notice almost always wears bulky, white fisherman sweaters, crosses her arms over her chest, closes her eyes, leans back, and does not flinch, like one of those Lipton tea commercials where the model splashes into the pool. For a moment, I am sure she is going to thump on the floor. At the last instant, her assigned partner grabs her head and shoulders and yanks her up harshly.

“Whoa!” several students yell. Some clap. Morrie finally smiles. “You see”, he says to the girl, “you closed your eyes, that was the difference. Sometimes you cannot believe what you see, you have to believe what you feel. And if you are ever going to have other people trust you, you must feel that you can trust them too — even when you’re in dark. Even when you are falling”.

The Speaking Tree, Page No: 08, 19, June, 2011

PHP Form Image Upload

This tutorial shows you how to upload an image on your server using PHP and html forms. You will also learn how to verify if the uploaded file is an image (checking the extension), if it doesn’t overtakes a size limit and how to change the uploaded file name.

Important: You must set the enctype form atribute to “multipart/form-data”, otherwise the form will not show you any errors, but it will just not upload your images!

 

Step 1: Create a folder named images located in the path you are planning to place the php script you are about to create. Make sure it has write rights for everybody or the scripts won’t work ( it won’t be able to upload the files into the directory).

Step 2: Paste the following code into a php file.

Please read carefuly the comments. All steps are explained there.

<?php
//define a maxim size for the uploaded images in Kb
 define ("MAX_SIZE","100"); 

//This function reads the extension of the file. It is used to determine if the file  is an image by checking the extension.
 function getExtension($str) {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }

//This variable is used as a flag. The value is initialized with 0 (meaning no error  found)  
//and it will be changed to 1 if an errro occures.  
//If the error occures the file will not be uploaded.
 $errors=0;
//checks if the form has been submitted
 if(isset($_POST['Submit'])) 
 {
 	//reads the name of the file the user submitted for uploading
 	$image=$_FILES['image']['name'];
 	//if it is not empty
 	if ($image) 
 	{
 	//get the original name of the file from the clients machine
 		$filename = stripslashes($_FILES['image']['name']);
 	//get the extension of the file in a lower case format
  		$extension = getExtension($filename);
 		$extension = strtolower($extension);
 	//if it is not a known extension, we will suppose it is an error and will not  upload the file,  
	//otherwise we will do more tests
 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
 		{
		//print error message
 			echo '<h1>Unknown extension!</h1>';
 			$errors=1;
 		}
 		else
 		{
//get the size of the image in bytes
 //$_FILES['image']['tmp_name'] is the temporary filename of the file
 //in which the uploaded file was stored on the server
 $size=filesize($_FILES['image']['tmp_name']);

//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*1024)
{
	echo '<h1>You have exceeded the size limit!</h1>';
	$errors=1;
}

//we will give an unique name, for example the time in unix time format
$image_name=time().'.'.$extension;
//the new name will be containing the full path where will be stored (images folder)
$newname="images/".$image_name;
//we verify if the image has been uploaded, and print error instead
$copied = copy($_FILES['image']['tmp_name'], $newname);
if (!$copied) 
{
	echo '<h1>Copy unsuccessfull!</h1>';
	$errors=1;
}}}}

//If no errors registred, print the success message
 if(isset($_POST['Submit']) && !$errors) 
 {
 	echo "<h1>File Uploaded Successfully! Try again!</h1>";
 }

 ?>

 <!--next comes the form, you must set the enctype to "multipart/frm-data" and use an input type "file" -->
 <form name="newad" method="post" enctype="multipart/form-data"  action="">
 <table>
 	<tr><td><input type="file" name="image"></td></tr>
 	<tr><td><input name="Submit" type="submit" value="Upload image"></td></tr>
 </table>	
 </form>

This code was tested and works fine, I hope you will find it useful.