Saturday, 10 December 2011

PHP ssh2_connect() not working?

Most of the times we use ssh2_connect() function to connect and download files from remote server without using ftp. Sometimes it doesn't work. Please note some useful tips:

1) Make ensure that openssl is enabled and libssh2 is installed on your server.

2) Even after that when calling ssh2_connect() function if you are getting errors like following:

[Sat Dec 03 19:30:35 2011] [error] [client 172.16.xxx.xx] PHP Warning: ssh2_connect(): Unable to connect to 172.18.xx.xxx on port 22 in /var/www/html/connection.php on line 9
[Sat Dec 03 19:30:35 2011] [error] [client 172.16.xxx.xx] PHP Warning: ssh2_connect(): Unable to connect to 172.18.xx.xxx in /var/www/html/connection.php on line 9

It means apache is not allowed to send packets using tcp.

Then run the following command from your server console:

//Allow HTTPD scripts and modules to connect to the network using any TCP port.

# setsebool -P httpd_can_network_connect 1

here P stands for permanent.

Sometimes the above command doesn't work. Then for temporary solution use this one..

# setsebool httpd_can_network_connect 1

It would work like charm :)





Sunday, 4 December 2011

PHP redirection through header() function not working?

header("Location: http://dirtyhandsphp.blogspot.com/");

While using header function sometimes you got the error like: 'Cannot add/modify header information – headers already sent by…' 

To avoid such situation you can use output buffering or just make sure that nothing was sent to the client. 

Remember also that headers MUST be sent before any output is started. There are no exceptions from this rule, in fact you cannot even sent a blank line to the output, executing code like this:

echo ""; 


Saturday, 3 December 2011

How to write PDF file in PHP?

PHP is a dynamic web development language with some surprising capabilities. It can even create PDF documents on the fly, if right third party library is available. Here in this post we are using FPDF library. You can download the same from here. Following is the example how you can write a simple pdf file using this library:

"pdf.php"

<?php

    //Connection to the database
    $link = mysql_connect("localhost","root","");
    if (!$link) {
        die('Could not connect: ' . mysql_error());
    }
    mysql_select_db("practice");
    //end of database connection code

    require('fpdf.php');

    $pdf=new FPDF();
    $pdf->AddPage();

    $pdf->SetFont('Arial','B',10);

    $pdf->Cell(50,3,"Learn how to write PDF Files in PHP");
    $pdf->Ln();
    $pdf->Ln();

    $pdf->SetFont('Arial','',6);
    $text = "As a PHP programmer on any day you may need to write PDF file using PHP at run time. Here i have just tried to include each and everything required to write pdf file. Please go through the following blog link.";
    $pdf->Write(5,$text);
     /* While you are using text we would recommend to use this function only because This method prints text from the current position. When the right margin is reached (or the \n character is met) a line break occurs and text continues from the left margin. Upon method exit, the current position is left just at the end of the text. */

    $pdf->Ln();

    $link = "http://dirtyhandsphp.blogspot.com/";
    $pdf->SetTextColor(0,136,60); //set color of the text using R,G,B combination
    $pdf->Write(5,$link,$link);
    $pdf->Ln();

    $pdf->SetTextColor(0,0,0);
    $pdf->Cell(10,5,"User Id");
    $pdf->Cell(350,5,"Username");
    $pdf->Ln();
    $pdf->SetFont('Arial','',6);
        $pdf->Cell(450,3,"-------------------------------------------------------------------------------------");

    $pdf->Ln();
    //Get data from table.
    $result=mysql_query("select * from users order by user_id");
    while($row=mysql_fetch_array($result))
    {
        $pdf->Cell(10,5,"{$row['user_id']}");
        $pdf->MultiCell(350,5,"{$row['user_name']}");
    }
   
    $pdf->Ln();
    $pdf->Image('images/php.jpg', 50, 50, 55, 35, 'JPG'); // inserts the image
    $pdf->Output("shiv.pdf","F"); // It would automatically call $pdf->Close();

?>



