Pages

Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Sunday, January 26, 2014

Debian/Linux/Ubuntu-Configure Postfix to use Gmail

Configure Postfix to use Gmail

Install necessary packages first

 sudo apt-get install postfix mailutils libsasl2-2 ca-certificates libsasl2-modules  

 Configure Postfix using


 sudo dpkg-reconfigure postfix  


Navigate to Postfix Directory

 cd /etc/postfix  

Open Postfix config file using following command

 sudo gedit main.cf  

Add following lines to it


 relayhost = [smtp.gmail.com]:587  
 smtp_sasl_auth_enable = yes  
 smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd  
 smtp_sasl_security_options = noanonymous  
 smtp_tls_CAfile = /etc/postfix/cacert.pem  
 smtp_use_tls = yes  

Now we need to create a file called sasl_passwd


 sudo vi /etc/postfix/sasl_passwd  

Add the following line to the same


 [smtp.gmail.com]:587  USERNAME@gmail.com:PASSWORD  

Configure permissions for sasl_passwd


 sudo chmod 400 /etc/postfix/sasl_passwd  
 sudo postmap /etc/postfix/sasl_passwd  

Validate Certificates


 cat /etc/ssl/certs/Thawte_Premium_Server_CA.pem | sudo tee -a /etc/postfix/cacert.pem  

Reload Postfix


 sudo /etc/init.d/postfix reload  

Test Mail from Terminal


 echo "Test mail from postfix" | mail -s "Test Postfix" you@example.com  

Copy of my php.ini mail section


 SMTP = ssl://smtp.gmail.com  
 smtp_port = 587  
 auth_username = usrname  
 auth_password = pwd  
 sendmail_from = from_mail  

Sunday, December 15, 2013

PHP-Image functions

//size of image
getimagesize()
http://www.php.net/getimagesize

//image width
imagesx()
http://www.php.net/manual/en/function.imagesx.php


//image height
imagesy()
http://www.php.net/manual/en/function.imagesy.php

//determine type of an image
exif_imagetype()
http://www.php.net/manual/en/function.exif-imagetype.php

Encrypt data using PHP

Encryption Decryption
AES_ENCRYPT() AES_DECRYPT()
ENCODE() DECODE()
DES_ENCRYPT() DES_DECRYPT()
ENCRYPT() N/A
ENCRYPT() N/A
MD5() N/A
OLD_PASSWORD() N/A
PASSWORD() N/A
SHA() N/A
SHA1() N/A
N/A UNCOMPRESSED_LENGTH()

Saturday, December 14, 2013

PHP-Database connectivity function's

One of the main aspects of PHP is database connectivity.Though it supports variety of databases we will talk about mysql in particular here.

All the functions which are of concern are present in file mysqli.php which contains class "mysqli_sql_exception" which in turn extends "RuntimeException"

The very first functions that we encounter while working with databases with PHP are the "connect functions".

Let's see what we get when we execute these functions in order

As a software development flows we will have some prerequisites,a function which will process them and then we will have some results.

Prerequiaites :

A dbhost : "localhost"
A username : "uroot"
A password : "proot"
Also

That's it and all we need is a php setup LAMP/WAMP/MAMP/XAMPP package

Our first function :
 $con= mysqli_connect('localhost1','puroot','pproot','test1');  
Reference :
/**
 * (PHP 5)<br/>
 * Alias of <b>mysqli::__construct</b>
 * @link http://php.net/manual/en/function.mysqli-connect.php
 * @param $host [optional]
 * @param $user [optional]
 * @param $password [optional]
 * @param $database [optional]
 * @param $port [optional]
 * @param $socket [optional]
 */
function mysqli_connect ($host, $user, $password, $database, $port, $socket) {}

This function tries to connect to the database with given credentials. We have created a negative mutant to test the same as you can see from what credentials we have passed above.


Our Second function and third function :
 if (mysqli_connect_errno())  
 {  
   echo "Failed to connect to MySQL: " . mysqli_connect_error();  
 }
Reference:
/**
 * (PHP 5)<br/>
 * Returns the error code from last connect call
 * @link http://php.net/manual/en/mysqli.connect-errno.php
 * @return int An error code value for the last call to <b>mysqli_connect</b>, if it failed.
 * zero means no error occurred.
 */
function mysqli_connect_errno () {}

/**
 * (PHP 5)<br/>
 * Returns a string description of the last connect error
 * @link http://php.net/manual/en/mysqli.connect-error.php
 * @return string A string that describes the error. <b>NULL</b> is returned if no error occurred.
 */
