Wednesday 26 June 2013

save data from a form app to a cookie and retrieve using php

create cookie.html file and write the following code.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>data storing in cookie</title>
</head>
<body>
<form action="cookieset.php" method="post">
    <p> Name <input type="text" name="astate" size="10px" /></p>  
    <input type="submit" name="submit" value="Submit" />
</form>
<form action="retreive.php" method="get">
    <input type="submit" name="retreive" value="Retreive" />
</form>
</body>
</html>

create cookieset.php file and write the following code for store the data.
<?php
$astate = $_POST['astate'];
$expire=time()+60*60*24*30;
setcookie("astate", $astate, $expire);

?>
write the code in retrieve.php file to retrieve cookie data 
<html>
<body>
<?php
if (isset($_COOKIE["astate"]))
  echo "Welcome " . $_COOKIE["astate"] . "!<br>";
else
  echo "Welcome guest!<br>";
?>
</body>

</html>

Tuesday 25 June 2013

email sending using php credentials in php

I worked around 1 day for sending email using gmail credentials in php,now i am able to send emails.
download phpmailer zip file from this Link .Extract file and keep it XAMPP server within the htdocs folder.before writing code some changes should be requeried  on XAMPP server apache.
setting up ssl on a local xampp/apache server
Apache side
Open the file xampp/apache/conf/httpd.conf in an editor and search for the line
#LoadModule ssl_module modules/mod_ssl.so
remove the hashmark, save the file and re-start the apache.
PHP Side
click on config button on XAMPP then open php.ini file and search for ;extension=php_openssl.dll remove the semicolon, save the file and re-start the apache.
up to now we have configured settings in apache and php side.Let us write the code for mail.
1.create one php file with name of email.php and keep it in phpmailer folder.Write the following code in email.php file.
<?php
if(isset($_POST['btnsubmit'])){
$uname=$_POST["txtemail"];
$pwd=$_POST["txtpassword"];
$sub=$_POST["txtmsg"];
date_default_timezone_set('America/Toronto');
require_once('class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded

$mail             = new PHPMailer();

$body             = $sub;
//$body             = eregi_replace("[\]",'',$body);

$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host       = "ssl://smtp.gmail.com"; // SMTP server
$mail->SMTPDebug  = 1;                     // enables SMTP debug information (for testing)
                                           // 1 = errors and messages
                                           // 2 = messages only
$mail->SMTPAuth   = true;                  // enable SMTP authentication
$mail->SMTPSecure = "ssl";                 // sets the prefix to the servier
$mail->Host       = "smtp.gmail.com";      // sets GMAIL as the SMTP server
$mail->Port       = 465;                   // set the SMTP port for the GMAIL server
$mail->Username   = $uname;  // GMAIL username
$mail->Password   = $pwd;            // GMAIL password

$mail->SetFrom($uname, '');

//$mail->AddReplyTo("user2@gmail.com', 'First Last");

$mail->Subject    = "Feedback from user";

//$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

$mail->MsgHTML($body);

$address = "xxx@gmail.com";  //write emailid to whom you wanted to send mail ex:shankar@gmail.com
$mail->AddAddress($address, "shankar");

//$mail->AddAttachment("images/phpmailer.gif");      // attachment
//$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
} else {
 echo '<script type="text/javascript">alert("Feedback has been sent...");</script>'; 
}
}
?>
<html>
<head>
</head>
<body bgcolor="#F3E2A9">
<form action="email.php" method="POST">
<table align="center">
<tr><td colspan="2"><p style="padding-left:60px;color:blue;font-size:large;font-family:bold;">Feedback Form</p></td></tr>
<tr>
<td>your email address</td>
<td><input type="text" id="txtemail" name="txtemail"/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" id="txtpassword" name="txtpassword"/></td>
</tr>
<tr>
<td>Feedback</td>
<td><textarea id="txtmsg" name="txtmsg" cols="32" rows="7"></textarea></td>
</tr>
<tr>
<td><button id="btnsubmit" name="btnsubmit" style="float:right;height: 30px;width: 90px;color:#0020C2;">submit</button></td>
<td><button id="btnCancel" name="btnCancel" style="height: 30px;width: 90px; color:#0020C2;">Cancel</button></td>
</tr>
</table>
</form>
</body>
</html>
I hope this will be helpful for sending email using gmail account credentials.