Download the library and check more commands you can use to create an effective pdf as per the requirements.


Thanks!!!!!!!!!! Enjoy Programming :)

Sunday, 27 November 2011

CakePHP url rewriting problem?

If you are facing url rewriting problem in cakephp even though you have enabled rewrite module.....Here is the solution....



- Just go to the httpd.conf file.

- Find the following text groups

  <Directory />
       Options FollowSymLinks
       AllowOverride None
       Order deny,allow
       Deny from all
  </Directory>

and

  # AllowOverride controls what directives may be placed in .htaccess files.
  # It can be "All", "None", or any combination of the keywords:
 # Options FileInfo AuthConfig Limit
 AllowOverride None.

- Replace 'AllowOverride None' with 'AllowOverride All' on both places.

- Save file and Restart Apache

Refresh Page and the problem is resolved. :)

Saturday, 26 November 2011

SMS Gateway Integration in PHP

To Integrate SMS Gateway in PHP you have to signup for an account with SMS service providers. To find any one out of them just google for it and you will get a list of providers.

All of them are paid service providers and some of them provide you just few free credits so that you can test their service.

Following is the example of such a provider http://www.clickatell.com/

After logged in it provides us an API that we would have to use for sending sms.

You can connect to the gateway using HTTP/s, SMPP, SMTP, FTP, XML, SOAP etc...

I have opted for HTTP/s

Following are the step to connect via HTTP:

    1) When you sign up for an HTTP/S account, you will be given a username, password and api_id: keep these at hand!

    2) Once your registration has been activated you will receive 10 free credits with which to test our service.

    3) Have the number you wish to send to ready in international format e.g. 448311234567.

    4)Open your browser (e.g. Internet Explorer), and type in your info in the address bar in the following sequence:
        http://api.clickatell.com/http/sendmsg?user=xxxxx&amp;password=xxxxx&amp;api_id=xxxxx&
        amp;to=448311234567&amp;text=Meet+me+at+home
 
      Press 'Enter' on your keyboard and your message will be sent.

                                                or

      In PHP you can use Curl and HttpRequest class to make HTTP requests. For example in curl you can do that as following.

<?php 

   $url = "http://api.clickatell.com/http/sendmsg?user=xxxxx&amp;password=xxxxx&amp;api_id=xxxxx&amp;to=448311234567&amp;text=Meet+me+at+home"; 
   $ch = curl_init(); 
   curl_setopt($ch, CURLOPT_URL, $url); 
   curl_setopt($ch, CURLOPT_HEADER, TRUE); 
   curl_setopt($ch, CURLOPT_NOBODY, TRUE); // remove body 
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
   $head = curl_exec($ch); 
   $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
   curl_close($ch);

   if($httpCode == 200)
           echo "Message Sent Successfully"; 
   else 
           echo "There is some problem"; 
   die; 

?>

     The text of your message must be formatted so that '+' signs replace spaces between words as above.

Sunday, 20 November 2011

How to access remote server using PHP SSH?

To remotely access a server in PHP provides a full library of functions called SSH2 functions. You can get the manual from the link. You'll get most of the information from the manual itself but it also leaves the user with some questions which are unanswered. Here i am just trying to explain the same in some better way..

Simple Example : 

<?php
    if (!function_exists("ssh2_connect"))
        die("function ssh2_connect doesn't exist");
    if(!($con = ssh2_connect("www.example.com", 22(port number)))){
        echo "fail: unable to establish connection\n";
    } else {
        if(!ssh2_auth_password($con, "username", "password")) {
            echo "fail: unable to authenticate\n";
        } else {
            echo "okay: root logged in...\n";
            $stream = shell_exec("mkdir /var/www/shiv");
        }
    }

?>

Important Notes :

1) If you are logged in as a normal user(not root user) then you can't change user and login to the root or super user using these function. You can use su as a command but can't enter password as a command because server only allow the user to enter password through standard input device. For example if you are trying like this:

$stream = shell_exec("su; superuser password");

then it won't work.

2) If you want to run multiple commands then you have to use single shell_exec() function for that. For example :

