Saturday 29 December 2012

Create an Animated Gif in Photoshop

Many users of photoshop don’t seem to ever get their hands dirty in the animation tools that Photoshop gives you. Well, this post is here to help you to start using more than $50 worth of photoshop!
First , we need to create our image, with all of the layers that will make up this animation. In the image below, I have 5 layers. 4 different background color layers and one text layer. The animation I want to achieve is simply to have the background color change thru the different colors. Very basic animation but it is a good start in learning how to animate in photoshop.
Animated Gif Tutorial Image 1
Now, we need to open up our "Animation" window (have you ever opened this up before?!) Go to "Window > Animation" and the animation panel should pop up at the bottom of your photoshop interface.
Animated Gif Tutorial Image 2
To start building our animation, we need to create "frames" in the animation panel. Click on the icon "Duplicate selected frames". This will duplicate the first fame already displayed in our animation panel. I am going to create 4 frames for this simple animation; One frame for each background color.
Animated Gif Tutorial Image 3
Once you have the correct number of frames that you want, now we need to determine what layers are to display in each frame. So, for the first frame, I want the dark teal color to show up along with the text layer. Click on the "eye" icon to hide the layers that should not be visible in the first frame. For this animation, I am hiding the other background colors for the first frame.
Animated Gif Tutorial Image 4
Complete this step for each frame in your animation, hiding and showing the correct layers for each frame.
Now we need to decide how long each frame should display for….for my animation, I will make each frame show for 2 seconds. The image below shows you where to click to control the seconds for each frame.
Animated Gif Tutorial Image 5
After you have added the timing, test your animation. Click on the play button at the bottom of the animation panel and you should see your animated gif in action.
Animated Gif Tutorial Image 6
There you go! You just learned how to create an animated gif using photoshop! Let’s not stop there, there is one more little tool that will help you to create more advanced animated gifs. We are going to use the "tween" tool.
Using Tweening
*NOTE** If you are going to create an animation using tweening, leave the timing set up until last. If you do this first on your original frames, each tween frame added will have the same time delay on each new frame as the original ones.**
To keep with our previous animation, let’s say I now want the text "brianyerkes.com" to scroll up and down as part of my animation. I need to move the text layer in each frame set this up.
In the first frame, move the text layer to the top of the document, and off of the displayed area. On the next frame, move the text to the bottom of the document, off of the displayed area.
So now, your first two frames should not have text visible inside them when you are looking at your animation panel. Repeat these steps for the other 2 frames, one with the text at the very top and one with the text at the very bottom.
With the first frame selected, click on the "more" icon on the very right top of your animation panel.
Animated Gif Tutorial Image 7
Click on "Tween", and you will be given a few tween options like frames to add for the tween animation. You can play around with these settings , but for this animation, I have used the default of 5 frames and tween with the "next frame". Hit "ok" and you should see your new frames added to your animation panel.
Continue to the old 2nd frame; now my 7th frame after the tween addition. Add a tween to this frame and do this for the other original frames. On the last original frame, you will need to select "First Frame" in the drop down menu for which frame to tween it with.
Play around with the time delays on each frame including the tween frames, and you are now ready to play your animation and test it out! If it looks good, go to "Save for web & devises" and select "gif". Done!
Ugly animation but at least it shows you how to achieve this!
Final Animated Gif

Friday 28 December 2012

on mouseover counting

move your mouse
move your mouse

Code goes here :




<!DOCTYPE html>
<html>
<head>
  <style>
