Wednesday, September 22, 2010

MRTG with Nagios: New features in PHP 6

MRTG with Nagios: New features in PHP 6

Tuesday, September 21, 2010

send mail with attachment in php

<?php
 $fname = $cust_info['customers_firstname'] ;
 $lname = $cust_info['customers_lastname]'];
 $email = $cust_info['customers_email_address'];
 $address = $cust_info['customers_default_address_id'];
 $phone  = $cust_info['customers_telephone'] ;
 $fax = $cust_info['customers_fax'];
$body = "Name: $fname $lname\nPhone: $phone \nE-mail: $email \nFax: $fax ";
 $to=$_POST['admin_email'];
  $subject="Print Request ".$fame." ".$lname;
$from = $email;
 $mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
       // now we'll build the message headers
      $headers = "From: $from\r\n" .
       "MIME-Version: 1.0\r\n" .
          "Content-Type: multipart/mixed;\r\n" .
          " boundary=\"{$mime_boundary}\"";
       // here, we'll start the message body.
       // this is the text that will be displayed
       // in the e-mail
       $message=$body;
       // next, we'll build the invisible portion of the message body
       // note that we insert two dashes in front of the MIME boundary
       // when we use it
       $message = "This is a multi-part message in MIME format.\n\n" .
          "--{$mime_boundary}\n" .
          "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
          "Content-Transfer-Encoding: 7bit\n\n" .
       $message . "\n\n";
     foreach($_FILES as $userfile)
       {
          // store the file information to variables for easier access
          $tmp_name = $userfile['tmp_name'];
          $type = $userfile['type'];
          $name = $userfile['name'];
          $size = $userfile['size'];
          //echo $tmp_name."\n\n";
          // if the upload succeded, the file will exist
          if (file_exists($tmp_name))
          {
             // check to make sure that it is an uploaded file and not a system file
             if(is_uploaded_file($tmp_name))
             {
                // open the file for a binary read
                $file = fopen($tmp_name,'rb');
                // read the file content into a variable
                $data = fread($file,filesize($tmp_name));
                // close the file
                fclose($file);
                // now we encode it and split it into acceptable length lines
                $data = chunk_split(base64_encode($data));
             }
             // now we'll insert a boundary to indicate we're starting the attachment
             // we have to specify the content type, file name, and disposition as
             // an attachment, then add the file content.
             // NOTE: we don't set another boundary to indicate that the end of the
             // file has been reached here. we only want one boundary between each file
             // we'll add the final one after the loop finishes.
            $message .= "--{$mime_boundary}\n" .
                "Content-Type: {$type};\n" .
                " name=\"{$name}\"\n" .
                "Content-Disposition: attachment;\n" .
                " filename=\"{$fileatt_name}\"\n" .
                "Content-Transfer-Encoding: base64\n\n" .
             $data . "\n\n";
          }
       }
    // here's our closing mime boundary that indicates the last of the message
 /*     $message.="--{$mime_boundary}--\n";
       // now we just send the message
       if (@mail($to, $subject, $message, $headers))
       {
    ?>
<script>
        alert("Mail Sent Successfully.");
     //document.location = "index.php";
       document.prints1.submit();
     </script>
<?php }
  else
   {
   ?>
<script>
     alert("Message Not Sent, Please Try Again.");
      document.location = "index.php";
      </script>
<?
}
*/

Thursday, September 16, 2010

php script to get alexa rank of your website

 <?php
function alexaRank($domain){
    $remote_url = 'http://data.alexa.com/data?cli=10&dat=snbamz&url='.trim($domain);
    $search_for = '<POPULARITY URL';
    if ($handle = @fopen($remote_url, "r")) {
        while (!feof($handle)) {
            $part .= fread($handle, 100);
            $pos = strpos($part, $search_for);
            if ($pos === false)
            continue;
            else
            break;
        }
        $part .= fread($handle, 100);
        fclose($handle);
    }
    $str = explode($search_for, $part);
    $str = array_shift(explode('"/>', $str[1]));
    $str = explode('TEXT="', $str);

    return $str[1];
}
echo alexaRank('www.cyfuture.com');
?>

Wednesday, September 15, 2010

Get all form element through JS

