Friday, 18 October 2013

Sending Emails with PHP

PHP must be configured correctly in the php.ini file with the details of how your system sends email.

Now you are ready to go:

Sending plain text email:

 

PHP makes use of mail() function to send an email. This function requires three mandatory arguments that specify the recipient's email address, the subject of the the message and the actual message additionally there are other two optional parameters.


mail( to, subject, message, headers, parameters );

 Here is the description for each parameters.

Parameter Description
to Required. Specifies the receiver / receivers of the email
subject Required. Specifies the subject of the email. This parameter cannot contain any newline characters
message Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters
headers Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n)
parameters Optional. Specifies an additional parameter to the sendmail program



As soon as the mail function is called PHP will attempt to send the email then it will return true if successful or false if it is failed.
Multiple recipients can be specified as the first argument to the mail() function in a comma separated list.

Example:

Following example will send an HTML email message to xyz@somedomain.com. You can code this program in such a way that it should receive all content from the user and then it should send an email.





<html>
<head>
<title>Sending email using PHP</title>
</head>
<body>
<?php
   $to = "xyz@somedomain.com";
   $subject = "This is subject";
   $message = "This is simple text message.";
   $header = "From:abc@somedomain.com \r\n";
   $retval = mail ($to,$subject,$message,$header);
   if( $retval == true )  
   {
      echo "Message sent successfully...";
   }
   else
   {
      echo "Message could not be sent...";
   }
?>
</body>
</html>


Sending HTML email:

When you send a text message using PHP then all the content will be treated as simple text. Even if you will include HTML tags in a text message, it will be displayed as simple text and HTML tags will not be formatted according to HTML syntax. But PHP provides option to send an HTML message as actual HTML message.
While sending an email message you can specify a Mime version, content type and character set to send an HTML email.

Example:

Following example will send an HTML email message to xyz@somedomain.com copying it to afgh@somedomain.com. You can code this program in such a way that it should recieve all content from the user and then it should send an email.


<html>
<head>
<title>Sending HTML email using PHP</title>
</head>
<body>
<?php
   $to = "xyz@somedomain.com";
   $subject = "This is subject";
   $message = "<b>This is HTML message.</b>";
   $message .= "<h1>This is headline.</h1>";
   $header = "From:abc@somedomain.com \r\n";
   $header = "Cc:afgh@somedomain.com \r\n";
   $header .= "MIME-Version: 1.0\r\n";
   $header .= "Content-type: text/html\r\n";
   $retval = mail ($to,$subject,$message,$header);
   if( $retval == true )
   {
      echo "Message sent successfully...";
   }
   else
   {
      echo "Message could not be sent...";
   }
?>
</body>
</html>


Sending attachments with email:

To send an email with mixed content requires to set Content-type header to multipart/mixed. Then text and attachment sections can be specified within boundaries.
A boundary is started with two hyphens followed by a unique number which can not appear in the message part of the email. A PHP function md5() is used to create a 32 digit hexadecimal number to create unique number. A final boundary denoting the email's final section must also end with two hyphens.
Attached files should be encoded with the base64_encode() function for safer transmission and are best split into chunks with the chunk_split() function. This adds \r\n inside the file at regular intervals, normally every 76 characters.
Following is the example which will send a file /tmp/test.txt as an attachment. you can code your program to receive an uploaded file and send it.


<html>
<head>
<title>Sending attachment using PHP</title>
</head>
<body>
<?php
  $to = "xyz@somedomain.com";
  $subject = "This is subject";
  $message = "This is test message.";
  # Open a file
  $file = fopen( "/tmp/test.txt", "r" );
  if( $file == false )
  {
     echo "Error in opening file";
     exit();
  }
  # Read the file into a variable
  $size = filesize("/tmp/test.txt");
  $content = fread( $file, $size);

  # encode the data for safe transit
  # and insert \r\n after every 76 chars.
  $encoded_content = chunk_split( base64_encode($content));
  
  # Get a random 32 bit number using time() as seed.
  $num = md5( time() );

  # Define the main headers.
  $header = "From:xyz@somedomain.com\r\n";
  $header .= "MIME-Version: 1.0\r\n";
  $header .= "Content-Type: multipart/mixed; ";
  $header .= "boundary=$num\r\n";
  $header .= "--$num\r\n";

  # Define the message section
  $header .= "Content-Type: text/plain\r\n";
  $header .= "Content-Transfer-Encoding:8bit\r\n\n";
  $header .= "$message\r\n";
  $header .= "--$num\r\n";

  # Define the attachment section
  $header .= "Content-Type:  multipart/mixed; ";
  $header .= "name=\"test.txt\"\r\n";
  $header .= "Content-Transfer-Encoding:base64\r\n";
  $header .= "Content-Disposition:attachment; ";
  $header .= "filename=\"test.txt\"\r\n\n";
  $header .= "$encoded_content\r\n";
  $header .= "--$num--";

  # Send email now
  $retval = mail ( $to, $subject, "", $header );
  if( $retval == true )
   {
      echo "Message sent successfully...";
   }
   else
   {
      echo "Message could not be sent...";
   }
?>
</body>
</html>








Sending e-mail from localhost in Windows Environment by using PHP mail function