div.out { width:20%; height:120px; margin:0 15px;
          background-color:#D6EDFC; float:left; }
div.in {  width:50%; height:40%;
          background-color:#FFCC00; margin:10px auto; }
p { line-height:1em; margin:0; padding:0; }
</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
 <p>code goes here :</p>
<div class="out overout">
  <span>move your mouse</span>
  <div class="in">
  </div>
</div>

<div class="out enterleave">
  <span>move your mouse</span>
  <div class="in">
  </div>
</div>

<script>
  var i = 0;
  $("div.overout").mouseover(function() {
    i += 1;
    $(this).find("span").text( "mouse over x " + i );
  }).mouseout(function(){
    $(this).find("span").text("mouse out ");
  });

  var n = 0;
  $("div.enterleave").mouseenter(function() {
    n += 1;
    $(this).find("span").text( "mouse enter x " + n );
  }).mouseleave(function() {
    $(this).find("span").text("mouse leave");
  });

</script>

</body>
</html>

Thursday 20 December 2012

simple css menu


css menu



your code goes here :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>css menu</title>
</head>

<body>
<div id="menu">
<ul>
<li><a href="#nogo">Link 1</a>
<ul>
<li><a href="#nogo">Link 1-1</a></li>
<li><a href="#nogo">Link 1-2</a></li>
<li><a href="#nogo">Link 1-3</a></li>
</ul>
</li>
<li><a href="#nogo">Link 2</a>
<ul>
<li><a href="#nogo">Link 2-1</a></li>
<li><a href="#nogo">Link 2-2</a></li>
<li><a href="#nogo">Link 2-3</a></li>
</ul>
</li>
<li><a href="#nogo">Link 3</a>
<ul>
<li><a href="#nogo">Link 3-1</a></li>
<li><a href="#nogo">Link 3-2</a></li>
<li><a href="#nogo">Link 3-3</a></li>
</ul>
</li>
</ul>
</div>
<style>
#menu{
padding:0;
margin:0;
}
#menu ul{
padding:0;
margin:0;
}
#menu li{
position: relative;
float: left;
list-style: none;
margin: 0;
padding:0;
}
#menu li a{
width:100px;
height: 30px;
display: block;
text-decoration:none;
text-align: center;
line-height: 30px;
background-color: black;
color: white;
}
#menu li a:hover{
background-color: red;
}
 #menu ul ul{
position: absolute;
top: 30px;
visibility: hidden;
}
#menu ul li:hover ul{
visibility:visible;

</style>
</body>
</html>

javascript digital date and time display


javascript digital date and time display



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>javascript digital date and time display</title>
<script>
function date_time(id)
{
        date = new Date;
        year = date.getFullYear();
        month = date.getMonth();
        months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'Jully', 'August', 'September', 'October', 'November', 'December');
        d = date.getDate();
        day = date.getDay();
        days = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
        h = date.getHours();
        if(h<10)
        {
                h = "0"+h;
        }
        m = date.getMinutes();
        if(m<10)
        {
                m = "0"+m;
        }
        s = date.getSeconds();
        if(s<10)
        {
                s = "0"+s;
        }
        result = ''+days[day]+' '+months[month]+' '+d+' '+year+' '+h+':'+m+':'+s;
        document.getElementById(id).innerHTML = result;
        setTimeout('date_time("'+id+'");','1000');
        return true;
}
</script>
</head>

<body>
<div style="border:2px solid #333;">
<span id="date_time"></span>
            <script type="text/javascript">window.onload = date_time('date_time');</script>
</div>
</body>
</html>

Wednesday 19 December 2012

Jquery slideshow with caption/next/preview menus

Jquery slideshow
Mini Ninjas Mini Ninjas
Your quest to defeat the Evil Samurai Warlord has begun. Control the powers of nature, possess creatures, use your furious Ninja skills to free your Ninja friends.
some image some image some image some image some image Borderlands
Fun combat and a steady flow of rewards make this journey a massively enjoyable one, especially with some fellow mercenaries along for the ride.

Features

Compatible with Internet Explorer 6+, Firefox 2+, Safari 2+, Google Chrome 3+, Opera 9+
  • Free to use under MIT licence
  • Compatible with Android and iPhone
  • Unique transition effects
  • Valid markup
  • Flexible configuration
  • Auto slide
  • Navigation box
  • Lightweight (8kb only)
  • Linking images
  • Fully customizable using CSS

show/hide table onclick

show/hide table onclick

show/hide two table on click

hdr1 hdr2 hdr3
one one click me
two two click me
threethree click me

i'm 1 i'm 1 i'm 1
i'm 2 i'm 2 i'm 2
i'm 3 i'm 3 i'm 3







 code goes here :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>show/hide table onclick</title>
<style type="text/css">
/*
IE 5.5 does not actually support "table-row-group"
only "table-header-group" and "table-footer-group"
but I've found the following CSS renders correctly
*/
tbody.on { display:table-row-group; }
tbody.off { display:none; }
</style>

<script type="text/javascript">
function toggleTbody(id) {
if (document.getElementById) {
var tbod = document.getElementById(id);
if (tbod && typeof tbod.className == 'string') {
if (tbod.className == 'off') {
tbod.className = 'on';
} else {
tbod.className = 'off';
}
}
}
return false;
}
</script>
</head>

<body>
<h3>show/hide two table on click </h3>
<div style="float:left; width:200px; padding:5px;">
<table class="mygrid">
<th>hdr1</th>
<th>hdr2</th>
<th>hdr3</th>

<tr>
<td>one</td>
<td>one</td>
<td><a href="#" onclick="return toggleTbody('two');">one View</a></td>
</tr>

<tr>
<td>two</td>
<td>two</td>
<td><a href="#" onclick="return toggleTbody('two');">two View</a></td>
</tr>