//call the ocg function with inout field action with str = this.form
function ocg(str){
var fname= str.name;
 var elem = str//document.getElementById('str').elements;

 var str1="";
 for(var i = 0; i < elem.length; i++)
 {

 if((elem[i].type=='radio'))
 {
 if(elem[i].checked){
 str1 += elem[i].name;
 str1 +=  elem[i].value ;
 str1 += "##";
  }
  }
  //selected value of select box
if(elem[i].type=='select-one'){
  //str1 +=  elem[i].type ;
  str1 += elem[i].name;
  str1 +=  elem[i].value ;
  str1 += "##";
  }
 }


if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","get.php?q="+escape(str1),true);
xmlhttp.send();
}


place the get.php at right location and print str in it

Tuesday, September 14, 2010

Date and Time handling in PHP/MySQL

Date and time can be inserted into mysql table in specific format only. But php will support different types of date and time formats.

So, we should convert the date and time from php into specific format before inserting the value into mysql table.

We can use the date() and strtotime() functions of the php to do it.

MySQL table will store and datetime correctly only when it is formatted as Y-m-d H:i:s.

(i-e) 4 digit year-2 digit month - 2 digit day blankspace 24hours hour:minute:seconds.

Refer the below sample code used for inserting datetime into mysql table.

- Assume that Date and time values are stored in two different variables($dateinput,$timeinput) in php.
- First we need to concatenate both date and time to get single string.
- Then use strtotime() to convert this single string into time data which can be formatted using date() function to get required format.

$dateinput="02/14/2009";
$timeinput="10:30 pm";
$dt1=date( "Y-m-d H:i:s",strtotime($dateinput. " ".$timeinput));

$sql="insert into test (sttime) values ('$dt1')";
if (mysql_query($sql))
{
echo "successfully inserted";
}
else
{
echo mysql_error();
}

Similary strtotime() can be used to get previous and next days/weeks/months/years also.

For example below code will get the previous 1 week.

$fromDate=date("Y-m-d",strtotime($displayDate."-1 week"));

PHP function to get the ID generated from the previous INSERT operation in mysql

It is necessary to get the ID (auto increment field) of a row inserted into a mysql table if the table is having any parent-child relationship with one or more child tables.

For example, assume that we are entering questions and multiple answers. The questions will be inserted into question table. The id in question table will be used in answer table for relating the question with answers.

So we need to get the id from questions table once after inserting the question.

We can use many different approaches to achieve this.

1. We can have a php variable assigned with current time, this variable value can be stored in question table as hash.
Once after completing the question insertion we can select the id corresponding to this hash from the question table. This approach needs one additional column in the table for storing the hash.

2. We can select the id as "select max(id) from question". This approach will work only when the id is getting incremented continuously.

3.The best way is we can use the php function Mysql_insert_id() to retrieve the ID generated for an AUTO_INCREMENT column by the previous/last INSERT query.

Difference between session_register and $_SESSION[] in php

We can use either session_register or $_SESSION for registering session variable in php.

Find below the difference between both of them.


session_register() is a function and $_SESSION is a superglobal array.

session_register() is used to register a session variable and it works only when register_globals is turned on. (Turning ON register_globals will create mesh-ups, but some applications (e.g OScommerce) requires turning ON of register_globals)
But $_SESSION works even when register_globals is turned off.

If session_start() was not called before session_register() is called, an implicit call to session_start() with no parameters will be made. But $_SESSION requires session_start() before use.

session_register function returns boolean value and $_SESSION returns string value

session_register() function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0.

Monday, September 13, 2010

MVC

Abstract

Model View Controller.
This tutorial will take you from the beginning to the end of building a MVC framework. The object is not soley to produce the finished MVC framework, although that will happen, but to demonstrate how MVC works and some of the concepts that lay behind it..

What is MVC?

MVC is a design pattern. A Design pattern is a code structure that allows for common coding frameworks to be replicated quickly. You might think of a design pattern as a skeleton or framework on which your application will be built.
In the MVC framework that is created in this tutorial, several key points will be raised. The first is the frameworks needs a single point of entry, ie: index.php. This is where all access to the site must be controlled from. To ensure that a single point of entry is maintained, htaccess can be utilized to ensure no other file may be accessed, and that we hide the index.php file in the url. Thus creating SEO and user friendly URL's.
It is beyond the scope of this tutorial to show how to set up htaccess and mod_rewrite and more information on these can be gained from the Apache manual. The .htaccess file itself looks like this.
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?rt=$1 [L,QSA]
The .htaccess file will permit access to the site via urls such as
http://www.example.com/news/show
If you do not have mod_rewrite available, the entry to the site will be the same, except that the URL will contain the values needed such as:
http://www.example.com/index.php?rt=news/show