$stream = shell_exec("mkdir /var/www/shiv; mkdir /var/www/modi");

It would create two sub-directories named 'shiv' and 'modi' in /var/www/ directory.


while


$stream = shell_exec("mkdir /var/www/shiv");
$stream = shell_exec("mkdir /var/www/modi");

commands won't work, because command n shell environment will not be remembered during the execution of command n+1.If you want the shell commands to be working while depending on each other in terms of environment, you should put several commands in a unique ssh2_exec().


Now you can run any number of commands on remote server. You can also use ssh php function to download, upload files etc....

Saturday, 19 November 2011

CakePHP-MultivalidatableBehavior: Using many validation rulesets per model.

If you are looking for action specific validation on a model then here it goes like that :

Following code examples are based on the following scenario:

1) We have a model Member.

2) We wanna two type of validation sets on that.

     a) First in case of Login (default)
     b) Second in case editing Profile. 

3) How to use these validation sets in action.


Step 1 :
<?php 
    class MultivalidatableBehavior extends ModelBehavior {

    /**
     * Stores previous validation ruleset
     *
     * @var Array
     */
    var $__oldRules = array();

    /**
     * Stores Model default validation ruleset
     *
     * @var unknown_type
     */
    var $__defaultRules = array();

    function setUp(&$model, $config = array()) {
        $this->__defaultRules[$model->name] = $model->validate;
    }

    /**
     * Installs a new validation ruleset
     *
     * If $rules is an array, it will be set as current validation ruleset,
     * otherwise it will look into Model::validationSets[$rules] for the ruleset to install
     *
     * @param Object $model
     * @param Mixed $rules
     */
    function setValidation(&$model, $rules = array()) {
      
        if (is_array($rules)){
            $this->_setValidation($model, $rules);
        } elseif (isset($model->validationSets[$rules])) {
            $this->setValidation($model, $model->validationSets[$rules]);
        }
    }

    /**
     * Restores previous validation ruleset
     *
     * @param Object $model
     */
    function restoreValidation(&$model) {
        $model->validate = $this->__oldRules[$model->name];
    }

    /**
     * Restores default validation ruleset
     *
     * @param Object $model
     */
    function restoreDefaultValidation(&$model) {
        $model->validate = $this->__defaultRules[$model->name];
    }

    /**
     * Sets a new validation ruleset, saving the previous
     *
     * @param Object $model
     * @param Array $rules
     */
    function _setValidation(&$model, $rules) {
            $this->__oldRules[$model->name] = $model->validate;
            $model->validate = $rules;
    }

}

?> 

Save the file as \app\models\behaviors\multivalidatable.php

Step 2 : 

Go to Member model and make the following changes.

<?php

    class Member extends AppModel{
           
        var $primaryKey = 'member_id';
        var $actsAs     = array('Multivalidatable');
       
        var $validate   = array(
            'username'    =>    array(
                'notEmpty' => array(
                    'rule' => 'notEmpty',
                    'required' => true,
                    'message'  => 'Username/Email is Required',
                    'last' => true
                ),
                'email'    =>    array(
                    'rule' => 'email',
                    'message'=> 'Please provide valide username',
                    'last' => true
                )
            ),
            'password'    =>    array(
                    'rule' => 'notEmpty',
                    'message'=> 'Password is Required',
                    'last' => true
            )           
        );
       
        var $validationSets = array(
            'member_detail' => array(
                'first_name' =>    array(
                    'notEmpty' => array(
                        'rule' => 'notEmpty',
                        'required' => true,
                        'message'  => 'First Name is Required',
                        'last' => true
                    )
                ),
                'last_name' =>    array(
                    'notEmpty' => array(
                        'rule' => 'notEmpty',
                        'required' => true,
                        'message'  => 'Last Name is Required',
                        'last' => true
                    )
                ),
                'email'    =>    array(
                    'notEmpty' => array(
                        'rule' => 'notEmpty',
                        'required' => true,
                        'message'  => 'Email is Required',
                        'last' => true
                    ),
                    'email' =>    array(
                        'rule' => 'email',
                        'message' => 'Please provide valid email',
                        'last' => true
                    )
                )
            )
        );
    }