<tr>
<td>three</td><td>three</td>
<td><a href="#" onclick="return toggleTbody('two');">three View</a></td>
</tr>
</tbody>
</table>
</div>
<div style="float:left; padding-left:20px; ">
<!--<a href="#" onclick="return toggleTbody('two');">Toggle tbody two</a>-->
<table >
<tbody id="two">
<tr>
<td>1</td><td>1</td>
<td>3</a></td>
</tr>
<tr>
<td>2</td><td>2</td>
<td>2</a></td>
</tr>
<tr>
<td>3</td><td>3</td>
<td>3</a></td>
</tr>
</tbody>
</table>
</div>  
   
     <!-- author abhishek-->
</body>
</html>

How to solve Folders Showing as Shortcuts, Hidden in USB/Memory-Card/HDD

By connecting flash drives to the affected computer, often it shows flash drive containing just some folder's shortcuts. Sometimes it shows nothing though drive's properties show it has files in it. Even we get some inaccessible folder or file. This type of problem may also seen in our local drives (HDD partitions). Even paid anti-virus is unable to resolve those folders, they just scan and detect The AUTORUN worm which one will execute all programs. Then our important files remain hidden.

hidden folders shortcuts
Hidden folders and Shortcuts by the Autorun Worm


Here we will see how can we solve this problem by using command line and batch file. Though the batch file is nothing but the executable file contains command lines. So solving the hidden and shortcut problem of USB or drives, we must have the administrator privilege as we will execute something.

Using Command line:

To solve/fix the folder's hidden or system file, the easiest way is to run a command line. You can apply this command to USB and local drive as well, need to change the drive_letter.

Go to Run, type cmd and hit enter. In command prompt just type:

attrib -h -s -r -a /s /d drive_letter:\*.* 

And hit enter. Be sure you've typed the drive letter (e.g. j:,h: or D:) instead of "drive_letter" in the command line. My USB drive letter is J: and my command should looks like:
Command to change files attributs
Command for unhide system-hidden files on a drive

All files and folders will be normal and you should be able to delete the shortcuts, created by the virus.
Command line details: Here atrib=attribute, "-"=remove attribute/permits, h=hidden s=system, r=read-only, a=archive, /s=sub directory, /d=directory, drive_letter=the letter of the drive shown in windows explorer (e.g. j:,h: or D:) and *.* is called the wild card for all files.
If you don't like to be a "command Ninja" then see below.

USB, MicroSD, MiniSD or other Mmory Cards issue:

     1. Connect your USB or memory card to the PC or laptop.

     2. Copy these lines and paste it into a "new text file"

@echo off
attrib -h -s -r -a /s /d drive_letter:\*.*

3. In the 3rd line give the drive letter name (Example: J or K or L etc.) instead of "drive_name"

4. Save the text file as any_name.bat

5. Double click on the any_name.bat file and it will run in the command prompt and see the hidden files/folders come back.

6. Delete the shortcuts and unnecessary files and folders from USB drive.

Local drive issue:

1. Copy these lines and paste it into a "new text file"

@echo off 
attrib -h -s -r -a /s /d D:\*.*
attrib -h -s -r -a /s /d E:\*.*
attrib -h -s -r -a /s /d F:\*.*
attrib -h -s -r -a /s /d G:\*.*
attrib -h -s -r -a /s /d H:\*.*
attrib -h -s -r -a /s /d I:\*.*
attrib -h -s -r -a /s /d J:\*.*
@echo complete.
2. Save the text file as a bat file (example: any_name.bat)

3. Run this bat file by double-clicking on it.

Thus you can solve this kind of problems with a *.bat file. You can save the *.bat file for solving this hidden problem.

Important: These tutorials are applied for Windows 7/Vista/xp. You must have the administrative privilege to run the command or execute the .bat file. Put the " : " after the j, k, or D (drive letters). These commands are not case sensitive.

Refreshing/Redirecting Your Web Pages with HTML( Meta Tag)

What is the Meta Refresh Tag

The meta refresh tag or meta redirect is a tool for reloading and redirecting web pages. Remember that the meta refresh tag is easy to use and easy to use poorly. It uses HTML meta tags to change the current URL to a new one so the customer is taken automatically to a new web page.

How to Reload the Current Page with the Meta Refresh Tag