The Site Structure

In this tutorial several directories are required to hold the various components that make up the MVC framework. The index.php and the .htaccess files will, of course, reside at the top level. We will need a directory to hold the application code, and directories for the model view and controllers. The site structure should look like this:
 html
        application
        controller
        includes
        model
        views
 .htaccess
 index.php

The Index File

As previously mentioned, the index.php file is our single point of access. As such, it provides the ideal space for declaring variables and site wide configurations. It is in this file that we will also call a helper file to initialize a few values. This file will be called init.php and it will be placed in includes directory as shown in the direcory structure. The index file therefore, will begin like this:

<?php

 
/*** error reporting on ***/
 
error_reporting(E_ALL);

 
/*** define the site path constant ***/
 
$site_path realpath(dirname(__FILE__));
 
define ('__SITE_PATH'$site_path);

 
/*** include the init.php file ***/
 
include 'includes/init.php';
?>
The index.php file so far only sets the error reporting, includes the init file, and defines the site path constant. With this file in place, and the .htaccess file we can begin to build the registry. In this MVC framework, the registry object is passed to other objects and contains site wide variables without the the use globals. To create a new registry object, we use the init.php file in the includes directory.
Of course, to create new object we need to include the registry class definition file. During the building of the MVC framework we will be including the application class files directly. Any PHP class definition files which are used by the model will be autoloaded as they can become quite cumbersome with larger applications. To alleviate some of this PHP has the __autoload function to help us out. After the application includes, the __autoload function will immediately follow to load class definition files automatically when they are required by the system. That is, when the new keyword is used. The class definitions will be stored in a directory called model. The includes/init.php file should now look like this.

<?php

 
/*** include the controller class ***/
 
include __SITE_PATH '/application/' 'controller_base.class.php';

 
/*** include the registry class ***/
 
include __SITE_PATH '/application/' 'registry.class.php';

 
/*** include the router class ***/
 
include __SITE_PATH '/application/' 'router.class.php';

 
/*** include the template class ***/
 
include __SITE_PATH '/application/' 'template.class.php';

 
/*** auto load model classes ***/
    
function __autoload($class_name) {
    
$filename strtolower($class_name) . '.class.php';
    
$file __SITE_PATH '/model/' $filename;

    if (
file_exists($file) == false)
    {
        return 
false;
    }
  include (
$file);
}

 
/*** a new registry object ***/
 
$registry = new registry;
?>
Here is should be noted that the autoload function uses a naming convention for the class definition files to be included. They must all follow the convention of ending in .class.php and the class name must be that of the .class.php file name. So that to create a new "news" object the class definition file name must be news.class.php and the class must be named "news". With these files in place we are well on the way, however our MVC does not do anything yet. In fact, if you tried to access the index.php file now, you would get many errors about missing files. Mostly from the files in the application directory. So, lets begin by creating those files each can be blank or simply contain
<?php

?>
The files to create in the application directory are:
  • controller_base.class.php
  • registry.class.php
  • router.class.php
  • template.class.php
Note that although these files are not autoloaded, we have still maintained the same naming convention by calling the files .class.php

The Registry

The registry is an object where site wide variables can be stored without the use of globals. By passing the registry object to the controllers that need them, we avoid pollution of the global namespace and render our variables safe. We need to be able to set registry variables and to get them. The php magic functions __set() and __get() are ideal for this purpose. So, open up the registry.class.php in the applications directory and put the following code in it:

<?php
Class Registry {

 
/*
 * @the vars array
 * @access private
 */
 
private $vars = array();


 
/**
 *
 * @set undefined vars
 *
 * @param string $index
 *
 * @param mixed $value
 *
 * @return void
 *
 */
 
public function __set($index$value)
 {
        
$this->vars[$index] = $value;
 }

 
/**
 *
 * @get variables
 *
 * @param mixed $index
 *
 * @return mixed
 *
 */
 
public function __get($index)
 {
        return 
$this->vars[$index];
 }

}
?>
With the registry in place, our system is working. It does not do anything or display anything, but we have a functional system. The __set() and __get() magic function now allow us to set variables within the registry and store them there. Now to add the Model and router classes.

The Model