function mysqli_connect_error () {}

Now when we execute the above pieces of code we get an error

Failed to connect to MySQL: Unknown MySQL server host 'localhost1' (2)Error creating database:

When we set host right we get following error
Failed to connect to MySQL: Access denied for user 'puroot'@'localhost' (using password: YES)Error creating database: 

Similarly when we set username and password right we get
Failed to connect to MySQL: Unknown database 'test1'

Now that we are done with the set of connection functions we will try to create a database on success.Now since we have already created a database "test" we will test with a negative mutant.

Our fourth and fifth function
 $sql="CREATE DATABASE test";  
 if (mysqli_query($con,$sql))  
 {  
   echo "Database test created successfully";  
 }  
 else  
 {  
   echo "Error creating database: " . mysqli_error($con);  
 }  
Reference:

 /**  
  * (PHP 5)<br/>  
  * Performs a query on the database  
  * @link http://php.net/manual/en/mysqli.query.php  
  * @param mysqli $link  
  * @param string $query <p>  
  * The query string.  
  * </p>  
  * <p>  
  * Data inside the query should be properly escaped.  
  * </p>  
  * @param int $resultmode [optional] <p>  
  * Either the constant <b>MYSQLI_USE_RESULT</b> or  
  * <b>MYSQLI_STORE_RESULT</b> depending on the desired  
  * behavior. By default, <b>MYSQLI_STORE_RESULT</b> is used.  
  * </p>  
  * <p>  
  * If you use <b>MYSQLI_USE_RESULT</b> all subsequent calls  
  * will return error Commands out of sync unless you  
  * call <b>mysqli_free_result</b>  
  * </p>  
  * <p>  
  * With <b>MYSQLI_ASYNC</b> (available with mysqlnd), it is  
  * possible to perform query asynchronously.  
  * <b>mysqli_poll</b> is then used to get results from such  
  * queries.  
  * </p>  
  * @return mixed <b>FALSE</b> on failure. For successful SELECT, SHOW, DESCRIBE or  
  * EXPLAIN queries <b>mysqli_query</b> will return  
  * a <b>mysqli_result</b> object. For other successful queries <b>mysqli_query</b> will  
  * return <b>TRUE</b>.  
  */  
 function mysqli_query (mysqli $link, $query, $resultmode = 'MYSQLI_STORE_RESULT') {}  
 /**  
  * (PHP 5)<br/>  
  * Returns a string description of the last error  
  * @link http://php.net/manual/en/mysqli.error.php  
  * @param mysqli $link  
  * @return string A string that describes the error. An empty string if no error occurred.  
  */  
 function mysqli_error (mysqli $link) {}  


Error creating database: Can't create database 'test'; database exists

because we have already created one

similarly mysql_query() is used for create table,insert

Our sixth function

 $result= mysqli_query($con,"SELECT * FROM Persons");  
 while($row= mysqli_fetch_array($result))  
 {  
   echo "<pre>";  
   print_r($row);  
   echo "</pre>";  
 }  
 $result= mysqli_query($con,"SELECT * FROM Persons");  
 while($row= mysqli_fetch_row($result))  
 {  
   echo "<pre>";  
   print_r($row);  
   echo "</pre>";  
 }  
 $result= mysqli_query($con,"SELECT * FROM Persons");  
 while($row= mysqli_fetch_object($result))  
 {  
   echo "<pre>";  
   print_r($row);  
   echo "</pre>";  
 }  
 $result= mysqli_query($con,"SELECT * FROM Persons");  
 while($row= mysqli_fetch_assoc($result))  
 {  
   echo "<pre>";  
   print_r($row);  
   echo "</pre>";  
 }  
References for ways we can fetch row:
 /**  
  * (PHP 5)<br/>  
  * Fetch a result row as an associative, a numeric array, or both  
  * @link http://php.net/manual/en/mysqli-result.fetch-array.php  
  * @param mysqli_result $result  
  * @param int $resulttype [optional] <p>  
  * This optional parameter is a constant indicating what type of array  
  * should be produced from the current row data. The possible values for  
  * this parameter are the constants <b>MYSQLI_ASSOC</b>,  
  * <b>MYSQLI_NUM</b>, or <b>MYSQLI_BOTH</b>.  
  * </p>  
  * <p>  
  * By using the <b>MYSQLI_ASSOC</b> constant this function  
  * will behave identically to the <b>mysqli_fetch_assoc</b>,  
  * while <b>MYSQLI_NUM</b> will behave identically to the  
  * <b>mysqli_fetch_row</b> function. The final option  
  * <b>MYSQLI_BOTH</b> will create a single array with the  
  * attributes of both.  
  * </p>  
  * @return mixed an array of strings that corresponds to the fetched row or <b>NULL</b> if there  
  * are no more rows in resultset.  
  */  
 function mysqli_fetch_array (mysqli_result $result, $resulttype = 'MYSQLI_BOTH') {}