Place the following meta tag within the HEAD of your HTML document. When used to refresh the current page, the syntax looks like this:
<meta http-equiv="refresh" content="600">
<meta>—This is the HTML tag. It belongs in the HEAD of your HTML document. You can learn more about the META element
in the HTML tag library.
http-equiv="refresh"—This attribute tells the browser that this meta tag is sending an HTTP command rather than text content. The word refresh is an HTTP header used by the web server. It tells the server that the page is going to be reloaded or sent somewhere else.
content="600"—This is the amount of time, in seconds, until the browser should reload the current page.

One of the most common uses of this version of the refresh tag is to reload a page that has dynamic content on it. For example: a stock ticker or weather map. Some people also use them to reload ads, but that can annoy your readers.

How to Redirect to a New Page with the Meta Refresh Tag

While being able to reload the current page is useful, it is not typically what people want from the meta refresh tag. To redirect to a new page, the syntax is nearly the same as reloading the current page:
<meta http-equiv="refresh" content="2;url=http://webdesign.about.com/">
But, as you can see above, the content attribute is slightly different.
content="2;url=http://webdesign.about.com/"—The number is the time, in seconds, until the page should be redirected, just as before. Then, separated by a semi-colon (;) you write the URL of the new page to be loaded.
Be Careful. The most common error when writing a meta refresh tag to redirect to a new page is to add an extra quote mark in the middle. e.g. content="2;url="http://newpage.com". If you set up a meta refresh tag and your page is not redirecting, check for that error first.

Drawbacks to Using Meta Refresh Tags

Meta refresh tags have some drawbacks:
  • Meta refresh redirects have been used by spammers to fool search engines. So search engines remove those sites from their database. If you use a lot of meta refresh tags to redirect pages, the search engines may decide your site is spam and delete it from their index. It’s better to use a 301 Server Redirect instead.
  • If the redirect happens quickly (less than 2-3 seconds), readers with older browsers can’t hit the “Back” button. This is a usability problem.
  • If the redirect happens quickly and goes to a non-existant page, your readers may get stuck in a loop without seeing any content other than a 404 page. When this happens, most people simply give up and leave rather than trying to figure out where you were trying to take them.
  • Refreshing the current page can confuse people. If they didn’t request the reload, some people can get concerned about security.

Monday 17 December 2012

tabSlideOut jQuery plugin

See that little tab over there that says 'Contact'? If you click that it will slide out. This plugin allows you to easily add one of those to your page.
The most important part of getting this plugin to work is to have your image path and image dimensions set correctly in the options. In this version, using the code below, I am linking directly to google code for the jquery library as well as the plugin which I am hosting at code.google.com.

Getting started

In your <head> tag you need the javascript (with the options customized for your image):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/
jquery.min.js" type="text/javascript"></script>
<script src="http://tab-slide-out.googlecode.com/files/
jquery.tabSlideOut.v1.3.js"></script>

    <script type="text/javascript">
    $(function(){
        $('.slide-out-div').tabSlideOut({
            tabHandle: '.handle', 
//class of the element that will become your tab
            pathToTabImage: 'images/contact_tab.gif', 
//path to the image for the tab //Optionally can be set using css
            imageHeight: '122px', 
//height of tab image           //Optionally can be set using css
            imageWidth: '40px', 
//width of tab image            //Optionally can be set using css
            tabLocation: 'left', 
//side of screen where tab lives, top, right, bottom, or left
            speed: 300, 
 //speed of animation
            action: 'click', 
 //options: 'click' or 'hover', action to trigger animation
            topPos: '200px', 
//position from the top/ use if tabLocation is left or right
            leftPos: '20px', 
 //position from left/ use if tabLocation is bottom or top
            fixedPosition: false 
//options: true makes it stick(fixed position) on scroll
        });

    });

    </script>
                
Below that add your css:
      
      <style type="text/css">
      
      .slide-out-div {
          padding: 20px;
          width: 250px;
          background: #ccc;
          border: 1px solid #29216d;
      }      
      </style>
                        
Anywhere in your page, (I put mine right above my </body>) put in the html for your hidden content.
  <div class="slide-out-div">
  <a class="handle" href="#">Content</a>
  <h3>Contact me</h3>
  <p>Thanks for checking out my jQuery plugin, I hope you find this useful.</p>
  <p>This can be a form to submit feedback, or contact info</p>
  </div>
        
    
tabSlideOut jQuery plugin
Content

Contact me

Thanks for checking out my jQuery plugin, I hope you find this useful.
This can be a form to submit feedback, or contact info

Wednesday 12 December 2012

Top 10 Javascript Frameworks

javascript frameworks

Top 10 Javascript Frameworks – Which do you prefer?

Free Website Builder

Javascript libraries have become fundamental to good web design, almost all site nowadays have some element of Javascript or Ajax present. It is probably the main element in developing the Web 2.0 movement.
There are many Frameworks, which do you prefer?