Have you ever been frustrating, why e-mail is not going from the localhost while using XAMPP or WAMP or any other PHP servers in windows environment? well in that situation i think i can help you.In this article i am going to tell you how to send e-mail from localhost in PHP.
  • Open the “php.ini“. You should know where it is located because it depends upon the particular server you’re running.
  • Search for the attribute called “SMTP” in the php.ini file.Generally you can find the line “SMTP=localhost“. change the localhost to the smtp server name of your ISP. And, there is another attribute called “smtp_port” which should be set to 25.I’ve set the following values in my php.ini file.

    SMTP = smtp.wlink.com.np
    smtp_port = 25
  • Restart the apache server so that PHP modules and attributes will be reloaded.
  • Now try to send the mail using the mail() function ,

    mail(“you@yourdomain.com”,”test subject”,”test body”);

    you might get the warning like this, Warning: mail() [function.mail]: “sendmail_from” not set in php.ini or custom “From:” header missing in C:\Program Files\xampp\htdocs\testmail.php on line 1
  • Now specify the following headers and try to send the mail again,


    $headers = ‘MIME-Version: 1.0′ . “\r\n”; 
    $headers .= ‘Content-type: text/html; charset=iso-8859-1′ . “\r\n”;
     $headers .= ‘From: sender@sender.com’ . “\r\n”;
     mail(“you@yourdomain.com”,”test subject”,”test body”,$headers);
That’s all, the mail is sent to “you@yourdomain.com” from the localhost.

Note: Some smtp server verifies the email address of the sender so the email address which is in the place of “sender@sender.com” should be a valid and existing email address otherwise mail might not be sent to the “you@yourdomain.com”.

Wednesday, 2 October 2013

Understanding Javascript Events

Events

javascript is used to create dynamic web pages but with out events javascript is meaningless. Events are actions that can be detected by JavaScript.In this tutorial I give an overview of what event handling is, who to handle events.

Every element on a web page (button,anchor tag,input type etc) has certain events which can trigger a JavaScript. For example, we can use the onclick event of a button element to indicate that a function will run when a user clicks on the button. We define the events in the HTML tags.

JavaScript is meant to add interactivity to your pages: the user does something and the page reacts. this only possibele by the help of an event.

Events are normally used  with functions, and the function will not be executed before the event occurs.

Example How to use event:

<html>
<head>
function test(){
alert('onclick event example.');
}
</head>
<body>
<input type="button" name="clickme" value="click me" onclick="test();" />
</body>
</html>

here in the input element we add an event onClick and call an user define function test();

when user click on this button the onclick even fire and call the userdefine function test() and the code in side the function execute for more about user define function click here.

List of some events

Window Event Attributes


Events triggered for the window object (applies to the <body> tag): the event's are applied to body tag only.

onload

Fires after the page is finished loading

example: <body onload="function_name();">

onunload

Fires once a page has unloaded (or the browser window has been closed)

example: <body onunload="function_name();">

Form Events

 

Events triggered by actions inside a HTML form (applies to almost all HTML elements, but is most used in form elements):

onblur

Fires the moment that the element loses focus

example: <input type="text" name="fname" onblur="function_name();">

onchange 

Fires the moment when the value of the element is changed

example: <input type="text" name="fname" onchange ="function_name();">


onfocus 

Fires the moment when the element gets focus

example: <input type="text" name="fname" onfocus ="function_name();">

onreset 

Fires when the Reset button in a form is clicked

example <input type="reset" name="rst" value="Reset it" onreset="function_name();" >

onselect 

Fires after some text has been selected in an element

example: <input type="text" name="fname" onselect="function_name();">

onsubmit

Fires when a form is submitted

examle: <form name="form1" action="your asction" onsubmit="function_name();">


Keyboard Events


Events triggered by a key, or similar user actions:

onkeydown 

Fires when a user is pressing a key


example: <input type="text" name="fname" onkeydown ="function_name();">


onkeypress

Fires when a user presses a key

 example: <input type="text" name="fname" onkeypress ="function_name();">

onkeyup  

Fires when a user releases a key

example: <input type="text" name="fname" onkeyup ="function_name();">

 

Mouse Events

Events triggered by a mouse, or similar user actions:

onclick  

Fires on a mouse click on the element

example: <input type="button" name="fname" value="click"  onclick ="function_name();" />

ondblclick 

Fires on a mouse double-click on the element

example: <input type="button" name="fname" value="click"  ondbclick ="function_name();" />

onmousedown 

Fires when a mouse button is pressed down on an element

example: <div  onmousedown ="function_name();" ><!-- Your content --></div>


onmousemove 

Fires when the mouse pointer moves over an element

example: <div  onmousemove ="function_name();" ><!-- Your content --></div>

onmouseout 

Fires when the mouse pointer moves out of an element

example: <div  onmouseout ="function_name();" ><!-- Your content --></div> 

onmouseover 

Fires when the mouse pointer moves over an element

example: <div  onmouseover ="function_name();" ><!-- Your content --></div>  

onmouseup

Fires when a mouse button is released over an element

example: <div  onmouseup ="function_name();" ><!-- Your content --></div> 



javascript programming basics

Programming Basics

As we know that javascript is a popular scripting language and it support variables. Programmers use variables to store values. A variable can hold several types of data. In JavaScript you don't have to declare a variable's data type before using it.

Javascript is not a strongly typed language which means you rarely have to concern yourself with
the type of data a variable is storing, only what the variable is storing and in Javascript, variables
can store anything, even functions.

 Any variable can hold any JavaScript data type, including:
  • String data
  • Numbers
  • Boolean values (T/F)

Variable Names

There are rules and conventions in naming variables in any programming language. It is good practice to use descriptive names for variables. The following are the JavaScript rules:
  • The variable name must start with a letter or an underscore. example:firstName or _myName
  • You can use numbers in a variable name, but not as the first character.Ex:name01 or tuition$
  • You can't use space to separate characters.Ex:userName not user Name
  • Capitalize the first letter of every word except the first. Ex. salesTax or userFirstName

 

Variables

 

  • To declare variables, use the keyword var and the variable name: Example:var userName 7 ;
  • To assign values to variables, add an equal sign and the value:Ex: var userName = "Smith"; var price = 100

 

Operators

 