/**
 * (PHP 5)<br/>
 * Get a result row as an enumerated array
 * @link http://php.net/manual/en/mysqli-result.fetch-row.php
 * @param mysqli_result $result
 * @return mixed <b>mysqli_fetch_row</b> returns an array of strings that corresponds to the fetched row
 * or <b>NULL</b> if there are no more rows in result set.
 */
function mysqli_fetch_row (mysqli_result $result) {}
/**
 * (PHP 5)<br/>
 * Fetch a result row as an associative array
 * @link http://php.net/manual/en/mysqli-result.fetch-assoc.php
 * @param mysqli_result $result
 * @return array an associative array of strings representing the fetched row in the result
 * set, where each key in the array represents the name of one of the result
 * set's columns or <b>NULL</b> if there are no more rows in resultset.
 * </p>
 * <p>
 * If two or more columns of the result have the same field names, the last
 * column will take precedence. To access the other column(s) of the same
 * name, you either need to access the result with numeric indices by using
 * <b>mysqli_fetch_row</b> or add alias names.
 */
function mysqli_fetch_assoc (mysqli_result $result) {}
/**
 * (PHP 5)<br/>
 * Returns the current row of a result set as an object
 * @link http://php.net/manual/en/mysqli-result.fetch-object.php
 * @param mysqli_result $result
 * @param string $class_name [optional] <p>
 * The name of the class to instantiate, set the properties of and return.
 * If not specified, a <b>stdClass</b> object is returned.
 * </p>
 * @param array $params [optional] <p>
 * An optional array of parameters to pass to the constructor
 * for <i>class_name</i> objects.
 * </p>
 * @return object an object with string properties that corresponds to the fetched
 * row or <b>NULL</b> if there are no more rows in resultset.
 */
function mysqli_fetch_object (mysqli_result $result, $class_name = null, array $params = null) {}

PHP-Reference Variable

Reference variable are those that have a reference to the value stored in them for example

 $name = 'fruit'; //Generic Varible  
 $$name='banana'; //Reference Variable  
 echo $fruit;   
 //Outputs Banana  


Here $name is a variable which stores name 'fruit' and in turn there is a memory location in your system when you run this program which is labelled as 'fruit' in which value is stored as $$name or $fruit.

Sunday, September 15, 2013

PHP-Loop Queston's

1. for($i=1;$i++;$i<100)
echo $i;

2. for($i=0;$i++;$i<100)
echo $i;

How many times will the loop execute in both the cases.

Answers:

1. Infinite why?
We know that for loop has 3 blocks 1st is assignment 2nd is condition and 3rd is increment.

Now in first block we have assignment $i=1 We are fine with it
In second block we are having $i++ which means that it will check for value of $i as condition before incrementing so $i=1 and increment $i to 2 and again in next pass we have $i=2 which is again true value>0 results in true.
and it will go on until falls short of memory.

2. 0 Why?

$i=0 initially checked that condition before increment $i=0 which returns false and as such loop halts.


OOPS-PHP-Magic Methods

1. __get($property)

Get value for a property set in a class foe example

 function __get($property)  
 {  
 return $this->properties[$property];  
 }  


Usage: echo $st->name;

2. __set($property,$value) Set value for a property
 function __set($property, $value)  
 {  
 $this->properties[$property]="AutoSet {$property} as: ".$value;  
 }  


Usage: $st->roll=16;

3. __call()
overloads any undefined function in a class.Thus we can also call an undefined function and show custom error message.

 function __call($method, $arguments)  
 {  
 echo "You called a method named {$method} with the following  
 arguments <br/>";  
 print_r($arguments);  
 echo "<br/>";  
 }  

Usage: $ol->notAnyMethod("boo");

OOPS-What is the difference between Static and Final Keyword

Static
A static method remains common for all objects and can be called directly without the need of creation of any object.

For Example : classname::functionname();

A static property on the other end remains common for all the objects.It preserves its last changed state by any object.