?> 

Step 3:

Go to the Members controller or to the controller actions where you want to validate a particular validate set. For example

<?php

  class MemberController extends AppController {

        var $name             = 'Member';
        var $helpers          = array('Html','Session','Javascript','Ajax');
        var $components  = array('Session','RequestHandler');
        var $uses             = array('Member');
              
        function beforeFilter() {
            $this->__validateLoginStatus();
        }

        ...............................................
       ....................................................

        function login() {
           
            if($this->Session->check('Member') === true) {
                $this->redirect('/member/index');
                exit;
            } else {
                if($this->params['form']) {
                    $this->Member->set($this->params['form']);
                   
                    if($this->Member->validates($this->params['form'])) { //here the default set would work
                   
                                   ...................................................
                                  ...................................................
                                                       
                    } else {
                        if($this->Member->validationErrors)
                            $this->errors = $this->Member->validationErrors;
                    }
                }
            }
            $this->set('errors',$this->errors);
            $this->set('notifications',$this->notifications);
            $this->set('form',$this->params['form']);
               
       }

       ........................................................................
       ........................................................................

      function edit($member_id) {
           
            $member= array();
            if($member_id) {
               
                if($this->params['form']) {
                   
                    ..........................................
                    ..........................................  
               
                    $this->Member->setValidation('member_detail'); // here it will use member_detail set for validation
                   
                    if($this->Member->validates()) {
                        $this->Member->save();
                        $this->Session->setFlash("Record updated successfully.");
                    } else
                        $this->errors = $this->Member->invalidFields();
                   
                }
            }

            $this->set('member',$member);
            $this->set('errors',$this->errors);
        }
 
       ........................................................................
       ........................................................................

  }

?>

So when you will call the edit action while saving profile details the 'member_detail' validation set would be called.

Here it's done...Enjoy!!!!!!!!!!!!


Sunday, 13 November 2011

Automatic Startup of Apache on Linux Server?

To start Apache automatically, follow these steps:
  • Copy Apache startup file to the startup directory:
cp /usr/local/apache/bin/apachectl /etc/init.d/

            In my case ‘apachectl’  was at location /usr/sbin/apachectl so I have used

            cp /usr/sbin/apachectl /etc/init.d/

  •  Edit /etc/init.d/apachectl by inserting these 2 lines in bold:
          
      #!/bin/sh
      #
      # chkconfig: - 345 85 15
      # description: Apache is a Web server used to serve HTML files and CGI.
      #
      # Copyright 2000-2005 The Apache Software Foundation or its licensors, as
      # applicable.
        . . .
      # Apache control script designed to allow an easy command line interface
      # to controlling Apache.  Written by Marc Slemko, 1997/08/23
      . . .

  • Enable httpd to startup automatically: 
          # chkconfig –-add httpd

  • To start mysql on startup too, use:
         # chkconfig –-add mysqld

  • Reboot Linux to verify Apache starts.

Saturday, 12 November 2011

How to Authenticate Users With Twitter OAuth ?

Best tutorial is available here.

Going through that tutorial you will learn

1) How to create twitter application.

2) How to get oauth_token, oauth_token_secret, user_id and screen_name of the authorized user.

3) How to update status using twitter API.

Sunday, 6 November 2011

Installing GUI under CentOS 6

If you installed using a text login and wish to switch to a graphical login, follow this procedure.

1) If you are not already root, switch users to the root account:

su -

Provide the administrator password when prompted.

2) If you have not already done so, install the X Window System and a graphical desktop environment. For example, to install the GNOME desktop environment, use this command:

yum groupinstall "X Window System" Desktop

To install the KDE desktop environment, use:

yum groupinstall "X Window System" "KDE Desktop"

This step may take some time as your Linux system downloads and installs additional software. You may be asked to provide the installation media depending on your original installation source.