The Model is the "M" in MVC. The model is where business logic is stored. Business logic is loosely defined as database connections or connections to data sources, and provides the data to the controller. As I am a fan of CAV (Controller Action View) we will blur the line between the Model and Controller. This is not strictly how MVC should work, but this is PHP baby. Our database connection is a simple singleton design pattern and resides in the classes directory and can be called statically from the controller and set in the registry. Add this code to the init.php file we created earlier.

<?php

 
/*** create the database registry object ***/
 
$registry->db db::getInstance();
?>
Like all registry members, the database is now globally availabe to our scripts. As the class is a singleton we always get the same instance back. Now that registry objects can be created a method of controlling what is loaded is needed.

The Router

The router class is responsible for loading up the correct controller. It does nothing else. The value of the controller comes from the URL. The url will look a like this:
http://www.example.com/index.php?rt=news
or if you have htaccess amd mod_rewrite working like this:
http://www.example.com/news
As you can see, the route is the rt variable with the value of news. To begin the router class a few things need to be set. Now add this code to the router.class.php file in the application directory.


<?php
class router {
 
/*
 * @the registry
 */
 
private $registry;

 
/*
 * @the controller path
 */
 
private $path;

 private 
$args = array();

 public 
$file;

 public 
$controller;

 public 
$action;

 function 
__construct($registry) {
        
$this->registry $registry;
 }
So it does not look like much yet but is enough to get us started. We can load the router into the registry also. Add this code to the index.php file.

 /*** load the router ***/
 $registry->router = new router($registry);
Now that the router class can be loaded, we can continue with the router class by adding a method to set the controller directory path. Add this block of code to the router.class.php file.

<?php
 
/**
 *
 * @set controller directory path
 *
 * @param string $path
 *
 * @return void
 *
 */
 
function setPath($path) {

        
/*** check if path i sa directory ***/
        
if (is_dir($path) == false)
        {
                throw new 
Exception ('Invalid controller path: `' $path '`');
        }
        
/*** set the path ***/
        
$this->path $path;
}
And to set the controller path in the registry is a simple matter of adding this line to the index.php file