Please note that this post is fairly old and some of the information may be out dated.
Perhaps you would prefer to browse our Javascript or jQuery categories.

1. script.aculo.us (http://script.aculo.us/)

script.aculo.usURL: http://script.aculo.us/.
Blog: n/a.
Documentation: http://wiki.script.aculo.us/.
Note: script.aculo.us is not a Framework by its self but it is an addon for Prototype.

"script.aculo.us provides you with easy-to-use, cross-browser user interface JavaScript libraries to make your web sites and web applications fly."

2. Prototype (http://www.prototypejs.org/)

PrototypeURL: http://www.prototypejs.org/.
Blog: http://www.prototypejs.org/blog.
Documentation: http://www.prototypejs.org/learn.

"Prototype is a JavaScript Framework that aims to ease development of dynamic web applications. Featuring a unique, easy-to-use toolkit for class-driven development and the nicest Ajax library around, Prototype is quickly becoming the codebase of choice for web application developers everywhere."

3. Moo Tools (http://www.mootools.net/)

Moo ToolsURL: http://www.mootools.net/.
Blog: http://blog.mootools.net/.
Documentation: http://docs.mootools.net/.
Demos:http://demos.mootools.net/.

"MooTools is a compact, modular, Object-Oriented JavaScript framework designed for the intermediate to advanced JavaScript developer. It allows you to write powerful, flexible, and cross-browser code with its elegant, well documented, and coherent API."

4. jQuery (http://jquery.com/)

 jQueryURL: http://jquery.com/.
Blog: http://jquery.com/blog/.
Documentation: http://docs.jquery.com/.

"jQuery is a fast, concise, JavaScript Library that simplifies how you traverse HTML documents, handle events, perform animations, and add Ajax interactions to your web pages. jQuery is designed to change the way that you write JavaScript".

5. MochiKit (http://www.mochikit.com/)

 MochiKitURL: http://www.mochikit.com/.
Blog: http://www.mochikit.com/blog.html.
Documentation: http://www.mochikit.com/doc/html/MochiKit/index.html.
Demos:http://www.mochikit.com/demos.html.

"MochiKit – makes JavaScript suck a bit less".

6. Rialto (http://rialto.improve-technologies.com/wiki/)

URL: http://rialto.improve-technologies.com/wiki/.
Blog: n/a
Documentation: http://rialto.improve-technologies.com/js/doc/.
Demos:http://rialto.improve-technologies.com/rialto/.

"Rialto (Rich Internet Application Toolkit) is ajax-based cross browser javascript widgets library".

7. Dojo Toolkit (http://dojotoolkit.org)

URL: http://dojotoolkit.org/about.
Blog: http://dojotoolkit.org/blog.
Documentation: http://dojotoolkit.org/docs.
Demos:http://dojotoolkit.org/demos.

"Dojo is an Open Source DHTML toolkit written in JavaScript. Dojo aims to solve some long-standing historical problems with DHTML which prevented mass adoption of dynamic web application development".

8. Spry Framework (http://labs.adobe.com/technologies/spry/)

URL: http://labs.adobe.com/technologies/spry/.
Blog: n/a.
Documentation: http://www.adobe.com/go/labs_gnav_wiki.
Demos:http://www.adobe.com/go/labs_gnav_showcase.

"The Spry framework for Ajax is a JavaScript library that provides easy-to-use yet powerful Ajax functionality that allows designers to build pages that provide a richer experience for their users. It is designed to take the complexity out of Ajax and allow designers to easily create Web 2.0 pages".

9. ASP.NET Ajax Framework (http://asp.net/ajax/)

URL: http://asp.net/ajax/.
Blog: n/a.
Documentation: http://asp.net/ajax/documentation/.
Demos:http://asp.net/ajax/showcase/.

"ASP.NET AJAX is a free framework for quickly creating efficient and interactive Web applications that work across all popular browsers".

10. Cean Ajax Framework (http://sourceforge.net/projects/clean-ajax/)

URL: http://sourceforge.net/projects/clean-ajax/.
Blog: n/a.
Documentation: http://sourceforge.net/docman/?group_id=145307.

"Easy to use AJAX framework that provides message queue, XSLT, XPath, encryption (SHA1, MD5), web service access (SOAP, XMLRPC), JSON-RPC, cross browser AJAX, AJAX history and cache control".

Tuesday 11 December 2012

jquery sibling method

What is .siblings() method in jQuery?

  • When we want to fetch siblings of every elements in the set of matched elements then we can use siblings() method.
  • We filter the elements fetched by an optional selector.
  • Syntax : .siblings( [selector])
  • “selector” is the selector expression which specify the matched elements.
For example
<ul>
<li> item 1 </li>
<li id=”second_item”> item 2 </li>
<li class=”myitem”> item 3 </li>
<li class=”myitem”> item 4 </li>
</ul>
Now we want to find the siblings of the element of id “second_item” and change the text color to Blue :
$(‘li.second_item’).siblings().css(‘color’,’blue’);
If we want specific sibling elements for example the elements having class “myitem” then we can pass a optional selector:
$(‘li.second_item’).siblings(‘.myitem’).css(‘color’,’blue’);

Saturday 8 December 2012

Send Emails Using PHP

How to Send Emails Using PHP

Hi everyone, I am not sure if anyone is interested in this, but I know I was when I first started to learn about PHP so I thought I would write a tutorial on how to send an email message through a PHP script. Once you know how to do this, it is simple to setup and you can do some cool things with it once you first grasp the basics of how everything works. So let's get started.

The Basics:

Every email has 4 basic components.

  • To: the email address of the person the email is being sent to
  • From: the email address of who the email is coming from
  • Subject: the subject of the email being sent
  • Message: the body of the email


Those 4 basic components are the heart of the PHP script that sends the email. Each one of those 4 components will be assigned to a variable in the PHP script and will be used to send the email. So to get started, we will need to create a new .php document. Whatever program you are using such as Dreamweaver (that is what I am using), TextMate, NotePad, Wordpad, BBEdit, or any other program you are using, copy and paste the following code at the top of the new .php document.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Create Email</title>
</head>
<body>


Once you have got that pasted into your new document, you want to go ahead and open your PHP tags. So right under the code you just pasted, type this:

<?php


Now this is where the fun starts. Instead of using the normal approach of creating the HTML page that will then send the POST data to the PHP page and then validate all of the user input that way, I decided to take a different approach. The way that I am going to show you is not hard at all, and you may already know it. If you do not know it already, it may seem harder if you have never seen it before, but once you learn this way of combining the HTML form and PHP script into one document instead of 2 documents your code will be more portable, easier to fix and find bugs, easier to improve, and overall just a better approach in my opinion. But there are sometimes where this approach is not the best or not possible and you must separate the HTML from the PHP. If you have no idea what I am talking about, you will in a few seconds :D

Okay, so once you have your opening PHP tag typed in, you need to check to see if the script has been submitted. So you would type this:

//Check to see if the form has been submitted
if (isset($_POST['submitted'])) {


What that checks for is the hidden form input in the HTML form. It checks to see if it "is set". The isset() function returns true as long as the variable exists and is not NULL. So, in this case, if the user filled out the form correctly, the $_POST['submitted'] variable is assigned the value "true" and the script continues along checking to see if any other errors occurred.

Next, once the script gets past the $_POST['submitted'] variable, it sets up an $errors array.

//Create an array that will contain all of the errors if ant are to occur once the script runs
$errors = array() ;


The $errors array will contain and hold all of the errors that occur (if any do occur) during the run of the script. Once you see the rest of the script, this will make more since to you.

Validation of User Input:

Next, is one of the most important parts of the script. User input validation checks. Although this is not the most secure way of securing the PHP script and checking for spam attacks and other attacks (I will write another tutorial on this later on), this works great and gets the job done for way more than the average person. To do our 1st validation check of 4, type this:

//Validate all user input
if (!empty($_POST['to'])) {
        $to = trim(strip_tags($_POST['to'])) ;
} else {
        $errors[] = 'You must enter a <b>to</b> address.' ;
}


What this does is that it first checks to make sure that the variable $_POST['to'] IS NOT empty. If it IS NOT empty, which means that it is not equal to 0 (0 as an integer), "0" (0 as a string), "" (an empty string), NULL, FALSE, array() (an empty array). So as long as the input by the user is not equal to the list of things above, the $_POST['to'] variable will be assigned to the variable $to. IF the $_POST['to'] variable is empty, it will NOT be assigned to the $to variable and an error message will be assigned to the $errors array. The code

$errors[] = 'You must enter a <b>to</b> address.' ;


means to assign the next numerical index to the $errors array. So, for example, if you have an array setup like this:

$array = array(1 => 'Value 1', 2 => 'Value 2', 3 => 'Value 3') ;


and you want to add a value to this, all you have to do is type the following code:

$array[] = 'Value 4' ;


Your new $array will now look like this:

$array = array(1 => 'Value 1', 2 => 'Value 2', 3 => 'Value 3', 4 => 'Value 4') ;


So that is what we are doing in our email example with the $errors array. Every time an error occurs in the script, instead of having to kill the script with the exit() function or die() function calls, you can allow the script to continue so the user will be able to see all of the errors that occur in the script rather than the last one that occurred.

So we want to do this same thing for each of the 4 basic components. Our whole script so far should look like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Create Email</title>
</head>
<body>
<?php
//Check to see if the form has been submitted
if (isset($_POST['submitted'])) {
        
        //Create an array that will contain all of the errors if ant are to occur once the script runs
        $errors = array() ;
        
        //Validate all user input
        if (!empty($_POST['to'])) {
                $to = trim(strip_tags($_POST['to'])) ;
        } else {
                $errors[] = 'You must enter a <b>to</b> address.' ;
        }
        
        if (!empty($_POST['from'])) {
                $from = "From: {$_POST['from']}" ;
                trim(strip_tags($from)) ;
        } else {
                $errors[] = 'You must enter a <b>from</b> address.' ;
        }
        
        if (!empty($_POST['subject'])) {
                $subject = trim(strip_tags($_POST['subject'])) ;
        } else {
                $errors[] = 'You must enter a <b>subject</b>.' ;
        }
        
        if (!empty($_POST['message']) && $_POST['message'] != 'Enter Your Message Here...') {
                $message = trim(strip_tags($_POST['message'])) ;
        } else {
                $errors[] = 'You must enter an original <b>message</b>.' ;
        }


All of the validation methods are the same foreach component of the email except for the $_POST['message'] variable. You might have noticed that it has an extra little bit of validation along with it. I will explain that part a little bit later.

Checking For Errors:

Next, we need to check to see if there were any errors when the user submitted the script. To do this, just type the following line of code:

//Check to make sure there were no errors while running the script
        if (empty($errors)) {


This line of code makes sure that the array $errors is empty. If the $errors array is empty, then there were no errors so far and now we are going to send the email :D

Sending the Email:

Since there are no errors in the script so far, it's now safe to try and send the email. To send the email, it is really simple. You will need to use the mail() function which can take up to 5 arguments. You will most likely only use 4 of them like I did here is this script. The 5 arguments the mail function can take are the following:

  • To: the message the email is being sent to
  • Subject: the subject of the email
  • Message: the actual message of the email
  • Additional Headers: these consist of headers such as from, cc, bcc, etc.
  • Additional Parameters: such as sending email in html or with sending email with attatchments


So the mail() function can look something like this:

mail('three3211@gmail.com', 'Subject Goes Here', 'Message of the Email Goes Here', 'From: somebody@domain.com') ;


Please take notice of a couple of things here.

  • Everything must be in quotes unless it is a variable
  • The From header is required and must be written like we here.


With that in mind, here is the code on how to send the email:

//Create the email and mail
if (mail($to , $subject , $message , $from)) {
        echo '<p>Your email has been sent!</p>' ;
} else {
        echo '<p>There was an error sending your email, please try again.</p>' ;
}


This checks to make sure that the email has been sent by putting it in an IF statement. We used the variable names here for each of the arguments that the mail function needs. Whatever the user types in the form will be replaced here when the form has been submitted. If the mail() function returns true, it will print out to the browser "Your email has been sent!". To make things clear, there is NO way of telling if the person you send the email to actually receives the email, reads the email, or if the email was actually even sent. The only way to test is to run the code through different functions and test and test it against your own email account to make sure it works. I have checked this against my Gmail and Yahoo email accounts and they both work great and instantly and they do NOT go to the spam folder. They go straight to my inbox.

Now, I am not going to go into details on this, but we now need to add an else clause just in case there were any errors when the form was submitted. The code for this would be this:

} else {
        //There were errors in the submission
//Use a foreach loop to loop through the errors array
//Print out errors heading before foreach loop

echo '<h2>Errors</h2>' ;
                
        foreach ($errors as $msg) {
                echo "- $msg<br />" ;
        }
                } //End of else clause


Display the HTML Form

Next, we need to add another else clause just in case the form has not been submitted. For example, if you were to go to the webpage for the first time, the HTML form would not submitted, and you would have to fill it out. So in that case we need to display the form for all of our first time visitors and for everyone else who wants to resubmit the form again. To do this, we need to add an else clause that will belong to the IF statement we made at the very beginning of the script which was:

//Check to see if the form has been submitted
if (isset($_POST['submitted'])) {


Now we are adding an else clause to this. So we would add this line of code to the bottom of our script:

} else { 
//The script has not been submitted yet
//Display the HTML form
echo '<form action="mail.php" method="post">
          <fieldset><legend>Enter your information in the form below:</legend>
          <p>To: <input name="to" type="text" size="30" /></p>
          <p>From: <input name="from" type="text" size="30" /></p>
          <p>Subject: <input name="subject" type="text" size="30" /></p>
          <p>Message:</p> <p><textarea name="message" cols="50" rows="10">Enter Your Message Here...</textarea></p>
          <input name="submit" type="submit" value="Email" />
          <input name="reset" type="reset" value="Reset" />
          <input name="submitted" type="hidden" value="true" />
          </fieldset>
          </form>' ;
          }
//End PHP
?>
</body>
</html>


This block of code only display the form if the $_POST['submitted'] is NOT assigned the value of "true". If the form has NOT been submitted, the $_POST['submitted'] variable will be empty and the form will be displayed. If the $_POST['submitted'] variable DOES have the value "true", then the form will not be displayed and the error checking and mail will try to be sent.

That's it! :o

I hope you liked this tutorial and I will be writing another one soon on how to add HTML to the email and how to add attachments to the email if people on the forum would like.

Full Email Script:

The script below is the full PHP script. It has some extra added features such as counting the words of the email and a couple of other cool little things. Nothing hard at all, just cool and useful. If you have any questions or if I accidentally skipped something please let me know :)



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Create Email</title>
</head>
<body>

<?php

//Check to see if the form has been submitted
if (isset($_POST['submitted'])) {
       
       
//Create an array that will contain all of the errors if ant are to occur once the script runs
        $errors
= array() ;
       
       
//Validate all user input
       
if (!empty($_POST['to'])) {
                $to
= trim(strip_tags($_POST['to'])) ;
       
} else {
                $errors
[] = 'You must enter a <b>to</b> address.' ;
       
}
       
       
if (!empty($_POST['from'])) {
                $from
= "From: {$_POST['from']}" ;
                trim
(strip_tags($from)) ;
       
} else {
                $errors
[] = 'You must enter a <b>from</b> address.' ;
       
}
       
       
if (!empty($_POST['subject'])) {
                $subject
= trim(strip_tags($_POST['subject'])) ;
       
} else {
                $errors
[] = 'You must enter a <b>subject</b>.' ;
       
}
       
       
if (!empty($_POST['message']) && $_POST['message'] != 'Enter Your Message Here...') {
                $message
= trim(strip_tags($_POST['message'])) ;
       
} else {
                $errors
[] = 'You must enter an original <b>message</b>.' ;
       
}
       
       
//Check to make sure there were no errors while running the script
       
if (empty($errors)) {
               
               
//Everything is okay here
       
               
//Create the email and mail
               
if (mail($to , $subject , $message , $from)) {
                        echo
'<p>Your email has been sent!</p>' ;
                       
                       
//Check to see how many words there are in the email
                       
if (str_word_count($message) > 1) {
                                echo
'<p>There were ' . str_word_count($message) . ' words in your email.</p>' ;
                       
} else {
                                echo
'<p>There was ' . str_word_count($message) . ' word in your email.</p>' ;
                       
}
                       
                       
//Check to see how many characters there are in the email
                       
if (strlen($message) > 1) {
                                echo
'<p>There were ' . strlen($message) . ' characters in your email.</p>' ;
                       
} else {
                                echo
'<p>There was ' . strlen($message) . ' character in your email.</p>' ;
                       
}
                       
                        echo
'<p><a href="http://your_web_site_here.com/mail.php">Click Here to Send Another Email</a>' ;
                       
               
} else {
                        echo
'<p>There was an error sending your email, please try again.</p>' ;
               
}
               
       
} else {
               
               
//There were errors in the submission
               
//Use a foreach loop to loop through the errors array
               
//Print out Errors Heading before foreach loop
                echo
'<h2>Errors</h2>' ;
               
               
foreach ($errors as $msg) {
                        echo
"- $msg<br />" ;
               
}
               
       
}
       
} else {

//The script has not been submitted yet
//Display the HTML form
echo
'<form action="mail.php" method="post">
          <fieldset><legend>Enter your information in the form below:</legend>
          <p>To: <input name="to" type="text" size="30" /></p>
          <p>From: <input name="from" type="text" size="30" /></p>
          <p>Subject: <input name="subject" type="text" size="30" /></p>
          <p>Message:</p> <p><textarea name="message" cols="50" rows="10">Enter Your Message Here...</textarea></p>
          <input name="submit" type="submit" value="Email" />
          <input name="reset" type="reset" value="Reset" />
          <input name="submitted" type="hidden" value="true" />
          </fieldset>
          </form>'
;
         
}

//End PHP
?>

</body>
</html>
1