3) Run the following command to edit the /etc/inittab file:

vi /etc/inittab

4) Press the 'i' key to enter insert mode.

5) Find the line that includes the text initdefault.

To change from a console to a graphical login, you should change the number in the line id:3:initdefault: from a 3 to a 5.

6) Type :wq and press the Enter key to save the file and exit the vi text editor.

If you want to go in graphical environment before restarting the server. Just type

#yum startx

Otherwise, Reboot the system using the reboot command. Your system will restart and present a graphical login.

Saturday, 5 November 2011

How to install Linux – CentOS 6 for Servers & Desktops

1) Set your computers BIOS to boot form CD / DVD

2) Insert the CentOS 6 CD or DVD

3) When presented with the following screen press enter on Install or upgrade an existing system.



4) You will now be presented with a CD Check, I always skip this step… I live life on the edge when it comes to media checking on Linux installs. However you might want to check the media.


5) You will now see some black and white text on your screen as your computer loads the X11 environment for the CentOS install, after 30 seconds or so you will be presented with the CentOS GUI installer, click next.


6) Select your Language, I am British (please no jokes about drinking tea on Twitter…) so I would select English (English).


7) Select your keyboard type


8) Storage type, as I am installing on my local hard drive I selected “Basic storage type” if you are using iSCSI or similar technology now would be the time to set it up.


9) As this is a clean install and the drive has never been formatted before I got the following Initialize drive warning, you might get the same if your drive (or virtual hard disk) is brand new.


10) Set the hostname for your Server


11) Set your timezone / location


12) Set your root password, something sensible please… Don’t set weak dictionary passwords or you will get hacked by a 13yr old russian super hackz0r… You might want to check out my guide on how to secure SSH.


13) You will now be set with a bunch of options for your disk partitioning, as this is a new fresh install I selected the top option “Use All Space” chose the relevant option for your setup and tick the review and modify partition layout.


14) You will now see your partition table laid out, now is the time to modify it if required. If this is a server I would suggest you create some different partitions for /home and /var. These are the two partitions that crash Linux servers, /home because users fill their home drives and causes the system to crash and /var because the log or ftp directories fill up and crash the server.


15) Format warning, click on Format (this will delete your data).


16) You will now see a warning about writing the changes to disk, click on Write changes to disk.


17) Boot loader options, I left this as default you might want to set a boot loader password.


18) The next part is important, for servers I ALWAYS select minimal, this installs a minimal setup which is ideal for servers, if you are installing for a desktop you might want to chose one of the other options. I would avoid the chose everything option as this will create a bloated system that will be more susceptible to hackers.


19) CentOS 6 will install


20) CentOS 6 has installed, congrats


21) Reboot and login as root


22) Update the system using “yum update”


Sometimes yum update doesn't work and we get error of following type

[root@centos-box ~]# yum update Loaded plugins: fastestmirror, refresh-packagekit Determining fastest mirrors Could not retrieve mirrorlist http://mirrorlist.centos.org/?release=6&arch=i386&repo=os error was 14: PYCURL ERROR 6 - "" Error: Cannot find a valid baseurl for repo: base

In this case you have to do the following:
Manually edit /etc/sysconfig/network-scripts/ifcfg-eth0 to get networking up:

[root@centos-box ~]# vi /etc/sysconfig/network-scripts/ifcfg-eth0

BOOTPROTO=dhcp
NM_CONTROLLED=no
ON_BOOT=yes

Save the file and reboot the server.

That’s it your done! Go forth and setup your server for what ever services you require, Asterisk, LAMP etc.

Sunday, 30 October 2011

PHP Reference Sheet (Basics)


Data Types
integer, float, boolean, string, array, object, resource, NULL

Variable Declarations
$variablename = <value>;
$anothervariable =& $variablename; (Assign by Reference)

Declare Array
$arrayname = array();

Initialize Array
$arrayname = array(<value1>, <value2>, <value3>);
$arrayname = array(<key> => <value>, <key> => <value>); (Define Keys)
$multiarray = array(<key> => array(<value1>,<value2>)); (Multi-dimensional)