Wednesday 12 June 2013

php frameworks


  1. CodeIgniter
  2. CakePHP
  3.  Symfony
  4. Prado
  5. Qcodo
  6.  Zend Framework
  7. Akelos
  8. Maintainable
  9. evoCore
  10. Stratos
  11. Seagull
  12. Zoop
  13.  php.MVC
  14. AjaxAc
  15. xAjax
  16. PHOCOA
  17. Kohana
  18. Limb
  19. Solar
  20. BlueShoes
  •  CodeIgniter :CodeIgniter is a powerful PHP framework with a very small footprint, built for PHP coders who need a simple and elegant toolkit to create full-featured web applications.read more..
  • Cakephp : Cakephp is a rapid development framework for PHP that provides an extensible architecture for developing, maintaining, and deploying applications.read more..
  • Symfony :Symfony is a full-stack framework, a library of cohesive classes written in PHP5. It provides an architecture, components and tools for developers to build complex web applications faster. Choosing symfony allows you to release your applications earlier, host and scale them without problem, and maintain them over time with no surprise.read more..
  •  Zend Framework :Zend Framework is focused on building more secure, reliable, and modern Web 2.0 applications & web services, and consuming widely available APIs from leading vendors like Google, Amazon, Yahoo!, Flickr, as well as API providers and catalogers like StrikeIron and ProgrammableWeb.read more..

Tuesday 11 June 2013

display excel worksheet details in php page using fgetcsv() Function

convert an existing Excel file into a .csv format and keep it in one folder. Write the following code in demo.php page.

<?php
if (($handle = fopen("EmpDetails.csv", "r")) !== FALSE) {
echo"<table border=\"1\"cellspacing=\"0\">";
$row = 1;
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
echo"<tr>";
        for ($c=0; $c < $num; $c++) {
echo"<td>";
            echo$data[$c];
echo"</td>";
        }
echo"</tr>";
$row++;
    }
echo"</table>";
    fclose($handle);
}
?>

Thursday 6 June 2013

MVC in PHP

Program flow

  • The model, view and controller are initialized
  • The view is displayed to the user, reading data from the model
  • The user interacts with the view (e.g. presses a button) which calls a specified controller action
  • The controller updates the model in some way
  • The view is refreshed (fetching the updated data from the model)


<?php
class Model {
    public $text;
   
    public function __construct() {
        $this->text = 'Hello world!';
    }        
}

class View {
    private $model;
    private $controller;
   
    public function __construct(Controller $controller, Model $model) {
        $this->controller = $controller;
        $this->model = $model;
    }
   
    public function output() {
        return '<a href="helloworld.php?action=textclicked">' . $this->model->text . '</a>';
    }    
}

class Controller {
    private $model;

    public function __construct(Model $model) {
        $this->model = $model;
    }

    public function textClicked() {
        $this->model->text = 'Text Updated';
    }
}

$model = new Model();
//It is important that the controller and the view share the model 
$controller = new Controller($model);
$view = new View($controller, $model);
if (isset($_GET['action'])) $controller->{$_GET['action']}();
echo $view->output();

?>

Tuesday 4 June 2013

php coding standards

1. Indenting and Line Lengths
·         Use indent of four spaces, no tab spaces(set tab size = 4 spaces)
·         It is recommended to keep lines at approximately 75-80 characters long for better code readability.