 /*** set the path to the controllers directory ***/
 $router->setPath (__SITE_PATH . 'controller');
With the controller path set we can load the controller. We will create a method to called loader() to get the controller and load it. This method will call a getController() method that will decide which controller to load. If a controller is not found then it will default back to the index. The loader method looks like this.

<?php

 
/**
 *
 * @load the controller
 *
 * @access public
 *
 * @return void
 *
 */
 
public function loader()
 {
        
/*** check the route ***/
        
$this->getController();

        
/*** if the file is not there diaf ***/
        
if (is_readable($this->file) == false)
        {
                echo 
$this->file;
                die (
'404 Not Found');
        }

        
/*** include the controller ***/
        
include $this->file;

        
/*** a new controller class instance ***/
        
$class $this->controller 'Controller_';
        
$controller = new $class($this->registry);

        
/*** check if the action is callable ***/
        
if (is_callable(array($controller$this->action)) == false)
        {
                
$action 'index';
        }
        else
        {
                
$action $this->action;
        }
        
/*** run the action ***/
        
$controller->$action();
 }
The getController method that the loader() method calls does the work. By taking the route variables from the url via $_GET['rt'] it is able to check if a contoller was loaded, and if not default to index. It also checks if an action was loaded. An action is a method within the specified controller. If no action has been declared, it defaults to index. Add the getController method to the router.class.php file.

<?php
 
/**
 *
 * @get the controller
 *
 * @access private
 *
 * @return void
 *
 */
private function getController() {

        
/*** get the route from the url ***/
        
$route = (empty($_GET['rt'])) ? '' $_GET['rt'];

        if (empty(
$route))
        {
                
$route 'index';
        }
        else
        {
                
/*** get the parts of the route ***/
                
$parts explode('/'$route);
                
$this->controller $parts[0];
                if(isset( 
$parts[1]))
                {
                        
$this->action $parts[1];
                }
        }

        if (empty(
$this->controller))
        {
                
$this->controller 'index';
        }

        
/*** Get action ***/
        
if (empty($this->action))
        {
                
$this->action 'index';
        }

        
/*** set the file path ***/
        
$this->file $this->path .'/'$this->controller '.php';
}
?>

The Controller

The Contoller is the C in MVC. The base controller is a simple abstract class that defines the structure of all controllers. By including the registry here, the registry is available to all class that extend from the base controller. An index() method has also been included in the base controller which means all controller classes that extend from it must have an index() method themselves. Add this code to the controller.class.php file in the application directory.

<?php
Abstract Class baseController {
/*
 * @registry object
 */
protected $registry;

function 
__construct($registry) {
        
$this->registry $registry;
}
/**
 * @all controllers must contain an index method
 */
abstract function index();
}
?>
Whilst we are in the controller creating mood, we can create an index controller and a blog controller. The index controller is the sytem default and it is from here that the first page is loaded. The blog controller is for an imaginary blog module. When the blog module is specified in the URL
http://www.example.com/blog
then the index method in the blog controller is called. A view method will also be created in the blog controller and when specified in the URL
http://www.example.com/blog/view
then the view method in the blog controller will be loaded. First lets see the index controller. This will reside in the controller directory.

<?php
class indexController extends baseController {

public function 
index() {
    
/*** set a template variable ***/
        
$this->registry->template->welcome 'Welcome to PHPRO MVC';

    
/*** load the index template ***/
        
$this->registry->template->show('index');
}

}
?>
The indexController class above shows that the indexController extends the baseController class, thereby making the registry available to it without the need for global variables. The indexController class also contains the mandatory index() method that ll controllers must have. Within itn index() method a variable named "welcome" is set in the registry. This variable is available to the template when it is loaded via the template->show() method.
The blogController class follows the same format but has has one small addition, a view() method. The view() method is an example of how a method other than the index() method may be called. The view method is loaded via the URL
http://www.example.com/blog/view

<?php
Class blogController Extends baseController {

public function 
index() {
        
$this->registry->template->blog_heading 'This is the blog Index';
        
$this->registry->template->show('blog_index');
}


public function 
view(){

        
/*** should not have to call this here.... FIX ME ***/

        
$this->registry->template->blog_heading 'This is the blog heading';
        
$this->registry->template->blog_content 'This is the blog content';
        
$this->registry->template->show('blog_view');
}

}
?>

The View

The View, as you might have guessed, is the V in MVC. The View contains code that relates to presentation and presentation logic such as templating and caching. In the controller above we saw the show() method. This is the method that calls the view. The major component in the PHPRO MVC is the template class. The template.class.php file contains the class definition. Like the other classes, it has the registry available to it and also contains a __set() method in which template variables may be set and stored.
The show method is the engine room of the view. This is the method that loads up the template itself, and makes the template variables available. Some larger MVC's will implement a template language that adds a further layer of abstraction from PHP. Added layers mean added overhead. Here we stick with the speed of PHP within the template, yet all the logic stays outside. This makes it easy for HTML monkies to create websites without any need to learn PHP or a template language. The template.class.php file looks like this:

<?php
Class Template {
/*
 * @the registry
 * @access private
 */
private $registry;
/*
 * @Variables array
 * @access private
 */
private $vars = array();
/**
 *
 * @constructor
 *
 * @access public
 *
 * @return void
 *
 */
function __construct($registry) {
        
$this->registry $registry;

}


 
/**
 *
 * @set undefined vars
 *
 * @param string $index
 *
 * @param mixed $value
 *
 * @return void
 *
 */
 
public function __set($index$value)
 {
        
$this->vars[$index] = $value;
 }


function 
show($name) {
        
$path __SITE_PATH '/views' '/' $name '.php';

        if (
file_exists($path) == false)
        {
                throw new 
Exception('Template not found in '$path);
                return 
false;
        }

        
// Load variables
        
foreach ($this->vars as $key => $value)
        {
                $
$key $value;
        }

        include (
$path);
}


}
?>

Templates

The templates themselves are basically HTML files with a little PHP embedded. Do not let the separation Nazi's try to tell you that you need to have full seperation of HTML and PHP. Remember, PHP is an embeddable scripting language. This is the sort of task it is designed for and makes an efficient templating language. The template files belong in the views directory. Here is the index.php file.

<h1><?php echo $welcome?></h1>
Well, that was pretty amazing.. Now for the blog_index.php file.

<h1><?php echo $blog_heading?></h1>
And finally the blog_view.php file..

<h1><?php echo $blog_heading?></h1>

<p><?php echo $blog_content?></p>
In the above template files note that the variable names in the templates, match the template variables created in the controller.