Final
Final keyword on other end does not allows a class to be extended a method to be overridden in subclass or to change a property respective to its use in a class.

Saturday, September 14, 2013

OOPS-PHP-usefull functions

1. get_declared_classes();
Returns an array with the name of the defined classes.Useful when you have integrated a component or helper or vender class and what to know whether it's been included or not.

Thursday, September 12, 2013

Differences between abstract class and interface in PHP

Following are some main difference between abstract classes and interface in php
  1. In abstract classes this is not necessary that every method should be abstract. But in interface every method is abstract.
  2. Multiple and multilevel both type of inheritance is possible in interface. But single and multilevel inheritance is possible in abstract classes.
  3. Method of php interface must be public only. Method in abstract class in php could be public or protected both.
  4. In abstract class you can define as well as declare methods. But in interface you can only defined your methods.

How are sessions stored?

The default behaviour for session storage is to save the session data in a file. This behaviour can be altered by changing the session.save_handler in your php.ini file. Options can be:

1. files
2. mm
3. database
4. SQLite

If we choose we can have this stored in one of the options above.

In files  session's are stored in /var/lib/php5 in Debian based linux
file is named like "sess_v93e2jhpjho4s4ea7r93vkbvu7" and data is stored like
foo|s:3:"bar";animals|a:8:{i:0;s:3:"cat";i:1;s:3:"dog";i:2;s:5:"mouse";i:3;s:4:"bird";i:4;s:9:"crocodile";i:5;s:6:"wombat";i:6;s:5:"koala";i:7;s:8:"kangaroo";}

The mm option saves the session data into memory, this also gives significant speed increase and is often recommended by tutorials for fine tuning PHP and apache web server.

Sessions may also be stored in a database. This option provides for greater manageability of sessions and allows the programmer to perform tasks such as counting of active sessions etc.In this session storage is permanent.

With the advent of PHP5, we now have SQLite bundled with PHP. If PHP is configured --with-sqlite, you will have access to saving sessions with a PHP native database, although SQLite is not truly a database, but a file abstraction layer with and SQL interface.

php-How do sessions work?

Sessions can be used in two ways:

1. cookie based
2. url based

Most sessions are cookie based. What this means is that when a session is started, a cookie is set on the clients machine with a unique session ID or SID. The session variables are stored typically on a file on the server that matches the unique session ID. When a variable is required, the client or browser looks for the file matching the session ID and retrieves the corresponding variables from it. A typical session file stored in the default session file directory would look like this
sess_fd51ab4d1820aa6ea27a01d439fe9959

PHP-Path to Session Storage

We can get and set session storage path using the following keyword in core php

session_save_path ([ string $path ] );

Wednesday, September 11, 2013

Php-require,require_once,include,include_once

Difference between require() and require_once(): require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page).

So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example. This way you make sure you don't include the file more times and you will not get the "function re-declared" error.

Difference between require() and include() is that require() produces a FATAL ERROR if the file you want to include is not found, while include() only produces a WARNING. There is also include_once() which is the same as include(), but the difference between them is the same as the difference between require() and require_once().

Cakephp-HABTM implementation

HABTM

"Has and Belongs To Many"

A "Post" may have many "Tags" and may belong to many tags

In Post's Model


 public $hasAndBelongsToMany = array(  
  'Tag' => array(  
   'className' => 'Tag',  
   'joinTable' => 'posts_tags',  
   'foreignKey' => 'post_id',  
   'associationForeignKey' => 'tag_id',  
   'unique' => 'keepExisting',  
  )  
  );  

Wednesday, March 27, 2013

PHP Web Programming and Business Benefits of PHP Development

Inception of PHP is almost two decade old, when Danish programmer Rasmus Lerdorf created PHP in 1995. Inspired by that, in year 1997, two Israeli programmers Andi Gutmans and Zeev Suraski rewrote the parser, creating the base for PHP 3 and also built the Zend engine which is still followed as the interpreter for PHP.

Influence Of PHP Across Web

Today, almost two decades after countless colossal modifications to codebase, more than 35% of web traffic is handled by PHP. Facts on Wikipedia say 75% of websites use PHP, which includes some giant domains such as Facebook, Wikipedia, Yahoo, Photobucket and many others. Amazingly, list doesn’t end here; world’s best blogging platform “WordPress” and other popular CMSs like Drupal and Joomla are built in php.
Above mentioned facts are enough to claim the dominancy of PHP even in the presence of killer web development technologies. But, what are the reasons, why php hits the mainstream enterprise and why it is forecasted to maintain its momentum even in the coming years.
Success of php web programming totally bets on advantages which it offers to its users. Not only PHP developers find it convenient, but even end-users claim it to be friendly. Several studies have concluded some common advantages offered by php development, and they are as follow.