Common Array Functions
sort(<array>); (Sort array assigns new keys)
asort(<array>); (Sort array maintain keys)
rsort(<array>); (Sort array in reverse, new keys)
arsort(<array>); (Sort array in reverse, maintain keys)
count(<array>); (Count elements)
count(<array>,COUNT_RECURSIVE); (Count multidimensional array)
array_push(<array>,<value>); (Push item onto end of array)
array_pop(<array>); (Pop item off end of array)

Comments
// Comment text
/* Multi-line comment text */
# Comment text

Arithmetic Operators
+ (Addition), - (Subtraction), * (Multiplication), / (Division), % (Modulus)

Relational Operators
== (Equal), === (Equal with type comparison), != (Not equal), <> (Not equal), !== (Not Equal with type comparison), < (Less than), > (Greater than), <= (Less than or equal to), >= (Greater than or equal to)

Logical Operators
! (logical NOT), && (logical AND), || (logical OR), xor (logical XOR)

Assignment Operators
= (Assign), += (Addition), -= (Subtraction), *= (Multiplication), /= (Division), .=
(Concatenation), %= (Modulus), &= (And), |= (Or), ^= (Exclusive Or), <<= (Left Shift), >>=(Right Shift)

String Concatenation
. (Period)


String Manipulation
substr(<string>,<start>,[<length>]);
strlen(<string>);
trim(<string>);
ltrim(<string>); // Trim left
rtrim(<string>); // Trim right
strtolower(<string>);
strtoupper(<string>);
str_replace(<search>,<replace>,<string>,[<count>]);
strpos(<string>, <search>);
strcmp(<string1>,<string2>); (Binary safe string comparison)
strcasecmp(<string1>,<string2>); (Binary safe case-insensitive comparison)
explode(<delim>,<string>,[<limit>]); (Break string into array)
implode(<delim>,<array>); (Join array into string separated by delim)

Cookies
setcookie (<cookiename>, [<value>],[<expire_time_in_secs_since_epoch>]);
$_COOKIE['cookiename']; (Returns value of cookie)

Sessions
session_start(); (Create session)
$_SESSION['key_name'] = value; (Set session variable)
$variablename = $_SESSION['key_name']; (Retrieve value from session variable)
session_destroy(); (Destroy session)

Error Handling
try {
<statements that may cause error>;
}
catch (<Exception Class> $exception_name)
{
<statements to execute when error is caught>;
}

Super Globals
$GLOBALS (Access all global variables in script)
$_SERVER (Access web server variables)
$_GET (Values passed to script through URL)
$_POST (Values passed to script through HTTP Post)
$_COOKIE (Values passed by user cookie)
$_FILES (Values passed by HTTP Post File Uploads)
$_ENV (Values passed to script via the environment)
$_REQUEST (Values passed by URL, HTTP Post, or user Cookies)
$_SESSION (Values passed through user's session)

If Else
if (<condition 1>)
{ <statement 1>; }
elseif (<condition 2>)
{ <statement 2>; }
else
{ <statement 3>; }

Inline If (Ternary)
<condition> ? true : false;

For Loop
for (<initialize>;<condition>;<update>)
{
<statements>;
}

For Each Loop
foreach (<array> as [<value> |<key> => <value>])
{
<statements>;
[break];
[continue];
}

While Loop
while (<condition>)
{
<statements>;
}

Do-While Loop
do
{
<statements>;
} while (<condition>);

Switch
switch (<expression>)
{
case <literal or type>:
<statements>;
[break;]
case <literal or type>:
<statements>;
[break;]
default:
<statements>;
}

Function Structure
function <function_name>([<parameters>])
{
<statements>;
[return <value>;]
}

Class Structure
class <class_name> [<extends base_class>]
{
[var | <modifiers*>] [<class member variables>];
[<modifiers*>] function <function_name>([<parameters>])
{
<statements>;
}
}
* Modifiers <public | pr ivate | static> are implemented in PHP5

Declare and Use Class
$variable = new class_name();
$variable->function_name();
class_name::function_name(); (Static call)


Thanks!!!!!!!!!! Enjoy Programming :)