2. Control Structures
·         If , for, while , switch comes under control structure
·         <?php
if ((condition1) || (condition2)) {
    action1;
} elseif ((condition3) && (condition4)) {
    action2;
} else {
    defaultaction;
}
?>
·         Control statements should have one space between the control keyword and opening parenthesis, to distinguish them from function calls.
·         Split long if statements onto several lines
<?php
if (($condition1
    || $condition2)
    && $condition3
    && $condition4
) {    //code here}?>
·         Ternary operators
The same rule as for if clauses also applies for the ternary operator.
<?php
$a = $condition1 && $condition2
    ? $foo : $bar;
?>

3.Function Calls
·         Functions should be called with no spaces between the function name, the opening parenthesis, and the first parameter; spaces between commas and each parameter, and no space between the last parameter, the closing parenthesis, and the semicolon.

<?php
$var = helloworld($bar, $baz, $quux);
?>
·         Split function call on several lines

The CS require lines to have a maximum length of 80 chars. Calling functions or methods with many parameters while adhering to CS is impossible in that cases. It is allowed to split parameters in function calls onto several lines.

·         Alignment of assignments

To support readability, the equal signs may be aligned in block-related assignments
<?php
$var1  = foo($bar);
$var2 = foo($baz);
?>
Note : The rule can be broken when the length of the variable name is at least 8 characters longer/shorter than the previous one

·         Split long assignments onto several lines

Assignments may be split onto several lines when the character/line limit would be exceeded. The equal sign has to be positioned onto the following line, and indented by 4 characters.
4. Class Definition
·         Class declarations have their opening brace on a new line.
<?php
class Foo_Bar
{
    //... code goes here
}
?> 

5. Function Definitions
·         Function declarations follow the "K&R style":
<?php
function fooFunction($arg1, $arg2 = '')
{
    if (condition) {
        statement;
    }
    return $val;
}
?>
           
·         Split function definitions onto several lines
1.     Functions with many parameters may need to be split onto several lines to keep the 80 characters/line limit.
2.     The first parameters may be put onto the same line as the function name if there is enough space. 
3.      Subsequent parameters on following lines are to be indented 4 spaces.
4.     The closing parenthesis and the opening brace are to be put onto the next line, on the same indentation level as the "function" keyword.
5.     <?php
function someFunctionWithAVeryLongName($firstParameter ='something', $secondParameter = 'booooo',
    $third = null, $fourthParameter = false, $fifthParameter = 123.12,
    $sixthParam = true
) {
    //....
?>

6. Arrays
·         Assignments in arrays may be aligned. When splitting array definitions onto several lines, the last value may also have a trailing comma. This is valid PHP syntax and helps to keep code diffs minimal

<?php
$some_array = array(
    'foo'  => 'bar',
    'spam' => 'ham',
);
?>

7.Comments
·         Complete inline documentation comment blocks (docblocks) must be provided.
1.     C style comments (/* */) 
2.     standard C++ comments (//)     both are fine.

8.PHP Code Tags
·         Always use <?php ?> to delimit PHP code, not the <? ?> shorthand. This is required for PEAR compliance and is also the most portable way to include PHP code on differing operating systems and setups.

9. Examples URLs
·         Use example.com, example.org and example.net for all example URLs and email addresses

10.Naming Conventions
·         Global Variables and Functions
1.    If your package needs to define global variables, their names should start with a single underscore followed by the package name and another underscore.
$_XML_destructor_object_list
2.    Global functions should be named using the "studly caps" style (also referred to as "bumpy case" or "camel caps"). 
XML_RPC_serializeData ()
·         Classes
Classes should be given descriptive names. Avoid using abbreviations where possible. Class names should always begin with an uppercase letter. The PEAR class hierarchy is also reflected in the class name, each level of the hierarchy separated with a single underscore. Examples of good class names are
Log                         Net_Finger                               HTML_Upload_Error
·         Class Variables and Methods
Class variables (a.k.a properties) and methods should be named using the "studly caps" style (also referred to as "bumpy case" or "camel caps"). Some examples (these would be "public" members)


$counter         connect()              getData()

Monday 3 June 2013

Java Script References(properties and methods)

Here are some properties and methods. 

JS Array
·        Length
·        Prototype
Array methods
  •        Concat()  --    concatenate more than two array information

Var x=[“shankar”,”parsanamoni”];
Var y=[“vikas”,”bodla”];
Var z=[”sai”,”srinivas”];
Var name=x.concat(y,z);
  •       indexOf() --    Searches the array for the specified item, and returns its position

var fts=new array[“shankar”,”srinivas”,”dinesh”];
var a=fts.indexOf(“dinesh”);

·         join()       --     this method is used to join all all array values.
            Var x=[“shankar”,”vikas”,”Mahesh”];
            Var result.innerHTML=x. Join ();

·         pop()      --     remove the last element of an array.
            Var y=[“shankar”,”parsanamoni”,”mudiraj”];
Var x.innerHTML=y.pop();

·         Push ()    --     adds new items to the end of an array, and returns the new length.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi")

·         Reverse() --    Reverse the order of an array
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits. Reverse();

·         Shift()       --    Removes the first element of an array and returns it.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift()

output: Orange,Apple,Mango.
·         Sort()     --   sort the items of an array
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();

·         toString()--   converts an array to string and returns it.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.toString();

·         Unshift ()   --   adds new items to the beginning of an array, and returns the new length.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon","Pineapple");
Output : Lemon,Pineapple,Banana,Orange,Apple,Mango

·         valueOf ()   --   Returns the primitive value of an array.

JS Boolean
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false).

·         toString()   --  Converts a Boolean value to a string, and returns the result
var bool = new Boolean(1);
var myvar = bool.toString();
result is :true

·         valueOf()   --   Returns the primitive of value of Boolean object
var bool = new Boolean(0);
var myvar = bool.valueOf();
result is : false

JS Date

                             The date object is used to work with date and time
                             Date object is created with new date()
                             There are four ways to instantiate date.
1.    var d=new date();
2.    var d=new date(milliseconds);
3.    var d=new date(date String);

getDate()           --   Returns the day of the month
                             var d=new Date();
                             var n=d.getDate();
js Math
                                                The Math object allows you to perform mathematical tasks
Js Number
The Number object is an object wrapper for primitive numeric values.Number objects are created with new Number ().

Js String                     the String object is used to manipulate a stored piece of text. String objects are created with new String ().

Length                  --    specifies the length of the string
                                    Var txt=”Hello World !”;
                                    Document.write(txt.length);

charAt()                 --    returns the character at the specified index
                                    var str=”Hello World”;
                                    var n=str.charAt(3);
                                    o/p : l

charCodeAt()        --     returns the character Unicode at the specified index.
                                    Var str=”Hello World”;
                                    Var n=str.charCodeAt(0);
                                    o/p : 72

concat()                --    concat the two strings and return concatenated string value
                                   var x=”shankar”;
                                   var y=”parsanamoni”;
                                   var z=x.concat(y);
                                   o/p : shankar parsanamoni

replace()               --   replace the value
                                  var x=”visit Microsoft”;
                                  var n=x.replace(“Microsoft”,”himansuit”);

slice()                    --  Extract part of a string and returns new result
                                  var n=”Hello Shankar”;
                                  var m=n.slice(0,3);
                                  o/p : Hel

split()                    --  Splits a string into an array of substrings
                                  string.split(separator,limit);
                                  var x=”Hello how are you?”;
                                  x.split(“ “);

                                  use the limit parameter

          var str="How are you doing today?";
        var n=str.split(" ",3);
        o/p : How are you
      
          use letter as a separator
     
        var str=”How are you doing todat?”;
        str.split(“o”);
        o/p : H,w are y,u d,ing t,dat?

Substr()           --  string.substr(start, length)
                           Var x=”Hello World”;
                           Var y=x.substr(1,4)
                           o/p : ello

substring()       --   Extracts the characters from a string, between two specified indices
                                  string.subString(from,to)
                                  var x=”Hello shankar how are you”;
                                  var y=x.subString(0,3)
                                  0/p : Hel

toLowerCase()    --    var x=”Hello Shankar”;
                                  var y=x.toLowerCase(x);

toUpperCase()    --    var x=”Hello World”;
                                  var y=x.toUpperCase(x);

                                  String HTML wrapper methods

Big()                    --   The big() method is used to display a string in a big font.
                                 String.big();
         var str = "Hello world!";
       document.write(str.big());

blink()             --  The blink() method is used to display a blinking string.
                                 Var str=”Hello Shankar”;

                                 Document.write(str.blink());