Like other programming language javascript also support following Operators
  • Assignment Operators(=,+=,-=,*=,/=,%=)
  • Arithmetic Operators(+,-,*,/,%,++,--)
  • Comparison Operators(==,!=,<,<=,>,>=)
  • Logical Operators(&&,||,!)
  • Conditional Operator(variablename=(condition)?value1:value2)

Note:The + Operator Used on Strings example : 

txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
 
//output:What a very nice day


Statements

  • Conditional statement (if, if.. else, switch)
  • Loop ( for loop, while loop )
  • try...catch throw

Conditional Statements

 

Want perform different actions for different decisions. You can use conditional statements in your code to do this. In JavaScript we have the following conditional statements:

  • if statement
    • use this statement to execute some code • only if a specified condition is true
  • if...else statement
    • use this statement to execute some code if the condition is true and another code if the condition is false
  • if...else if....else statement
    • use this statement to select one of many blocks of code to be executed.
  • switch statement
    • Use this statement to select one of many blocks of code to be executed

example of If...else if...else Statement

<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>");
}
else if (time>10 && time<16)
{
document.write("<b>Good day</b>");
}
else
{
document.write("<b>Hello World!</b>");
}
</script>

example of switch Statement
<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date();
theDay=d.getDay();
switch (theDay)
{
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
document.write("I'm looking forward to this weekend!");
}
</script>


loops

 

Some time we need same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this
In JavaScript, there are three different kind of loops:
  • for
  • while
  • do ..while

Exampel for loop:
 
The for loop is used when you know in advance how many times the script should run.
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=5;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

Exampel while loop:
 
Loops execute a block of code a specified number of times, or while a specified condition is true.

<html>
<body>
<script type="text/javascript">
var i=0;
while (i<=5)
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
</script>
</body>
</html>

Exampel do...while Loop
 
The do...while loop is a variant of the while loop. This loop will execute the block of code ONCE, and then it will repeat the loop as long as the specified condition is true.

<html>
<body>
<script type="text/javascript">
var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
while (i<=5);
</script>
</body>
</html>

JavaScript Break and Continue Statements  

 


The break Statement
 
The break statement will break the loop and continue executing the code that follows after the loop (if any).

<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>


The continue Statement
 
The continue statement will break the current loop and continue with the next value.