Sunday, 23 October 2011

Why GROUP_CONCAT returns BLOB?

Last week, when using the GROUP_CONCAT() function on a MySQL database, I got an unexpected result. :(

Indeed, instead of getting my result as VARCHAR types, I got it as BLOB types! For information, a BLOB is a binary large object that can hold a variable amount of data:
http://dev.mysql.com/doc/refman/5.0/en/blob.html
Because BLOB values are treated as binary strings, it is not easy to use. This is why we would prefer to have VARCHAR values.

So the question is how to get around this frustrating problem?

The answer is, for once, very simple! :D
You simply need to:

Open your my.ini or my.cnf file;
Change the value of the group_concat_max_len system variable to 512 (no ‘k’ suffix);
Restart the mysql service

To verify if the value has been successfully updated, execute the following command in your mysql client:
mysql> show variables like "%concat%";
+----------------------+-------+
| Variable_name | Value |
+----------------------+-------+
| group_concat_max_len | 512 |
+----------------------+-------+
1 row in set (0.00 sec)

Note that you cannot set the value of group_concat_max_len to less than 1Kb using the MySQL Administrator GUI. Which means that the only way to set this system variable to 512 (which is less than 1Kb) is to edit your MySQL configuration file as described above.

Sunday, 16 October 2011

Different type of Cookies?

What are Temporary Cookies?

Temporary, or session, cookies are removed from your computer after you close the browser. Websites use them to store temporary information, such as items in your shopping cart.

 What are Persistent Cookies?

Persistent, or saved, cookies remain on your computer after you close the browser. Websites use them to store information, such as your sign-in name and password, so that you don't have to sign in each time you go to a particular site. Persistent cookies can remain on your computer for days, months, or even years.

What are First-party Cookies?

First-party cookies come from the website that you're viewing and can be either persistent or temporary. Websites might use these cookies to store information that they'll reuse the next time you go to that site.

What are Third-party Cookies?

Third-party cookies come from other websites' advertisements (such as pop-up or banner ads) on the website that you're viewing. Websites might use these cookies to track your web use for marketing purposes.



Saturday, 15 October 2011

Cloud Computing vs. Virtualization

Cloud computing and virtualization are both technologies that were developed to maximize the use of computing resources while reducing the cost of those resources. They are also mentioned frequently when discussing high availability and redundancy. While it is not uncommon to hear people discuss them interchangeably; they are very different approaches to solving the problem of maximizing the use of available resources. They differ in many ways and that also leads to some important considerations when selecting between the two.

Virtualization: More Servers on the Same Hardware


Virtualization

It used to be that if you needed more computing power for an application, you had to purchase additional hardware. Redundancy systems were based on having duplicate hardware sitting in standby mode in case something should fail. The problem was that as CPUs grew more powerful and had more than one core, a lot of computing resources were going unused. This obviously cost companies a great deal of money.


Enter virtualization. Simply stated, virtualization is a technique that allows you to run more than one server on the same hardware. Typically one server is the host server and control the access to the physical server’s resources. One or more virtual servers then run within containers provided by the host server. The container is transparent to the virtual server so the operating system does not need to be aware of the virtual environment. This allows server to be consolidated which reduces hardware costs. Less physical servers also means less power which further reduces cost.

Most virtualization systems allow the virtual servers to be easily moved from one physical host to another. This makes it very simple for system administrators to reconfigure the servers based on resource demand or to move a virtual server from a failing physical node.

Virtualization helps reduce complexity by reducing the number of physical hosts but it still involves purchasing servers and software and maintaining your infrastructure. It’s greatest benefit is reducing the cost of that infrastructure for companies by maximizing the usage of the physical resources.

Cloud Computing: Measured Resources, Pay for What You Use

Cloud Computing

While virtualization may be used to provide cloud computing, cloud computing is quite different from virtualization. Cloud computing may look like virtualization because it appears that your application is running on a virtual server detached from any reliance or connection to a single physical host. And they are similar in that fashion. However, cloud computing can be better described as a service where virtualization is part of a physical infrastructure.

Cloud computing grew out of the concept of utility computing. Essentially, utility computing was the belief that computing resources and hardware would become a commodity to the point that companies would purchase computing resources from a central pool and pay only for the amount of CPU cycles, RAM, storage and bandwidth that they used. These resources would be metered to allow a pay for what you use model much like you buy electricity from the electric company. This is how it became known as utility computing.

It is common for cloud computing to be distributed across many dedicated servers. This provides redundancy, high availability and even geographic redundancy. This also makes cloud computing very flexible. It is easy to add resources to your application. You just use them, just like you just use the electricity when you need it. Cloud computing has been designed with scalability in mind.

The biggest drawback of cloud computing is that, of course, you do not control the servers. Your data is out there in the cloud and you have to trust the provider that it is safe. Many cloud computing services offer SLAs that promise to deliver a level of service and safety but it is critical to read the fine print. A failure of the cloud service could result in a loss of your data.

Which One is Right for My Application?

How do you decide whether you need virtualization or cloud computing? They both can save money but they do it in different ways. One key consideration is when do you need to save the money. If you use virtualization, you will have a great deal of upfront cost. A new application will need servers and you’ll have to purchase the infrastructure for it. Virtualization means you’ll be spending less upfront and you will save money over time, but there is still going to be a large amount of capital spent early on. Cloud computing works in just the opposite fashion. You new application may not need many resources initially so cloud computing will likely cost very little in the beginning. However, as your application becomes popular and uses more resources, paying by the resource may become more expensive than using virtual servers on your own infrastructure.

Another important consideration is how safe will your data be. Are you comfortable with the cloud computing vendor? In a virtualized environment, you data is on your own hardware. You know who has access, where it is and how its being backed up. You also know exactly how you’ll handle a disaster recovery scenario. Cloud computing, on the other hand, places more that control in the hands of the vendor. While you’ll likely have a SLA to fall back on, it may not be enough. Last year, Microsoft had a failure in a data center that provided cloud computing services for T-Mobile’s Sidekick service. This failure resulted in the loss of customer data and a huge blow to T-Mobile’s reputation. While the SLA will likely provide some monetary compensation to T-Mobile, it cannot repair their reputation with the customers who lost data. You’ll want to consider carefully whether the SLA will cover all your bases as well.

Virtualization and cloud computing are both ways to reduce infrastructure cost by maximizing the utilization of computing resources. They are not the same thing however. Virtualization allows server consolidation by hosting many servers on a single piece of hardware where cloud computing is a service that delivers computer resources on a metered pay-as-you-go model. While they both have advantages, you’ll want to think about factors like start up cost versus long term costs and the possible loss of control of your infrastructure when deciding which model to utilize.

Sunday, 9 October 2011

Connection between PHP (server) and Android (client)

Nowadays, PHP and Android are widely used platforms, while PHP is used for dynamic web development, Android is an OS for mobiles, tablets etc. To develop Android applications we can use the benefits of PHP to communicate it with MySQL database and get required data from there.

We can use JSON and HTTP as an intermediate of communication between Android and PHP. The whole process can be divided into five steps:

1)      An HTTP request is sent from Android(Client) to PHP(Server).

2)      PHP runs it’s script to make connection with database, and send request to MySQL database for required data.

3)      MySQL responds back to PHP with requested data.

4)      PHP script analyse the date and coverts it into information. The whole information is then converted into JSON format and sent to the Android (Client).

5)      Android script reads the data, perform its operations and shows it on it’s screen.

The Whole process has also been described in the following diagram.


                                                      Figure : Android and PHP

 

Thanks!!!!!!!!!!! Enjoy Programming!!!!!!!! :)

 

 

Odoo 10: Close wizard and open standard form

Hi, Today we are going to learn how to open standard form after saving data in wizard. Let's say I have created an wizard to fill bas...