Free For All “Its Open Source”

Under GPL (General Public License) PHP is freely available for use, along with its associated software’s like MySQL, Text Editors and Apache Server to reduce your overall development cost. With the aim to serve you better, php community offers technical support and is constantly sweating hard to improve the core functionalities of PHP.

Cross-Platform Compatibility

It exhibits high compatibility with all the major OS and servers for easy deployment across vivid platforms. PHP scripts can run across OS like Linux, Windows, Solaris, OpenBSD, Mac OSX and others. It also provides support for all leading servers such as Apache, IIS, iPlanet and so on.

Powers Equally – Either Small or Big Websites

Either small or giant, whatever are your business needs a php based business website can be easily developed in not time and in limited budget. Business and organizational websites, informative forums, CRM solutions, e-commerce websites, community websites, e-business and gigantic database driven sites can be easily developed using php.

Extensions to Expand Functionalities

Plethora of extensions and libraries are available across the web using which you can extend core functionalities of your website. Even custom created extensions can be included into source code of PHP.

Top Security – For Hacker Proof Website

It offers top level security that helps prevent malicious attacks. These security stages can be easily attuned in the .ini file.

Veteran Developers to Execute Your Plans

You can hire PHP programmers/developers from reputed web development company more easily than any other language programmers. Just follow simple tips to hire veteran developers and stay away from worries.
In the end, if you are in the mood to add dynamic content to your project, then use of PHP is highly recommended. It free, easy to understand and integrates almost all the functionalities as per your needs. There are tons of php developers available on the net. Please don’t hesitate to add anything if I have missed some other great PHP benefits. Feel free to share your thoughts with other readers.

Tips to Create Secure PHP Applications

PHP is one of the most popular programming languages for the web. Such languages are very helpful for the programmer but the security holes in it can create a problem. They can create problems in the development path.Below are few tips to help you avoid some common PHP security pitfalls and development bug.
1. Use of Proper Error Reporting
Error reporting can be your best friend during the development process. Error reports helps you to find spelling mistakes in your variables and also detect incorrect function usage. Always make sure that you hide all the error reporting once you decide to make the site live.
This can be done by invoking the simple function “error_reporting(0)” at the top of your application file(s).
You should always make sure to log your errors to a protected file. Which help to detect the problem when something go wrong. Therefore, This can be done with the PHP function “set_error_handler”.
2. Disable PHP’s harmful Features
PHP’s creators have always included some features to make PHP development easier. Some of these helpful features can have unintended consequences.
We can call these as “bad features” because they have allowed data validation and created a path for bugs to finding their way into scripts. One of
the first things you should do when the development process begins is
disable certain of these features. Depending on the host which you are using, these may or may not be turned off for you. If you are developing on your own computer or any local environment, they probably won’t be turned off. Some of these features have also been removed in the upcoming PHP6, but are ubiquitous in PHP4 applications and are only deprecated in PHP5 applications.
3. Validate Input
With addition to escaping characters, another good way to protect
input is to validate it. Normally you actually know what kind of data you are expecting on input.  So the simplest way to protect yourself against attacks is to make sure your users can only enter the appropriate data.
4. Watch for Cross Site Scripting (XSS) Attacks in User Input
A web application usually accepts input from users and displays it
in some way. They can be in a wide variety of forms. When accepting input, allowing HTML can be a dangerous thing,because that allows for JavaScript to be executed in unintended ways. If even one hole is left open, JavasScript can be executed and cookies could be hijacked. This cookie data could then be used to fake a real account and give an illegal user access to the website’s data. There are a some ways you can protect your site from such attacks. One way is to disallow HTML altogether, because then there is no possible way to allow any JavaScript to execute.
5. Protecting against SQL Injection
SQL injection attacks occur when data is not checked, and the application doesn’t escape characters used in SQL strings such as single quotes (‘) or double quotes (“). If these characters are not filtered out users can disturb the system by making queries always true and which allow them to trick  login systems.
MySQLi help protect your database input. We can do it in 2 ways.
Either with the mysqli_real_escape_string function when connected to a server or with prepared statements.
Prepared statements are a method of separating SQL logic from the data being passed to it. The functions used within the MySQLi library filter the input for us when we bind variables to the prepared statement.

Friday, January 25, 2013