<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3)
{
continue;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

JavaScript For...In Statement
 
The for...in statement loops through the elements of an array or through the properties of an object.
Note: The code in the body of the for...in loop is executed once for each element/property.
Note: The variable argument can be a named variable, an array element, or a property of an object.


<html>
<body>
<script type="text/javascript">
var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
for (x in mycars)
{
document.write(mycars[x] + "<br />");
}
</script>
</body>
</html>
output:


JavaScript Try...Catch Statement


 
The try...catch statement allows you to test a block of code for errors.

Catching Errors
 
When browsing Web pages on the internet, we all have seen a JavaScript alert box telling us there is a runtime error and asking "Do you wish to debug?". Error message like this may be useful for developers but not for users. When users see errors, they often leave the Web page.

The try...catch Statement
 

The try...catch statement allows you to test a block of code for errors. The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs.



<html>
<head>
<script type="text/javascript">
var txt="";
function message()
{
try
{
adddlert("Welcome guest!");
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.description + "\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
}
}
</script>
</head>
<body>
<input type="button" value="View message" onclick="message()" />
</body>
</html>
output:

The Throw Statement

 
The throw statement allows you to create an exception. If you use this statement together with the try...catch statement, you can control program flow and generate accurate error messages.

Example
 
The example below determines the value of a variable called x. If the value of x is higher than 10, lower than 0, or not a number, we are going to throw an error. The error is then caught by the catch argument and the proper error message is displayed:

<html>
<body>
<script type="text/javascript">
var x=prompt("Enter a number between 0 and 10:","");
try
{
if(x>10)
{
throw "Err1";
}
else if(x<0)
{
throw "Err2";
}
else if(isNaN(x))
{
throw "Err3";
}
}
catch(er)
{
if(er=="Err1")
{
alert("Error! The value is too high");
}
if(er=="Err2")
{
alert("Error! The value is too low");
}
if(er=="Err3")
{
alert("Error! The value is not a number");
}
}
</script>
</body>
</html>


Functions

 

With functions, you can give a name to a whole block of code, allowing you to reference it from anywhere in your program. JavaScript has built-in functions for several predefined operations. Here are three some functions.
  • alert("message")
  • confirm("message")
  • prompt("message")

Function Example
 
<html>
<head>
<script type="text/javascript">
function show_prompt()
{
var name=prompt("Please enter your name","Harry Potter");
if (name!=null && name!="")
{
document.write("Hello " + name + "! How are you today?");
}
}
</script>
</head>
<body>
<input type="button" onclick="show_prompt()" value="Show prompt box" />
</body>
</html>
output:

User-Defined Functions
 
With user-defined functions, you can name a block of code and call it when you need it. You define a function in the HEAD section of a web page. It is defined with the function keyword, followed by the function name and any arguments.

function functionName(argument)
{
statements
 }
 Example:

<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!" onclick="displaymessage()" />
</form>
</body>
</html>


Output:


The return Statement
 
The return statement is used to specify the value that is returned from the function. So, functions that are going to return a value must use the return statement. The example below returns the product of two numbers (a and b):

<html>
<head>
<script type="text/javascript">
function product(a,b)
{
return a*b;
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(product(4,3));
</script>
</body>
</html>
output:


The Scope of JavaScript Variables (Life time of variable)

If you declare a variable within a function, the variable can only be accessed within that function.
When you exit the function, the variable is destroyed. These variables are called local variables. You
can have local variables with the same name in different functions, because each is recognized only
by the function in which it is declared.

If you declare a variable outside a function, all the functions on your page can access it. The lifetime
of these variables starts when they are declared, and ends when the page is closed.

Explore more about java script events here.

Why javascript & how to use javascript

Introduction

 

JavaScript is the most popular scripting language (a scripting language is a lightweight programming language) on the internet, and works in all major browsers, such as Internet Explorer, Firefox, Chrome, Opera, and Safari.

JavaScript was released by Netscape and Sun Microsystems in 1995.However, JavaScript is not the same thing as Java.

  • It designed to add interactivity to HTML pages
  • ItIs a scripting language (a scripting language is a lightweight programming language)
  • JavaScript code is usually embedded directly into HTML pages
  • JavaScript is an interpreted language (means that scripts execute without preliminary compilation)

 

Uses of JavaScript

 

  • Use it to add multimedia elements. With JavaScript you can show, hide, change, resize images, and create image rollovers. You can create scrolling text across the status bar.
  • Create pages dynamically Based on the user's choices, the date, or other external data, JavaScript can produce pages that are customized to the user.
  • Interact with the user It can do some processing of forms and can validate user input when the user submits the form.

 

Getting Started

 

JavaScript code is typically embedded in the HTML, to be interpreted and run by the client's browser. Here are some tips to remember when writing JavaScript commands.

  • JavaScript code is case sensitive
  • White space between words and tabs are ignored
  • Line breaks are ignored except within a statement
  • JavaScript statements end with a semi- colon ;

The HTML <script> tag is used to insert a JavaScript into an HTML page.Inside the <script> tag we use
the type attribute to define the scripting language. So, the <script type="text/javascript">and </script> tells where the JavaScript starts and ends:


Example given bellow:

<html>
<body>
<script type="text/javascript">
alert("Hello World!");
</script>
</body>
</html>


Where Do You Place Scripts?
 
  • Scripts can be in the either <head> section or <body> section
  • Convention is to place it in the <head> section
<html>
<head>
<script type="text/javascript">
....
</script>
</head>
<body>
<!-- your content -->

</body>
</html>

 

Implementing JavaScript

There are three ways to add JavaScript commands to your Web Pages.
  • Embedding code
  • Inline code
  • External file

 

Embedding code 

you can Embedding javascript commands in html tags .no need to write <script> tag

Example of Embedding javascript code.

<html>
<body onload="alert('hello world ! ');">

<!-- your content -->

</body>
</html>

Note: here onload() is a javascript event which will call at the time of browser load.
Chick here for more about java script events.

Inline code

Write javascript code in the html file by the help of  <script>  tag .
Example of Inline javascript code.


<html>
<body">

<script type="text/javascript">
alert("hello world!");
</script>

<!-- your content -->

</body>
</html>

External File

If you want to run the same JavaScript on several pages, without having to write the same script on every page, you can write a JavaScript in an external file.

Save the external JavaScript file with a .js file extension.
Note: The external script cannot contain the tags!

 Example of external js file bellow. Create a abc.js file and write following codes.

alert("hello world !");

Now create a xyz.html file and call  abc.js file by writting following code.

<html>
<body>
<script type="text/javascript" src="abc.js"></script>
</body>
</html>

I hope this tutorial will helps you for better understanding about javascript and how to use javascript. click here for more about javascript programming basics and syntax.

Monday, 30 September 2013

GET data with htaccess URL rewrite?

URL rewriting is one of the best way to create SEO friendly URL for your site.

Most dynamic sites include variables in their URLs that tell the site what information to show the user. Typically, this gives URLs like the following, telling the relevant script on a site to load product number 7

http://www.yourdomain.com/product.php?product_id=7

The problems with this kind of URL structure are that the URL is not at all memorable and not SEO friendly also.
In case of dynamic pages created by admin (product.php?slug=productname) or pages with query string you have to redirect that dynamic page to a existing page let's say "get-product.php" here you can get the slug value (query string value) by using PHP $_GET['slug'](super global variable) by the help of that variable you can fetch corresponding data from database.

Note: create a unique slug  from the title field for fetching data from database.

Write following code in .htaccess file for url rewrite of dynamic generated file.

RewriteEngine on
RewriteRule ^([A-Za-z0-9]+)\.php get-product.php?slug=$1 [NC,QSA,L]

Note: here we added some flags at the end of RewriteRule.
  • NC (case insensitive)
  • QSA (append query string from request to substituted URL)
  • L (last - stop processing rules)
Now go to "get-product.php" file write following code.

<?php print_r($_GET);?>

Output
Array ( [slug] => productname )

Sunday, 29 September 2013

PHP ini file and its uses

The ini File

The ini(initialization) file has come to be a pseudo standard among application developers for initializing data variables.

Most applications that use an ini file for configuration use the PHP parse_ini_file() function to get values from the ini file. Many classes and abstractions have been written to provide a Object Oriented approach, but the core remains the single PHP function to gain access to the values within.

The simple syntax within the ini file makes it simple to edit and is easy to read. The reason it has been around so long is due to this simplicity. Here is an example of an ini file. Create file called "config.ini"

;
; This is a comment
;
[database]
db_username = username
db_password = password
db_host = localhost
db_port = 1234

[mail]
mail_username = username
mail_password = password
mail_host = mail.example.com

[blog]
blog_title = "My Blog"
blog_moderate = 1
blog_images = 1


To parse the example config.ini file use PHP parse_ini_file() function in your php file.

<?php
    /*** turn on errors ***/
    error_reporting(E_ALL);

    /*** parse the ini file ***/
    $config parse_ini_file("config.ini"1);

    /*** print the array ***/
    print_r($config);?>

This simple script above reads the ini file int a multi-dimensional array for easy retrieval. The array looks like this.

Array
 (
  [database] => Array
  (
   [db_username] => username
   [db_password] => password
   [db_host] => localhost
   [db_port] => 1234
  )

  [mail] => Array
  (
   [mail_username] => username
   [mail_password] => password
   [mail_host] => mail.example.com
  )

  [blog] => Array
  (
   [blog_title] => My Blog
   [blog_moderate] => 1
   [blog_images] => 1
  )
 )

To retrieve a single value from the array is now a simple matter of reading the array as with any PHP array. In the following script, a single value is retrieved from the ini file, and a timer is added to see how long it takes.

<?php
    /*** turn on errors ***/
    error_reporting(E_ALL);

    /*** start a timer ***/
    $start microtime(true);

    /*** parse the ini file ***/
    $config parse_ini_file("config.ini"1);

    /*** get the database user name ***/
    echo $config['database']['db_username']."\n";

    /*** end timer ***/
    $end microtime(true);

    /*** show duration ***/
    echo round$end $start6) . "\n";?>

The above script echos the database db_username configuration option and calculates the time in seconds, rounded to six decimal places. The results from this test averaged around 0.000421

username
0.000425

File Handling in PHP

Opening and Closing Files

Files are opened in PHP using the fopen command. The command takes two parameters, the file to be opened, and the mode in which to open the file. The function returns a file pointer if successful, otherwise zero (false). Files are opened with fopen for reading or writing.

$fp = fopen("myfile.txt", "r");

If fopen is unable to open the file, it returns 0. This can be used to exit the function with an appropriate message.

if ( !($fp = fopen("myfile.txt", "r") ) )
exit("Unable to open the input file.");


FileModes

The following table shows the different modes the file may be opened in.

Mode Description
r Read Only mode, with the file pointer at the start of the file.
r+ Read/Write mode, with the file pointer at the start of the file.
w Write Only mode. Truncates the file (effectively overwriting it). If the file doesn't exist, fopen will attempt to create the file.
w+ Read/Write mode. Truncates the file (effectively overwriting it). If the file doesn't exist, fopen will attempt to create the file.
a Append mode, with the file pointer at the end of the file. If the file doesn't exist, fopen will attempt to create the file.
a+ Read/Append, with the file pointer at the end of the file. If the file doesn't exist, fopen will attempt to create the file.

Note: The mode may also contain the letter 'b'. This is useful only on systems which differentiate between binary and text files (i.e.Windows. It's useless on Unix/Linux). If not needed, it will be ignored.


Closing a File

The fclose function is used to close a file when you are finished with it.

fclose($fp);


Reading from Files

You can read from files opened in r, r+, w+, and a+ mode. The feof function is used to determine if the end of file is true.

if ( feof($fp) )
echo "End of file
";

The feof function can be used in a while loop, to read from the file until the end of file is encountered. A line at a time can be read with the fgets function:

while( !feof($fp) ) {
// Reads one line at a time, up to 254 characters. Each line ends with a newline.
// If the length argument is omitted, PHP defaults to a length of 1024.
$myline = fgets($fp, 255);
echo $myline;
}

You can read in a single character at a time from a file using the fgetc function:

while( !feof($fp) ) {
// Reads one character at a time from the file.
$ch = fgetc($fp);
echo $ch;
}

You can also read a single word at a time from a file using the fscanf function. The function takes a variable number of parameters, but the first two parameters are mandatory. The first parameter is the file handle, the second parameter is a C-style format string. Any parameters passed after this are optional, but if used will contain the values of the format string.

if (!($fp = fopen($listFile, "r")))
exit("Unable to open $listFile.");
while (!feof($fp)) {
// Assign variables to optional arguments
$buffer = fscanf($fp, "%s %s %d", $name, $title, $age);
if ($buffer == 3) // $buffer contains the number of items it was able to assign
print "$name $title $age
\n";
}

Here is the file list.txt:
Dave Programmer 34
Sue Designer 21
Lisa Programmer 29
Nigel User 19

You can also store the variables in an array by omitting the optional parameters in fscanf:

while (!feof($fp)) {
$buffer = fscanf($fp, "%s %s %d"); // Assign variables to an array
// Use the list function to move the variables from the array into variables
list($name, $title, $age) = $buffer;
print "$name $title $age
\n";
}

You can read in an entire file with the fread function. It reads a number of bytes from a file, up to the end of the file (whichever comes first). The filesize function returns the size of the file in bytes, and can be used with the fread function, as in the following example.

$listFile = "myfile.txt";
if (!($fp = fopen($listFile, "r")))
exit("Unable to open the input file, $listFile.");
$buffer = fread($fp, filesize($listFile));
echo "$buffer
\n";
fclose($fp);

You can also use the file function to read the entire contents of a file into an array instead of opening the file with fopen:

$array = file(‘filename.txt’);

Each array element contains one line from the file, where each line is terminated by a newline.


Writing to Files

The fwrite function is used to write a string, or part of a string to a file. The function takes three parameters, the file handle, the string to write, and the number of bytes to write. If the number of bytes is omitted, the whole string is written to the file. If you want the lines to appear on separate lines in the file, use the \n character.  
Note:Windows requires a carriage return character as well as a new line character, so if you're using Windows, terminate the string with \r\n. The following example logs the visitor to a file, then displays all the entries in the file.

\r\n";
else
$userDetails .= "
\r\n";
fwrite($fp, "$userDetails"); // Write the user details to the file
rewind($fp); // Move the file pointer to the start of the file
$entries = 0;
while(!feof($fp)) { // Display each line in the file
$buffer = fgets($fp, 1024);
if ($buffer != "") {
echo $buffer;
$entries++;
}
} // Show a summary
echo "There are $entries entries in the log file
";
fclose ($fp);
?>


Locking Files

boolean flock ( resource fp, integer operation)

 PHP supports a portable way of locking complete files in an advisory way (which means all accessing programs have to use the same way of locking or it will not work). If there is a possibility that more than one process could write to a file at the same time then the file should be locked.

flock() operates on fp which must be an open file pointer. operation is one of the following:
  • To acquire a shared lock (reader), set operation to LOCK_SH
  • To acquire an exclusive lock (writer), set operation to LOCK_EX
  • To release a lock (shared or exclusive), set operation to LOCK_UN
  • If you don't want flock() to block while locking, add LOCK_NB to LOCK_SH or LOCK_EX
When obtaining a lock, the process may block. That is, if the file is already locked, it will wait until it gets the lock to continue execution. flock() allows you to perform a simple reader/writer model which can be used on virtually every platform (including most Unix derivatives and even Windows). flock() returns TRUE on success and FALSE on error (e.g. when a lock could not be acquired).

Here is a script that writes to a log file with the fputs function and then isplays the log file’s contents:

”; // dump log
readfile(“/tmp/log.txt”);
echo “
\n”; ?>


Other Useful File Functions

The opendir function returns a directory handle; closedir closes a directory; readdir reads a directory entry.

$myDirectory = opendir(“.”); // use the current directory
while($entryname = readdir($myDirectory)) {
echo “”;
echo “$entryname

”;
echo “”;
echo filesize($entryname); // the filesize function returns the file size in bytes
echo “

”;
echo “\n”;
}c
losedir($myDirectory);

The is_dir function tests if a filename refers to a directory:

if(is_dir($filename))
echo $filename . “ is a directory”;

The is_file function determines if a filename refers to a file:

if(is_file($filename))
echo $filename . “ is a file”;

The is_readable function returns TRUE if the file exists and it is readable, otherwise it returns false. On Unix/Linux this is determined by the file’s permissions. On Windows, TRUE is always returned if the file exists.

if(is_readable($filename))
echo $filename . “ is readable”;

The is_writable function determines whether the server will allow you to write data to the file before you attempt to open it:

if(is_writable(‘../quotes.txt’)) {
// attempt to open the file and write to it
} else {
echo ‘The file is not writable’;
}

Note: there are many more file functions. Please refer to PHP documentation for an exhaustive list.

Introduction to PHP SESSION Variable

Introduction

As we know that http protocol is a stateless protocol so the web server does not recognize you . A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database.

Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.

What is session control?

Gives ability to track a user through site, and easily move data related to that user among pages.No need to move data through hidden form fields.
Very useful for authentication, but can be used any time persistent data needed throughout a site visit.

How sessions work

Sessions are identified by a random number (Session ID) generated by PHP and stored on the client computer in 1 of 2 ways:
  1. Using a cookie, if the user's browser supports.
  2. Appending the session number to URLs as user traverses site (i.e  www.whatever.com?PHPSESSID=495294532459x)
Session ID corresponds a session data store onserver
A session will eventually expire‐‐usually after aspecified period of inactivity.

Progression of events

PHP script starts a session. Done before any other page activity.

session_start();// Session ID created and stored on user's computer. (if possible)


Session variables are created, and values stored on the server.
PHP script can use these variables from page to page throughout a site.

Starting a session In PHP

In any script using sessions, you must first call

session_start();
  •  If session has not been established, this will do that.
  • If a session has been established, this will load session data.
You must start the session at the very beginning of the script‐‐as part of header transmission.
Add or access session variables by using the $_SESSION superglobal array.

Session Handling

Createa page ses1.php copy the following code in that page. and run it. now session will be set.

<?php
session_start();
$_SESSION['name'] = "your name";
$_SESSION['office'] = "company name";
$_SESSION['phone'] = 96951;
?>

Let's create another page ses_result.php copy following codes and run.


<?php
session start();
session_echo "Here's the session info:<br />";
foreach ($_SESSION as $var=>$contents)
echo "$var: $contents<br />";
?>


Manipulating the Session data

session_unset() erases all session variables and data.

unset() can be used to erase a single variable and data.

unset($_SESSION['myvar']);

session destroy() destroys the session data (without destroying the session variables).Can be useful for "logging out" user.


Session variable arrays

 Session variables can be arrays



<?php
session_start();
$_SESSION['list'][]="Hello";
$_SESSION['list'][]="Wow";
echo count($_SESSION['list'])."<br />";
foreach ($_SESSION['list'] as $item)
echo "$item<br />";
?>

Can be useful technique for shopping carts or other data that is accumulated over multiple page visits.

 

When and why to use Sessions

  • Performance: When performing a slow operation, storing the results for use on several pages is better than repeating the calculation on each.
    Example: storing results of SQL query
  • Sequence: When a user process takes place over a sequence of screens, storing information saves time and user input.
Personalization: Session variables can be used to store user color or layout preferences or facts about browsing activity. Pages can then adapt to that activity.


Introduction and use of cookies in PHP

Introduction

A cookie is a small text file composed of alphanumeric characters, which is created on your computer when your browser accesses a website that uses cookies. The files are used to help your browser navigate the website and fully use all its features like logins, preferences, language settings, themes, among other common features. The cookie is used solely to help your browser process a website, it doesn't collect any information from your computer or your file system.

The cookie containing following things
  • The name of the website server that created the cookie
  • The duration of the cookie-how long use the cookie will be alive.
  • A cookie value-this unique information is normally a randomly generated number.

HTTP (Hyper Text Transfer Protocol), is  protocol used by the WWW ( World Wide Web). HTTP  is responsible for submit the user request to the Web server and receive the response from the server.
It is a  stateless protocol means it does not store or remember any value after sending the request  or receiving the response from server.
So cookies are used to remember some useful date in client side for example to remember login username and password in client side.

Using cookies in PHP

To create a cookie, use setcookie() function in php

setcookie(cookiename, value, [expire]);
setcookie("cook","27");

Expiration—expressed using time. If not set, cookie is valid for this user session only.

setcookie(cookiename, value, [expire]);
setcookie("other","1", time()+60*60*24*30);

Retrieved similar to $_POST variables: $_COOKIE['cookiename']

Deleting and checking cookies

To delete: overwrite cookie with expiration time in the past.

setcookie("cook","",time()-100);

Actual cookie deletion done by user's browser.

To see if the user accepts cookies, write one and then check (on another page or after a refresh) to see if it exists.

Saturday, 28 September 2013

Introduction to MVC Architecture and it's Benefits

MVC (Model-View-Controller) is a software architecture,or design pattern which is used in software engineering. The principle of MVC is  separation  the "presentation logic" from the "business logic".  MVC design pattern have some rules, that should be followed by the programmer to produce clean, scalable, powerful, fast code in the least amount of time with the least amount of effort.


The MVC principle is to separate the application into 3 main parts
"Model" ,"View","Controller"


Model 

Model is the most important part  of MVC .It is responsible for the business logic of he software application like the database logic, main logic of the application etc. End user does not bother about this logic,model doesn't interact with the end user.


View

View is responsible for the presentation  logic of the application , it represent the output   to the user.
it obtains data from the model and presents it to the user.

 
Controller

Controller is responsible for communication between model and view it send commands to the model to update the model's state (e.g., updating database). It can also send commands to its associated view to change the view's presentation of the model (e.g., Present the updated view).

 

Benefits of MVC

 

Substitutable user interface
 
Different views and controllers can be substituted to provide alternate user interfaces for the same model. For example, the same model data can be displayed as a bar graph, or a pie chart, or a spreadsheet.

Multiple simultaneous views of the same model
Multiple different views can be active at the same time. Each view simultaneously and independently presents the same information from the model. This applies more to GUI MVC than web MVC. 

Syncronized views
 The change propagation mechanism insures that all views simultaneously reflect the current state of the model.

Easier user interface changes 
Changes affecting just the user interface of the application logic become easier to make.

Easier testing
With MVC it can be easier to test the core of the application, as encapsulated by the model.

 




 

 








 

Thursday, 26 September 2013

PHP Class For Mobile Device Detection: Mobile_Detect

Mobile_Detect is an open source PHP class for detecting mobile devices.

It uses the User-Agent string combined with various HTTP headers in order to detect the mobile environment.

The class can easily understand whether the platform is mobile, tablet or desktop.


Also, functions exist for detecting whether it is iPad, iPhone, Android, Blackberry, etc. And, we can even drill-down to the versions of the platforms and browsers if needed.
It has a huge library of devices (including Nook, Nexus, Kindle, Archos..) and browsers for a stable detection.

Wednesday, 25 September 2013

Login or Register With Yahoo Open Id in PHP

This article will guide you to crate login or register with Yahoo.

The process and steps are same as login or register through Gmail. You only need to change the path from https://www.yahoo.com/accounts/o8/id to https://me.yahoo.com.

Step1:

Include your database connection file and openid.php to you login page.
Here you can download openid.php  file.

<?php
 include('connection.php');
 require_once 'yahoo/openid.php';
 $yahooid = new LightOpenID("localhost");//your damain name
 $yahooid->identity = 'https://www.yahoo.com/accounts/o8/id';
 $yahooid->required = array(
   'namePerson/first',
   'namePerson/last',
   'contact/email',);
$yahooid->returnUrl = 'http://xxx.com/login-yahoo.php';
?>

Now Add the following code to "Login with Yahoo" button.

<a href="<?php echo $yahooid->authUrl() ?>">Login with Yahoo</a>

If the user enters the correct info then Yahoo page will redirect back to or login page with required information's.

if ($yahooid->mode == 'cancel') {
echo "User has canceled authentication !";
} elseif($yahooid->validate()) {
$data = $yahooid->getAttributes();
$email = $data['contact/email'];
$firstname = $data['namePerson/first'];
$lastname = $data['namePerson/last'];

$Identity = explode("=",$yahooid->identity);
$userid = $Identity[1];
$loginwith = 'Yahoo';

$sql = mysql_query("select userid from register where passcode='".$userid."'");
$numrow = mysql_num_rows($sql);
if($numrow > 0){
header('Location:myaccount.php');
exit();
}
}

If the user registered before then our system will redirect the user to my account page otherwise it will ask the user to register for the first time.

if($_POST['register']){
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$email = mysql_real_escape_string($_POST['email']);
$passcode = mysql_real_escape_string($_POST['passcode']);
$loginwith = mysql_real_escape_string($_POST['loginwith']);
$status = 'active';
$mysql = mysql_query("insert into register set fastname = '".$fname."',
lastname = '".$lname."',
email = '".$email."',
passcode = '".$passcode."',
loginwith = '".$loginwith."',
status = '".$status."'");
header('Location:myaccount.php');
}

The MySql table used in this project

CREATE TABLE IF NOT EXISTS `register` (
`userid` int(11) NOT NULL AUTO_INCREMENT,
`fastname` varchar(50) NOT NULL,
`lastname` varchar(50) NOT NULL,
`email` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
`passcode` varchar(100) NOT NULL,
`loginwith` varchar(20) NOT NULL,
`status` varchar(10) NOT NULL,
PRIMARY KEY (`userid`),
UNIQUE KEY `userid` (`userid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Login/ Register Using Google Open Id in PHP

This summary is not available. Please click here to view the post.

Display User feeds from Twitter in webpage

Though Twitter has lunched API Ver1.1, most of the application developed in older version API will not work, You need to migrate your application to Ver1.1 and which requires Authentication on all endpoints and support JSON only. Lets discuss how to display User feeds from Twitter in you website.

The first thing you need to create an application in twitter and get the following
 - oauth access token
 - oauth access token secret
 - consumer key
 - consumer secret
This you can create in dev.twitter.com, by using your twitter user name and password.

Then you need TwitterAPIExchange.php class file which you can download from here.

Now copy paste the following code to get user Twitter Feeds.
Note: Click here to generate App ID/API Key for Twitter.
 
<?php
include("TwitterAPIExchange.php");

$settings = array(
'oauth_access_token' => "Enter Your Access Token",
'oauth_access_token_secret' => "Enter Your Token Secret",
'consumer_key' => "Enter Your Consumer Key",
'consumer_secret' => "Enter Your Consumer Secret"
);

$url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
$getfield = '?screen_name=a2zwebhelp';
$requestMethod = 'GET';

$twitter = new TwitterAPIExchange($settings);
$response = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();

/* Here you will get all info from user timeline */
var_dump(json_decode($response));
?>
Copy/ paste the following code to display user feeds
<?php
$valid_data = json_decode($response); //JSON data to PHP.
print "<ul>";
  foreach ($valid_data as $key=>$value) {
    print "<li>";
    print $value->text;
    print "</li>";
  }
print "</ul>";
?>

Export Database table to CSV using PHP

Lets write a simple php program to export data from MySql table to CSV file.

PHP Code

<?php

// Database Connection

$host="localhost";
$uname="root";
$pass="";
$database = "database-name"; 

$connection=mysql_connect($host,$uname,$pass); 

echo mysql_error();

//or die("Database Connection Failed");
$selectdb=mysql_select_db($database) or 
die("Database could not be selected"); 
$result=mysql_select_db($database)
or die("database cannot be selected <br>");

// Fetch Record from Database

$output = "";
$table = ""; // Enter Your Table Name 
$sql = mysql_query("select * from $table");
$columns_total = mysql_num_fields($sql);

// Get The Field Name

for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$output .= '"'.$heading.'",';
}
$output .="\n";

// Get Records from the table

while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}

// Download the file

$filename = "myFile.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);

echo $output;
exit;

?>


What is cURL and how to use cURL in PHP

Introduction

cURL stands for client URL

curl is a command line tool for transferring data with URL syntax, supporting DICT, FILE, FTP, FTPS, Gopher, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS, Telnet and TFTP. curl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM, Negotiate, kerberos...), file transfer resume, proxy tunneling and a busload of other useful tricks.

PHP cURL allows you to read websites, make automated logins, upload files and many more.

Requirements

In order to use PHP's cURL functions you need to install the » libcurl package. PHP requires that you use libcurl 7.0.2-beta or higher. In PHP 4.2.3, you will need libcurl version 7.9.0 or higher. From PHP 4.3.0, you will need a libcurl version that's 7.9.8 or higher. PHP 5.0.0 requires a libcurl version 7.10.5 or greater.

Example

Now that you know what cURL is, I think it’s time to look at some code.

<?php
$ch = curl_init ("http://www.yahoo.com");//Initialize curl with the URL of yahoo
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
/*Tell php curl that we want the data returned to us instead of being displayed*/ 
 $yahoo = curl_exec ($ch);//Execute curl and put the output in $yahoo.
?>


The power of PHP cURL lies within the curl_setopt() function. This function instructs cURL of what exactly we want to do. Let’s say, what if a webpage that you want to access checks for the HTTP_REFERER header? Or perhaps, what if you need to access a webpage that works correctly only if cookies are enabled? for more parameters of  curl_setopt() click here .

Here’s another example… This time we specify the HTTP_REFERER…

<?php
$ch = curl_init ("http://www.somedomain.com/page2.php");
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_REFERER, "http://www.somedomain.com/page1.php");
$page = curl_exec ($ch);
?>



In this example, the CURLOPT_REFERER line tells cURL to set the HTTP_REFERER header to http://www.somedomain.com/page1.php.

PHP cURL can do more. It can send POST data, it can log on to a website and automate tasks as if it was a real person and much more.

Tuesday, 24 September 2013

Multiple Like Buttons on a Single Page on multiple images

My last post explained how to put a Like button on a web page. That sets us up nicely to explain how to make different Like buttons for different parts of a page.
For example, imagine you have a page that lists all of your books. You could have a Like button for each of them right below the cover image.

Sound good? Let's get going then.

For the purpose of this post, let's say you have a small-to-medium-sized website. It has a home page, a page about you, a page that lists all your books and stories, and a simple form for contacting you. It's nothing fancy, but it's a start. And it looks good.

  Because you read my last post, you added a Like button to your home page. Now, you want to add a Like button for each of your books, but you've got a problem. The way the Like button works, it uses the entire page. Even though you put a button next to each book, they all seem to Like the entire page. That's not what you want.

It's a tricky problem, but there is a solution.

Step 1) More Pages

Because you have to Like whole pages, that means you need to create a separate page for each book.

Each page should have the book cover image and your hook (1-2 sentences that describe your book). Fill in the Open Graph tags just the way I explained in my previous article. The page can also have blurbs, snippets, buy links, ISBN, etc. The key is that the page is devoted to the book.

Don't forget to include a Like button on this page.

Step 2) Can You Feel the Like?

Go back to your main books page--the one that has all your books and stories. Add Like buttons to each one just like you did before. The code will look something like this:

<!-- AddThis Button BEGIN -->
<div class="addthis_toolbox addthis_default_style ">
<a class="addthis_button_facebook_like" fb:like:layout="button_count"></a>
...
<!-- AddThis Button END -->


Here's the key. In the first div tag, add the following attribute:

<!-- AddThis Button BEGIN -->

<div class="addthis_toolbox addthis_default_style " addthis:url="http://url/to/your/book/page">
<a class="addthis_button_facebook_like" fb:like:layout="button_count"></a>
...
<!-- AddThis Button END -->

That's all there is to it.

Now, when someone uses that Like button, it will like the book page just as if they clicked the Like button on the book page itself.

This will work for anything. Just setup a page for the thing you want Liked. Then create a Like button using the page URL. This button can be used on as many different pages as you want.