Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Monday, October 5, 2015

Top 5 practice to become a good PHP Developer

1. Use PHP Core Functions and Classes

 Always give preference to the functions already defined and use php's core classes to acheive your goal before defining your own function or classes. For example There’s no need to create a function to remove the white space at the beginning and at the end of a string when you can just use the trim() function

2. Using Configuration File

Always create a configuration file for variables which are used globally in your application. For example  Instead of having your database connection settings scattered everywhere, why not just create one master file that contains its settings, and then include it in your PHP scripts? In case of changes, you will need to change only one file instead of changing multiple files.

3. Always Sanitize Data

Sanitize user input before you start any processing on the data to avoid sql injection or cross-site scripting xss attack. Luckily, there’s a PHP functions that can help. htmlspecialchars
mysql_real_escape_string  are few functions to santize your data. you can write your own function to avoid cross-site scriptingattack

4. Comment Your Code

Don't forget to comment your  code. A well comment code not only helps other to understand the code fast but also helps you to generate a good technical documentation on fly. there are tools which does that.
phpDocumentor  is a good tool which helps to generate technical documentation out of your code, if commented properly.

10. Connect with Other PHP Developers

You don’t know all. E ven if you think so, there are thousands of other professionals out there who  know how to do something better than you do. Join a PHP community like PHPDeveloper and interact with others to sharpen your skills.

Wish you to become a better PHP developer. You can also help me referring good things. Your inputs and suggestions are welcome.



Wednesday, June 13, 2012

xml to array

Here is the function which convert xml data to respective array.

function xmlToArray($xml,$ns=null){
  $a = array();
  for($xml->rewind(); $xml->valid(); $xml->next()) {
    $key = $xml->key();
    if(!isset($a[$key])) { $a[$key] = array(); $i=0; }
    else $i = count($a[$key]);
    $simple = true;
    foreach($xml->current()->attributes() as $k=>$v) {
        $a[$key][$i][$k]=(string)$v;
        $simple = false;
    }
    if($ns) foreach($ns as $nid=>$name) {
      foreach($xml->current()->attributes($name) as $k=>$v) {
         $a[$key][$i][$nid.':'.$k]=(string)$v;
         $simple = false;
      }
    } 
    if($xml->hasChildren()) {
        if($simple) $a[$key][$i] = xmlToArray($xml->current(), $ns);
        else $a[$key][$i]['content'] = xmlToArray($xml->current(), $ns);
    } else {
        if($simple) $a[$key][$i] = strval($xml->current());
        else $a[$key][$i]['content'] = strval($xml->current());
    }
    $i++;
  }
  return $a;
}
This function can be used as follows.
$xml = new SimpleXmlIterator('./a.xml', null, true);
$namespaces = $xml->getNamespaces(true);
$arr = xmlToArray($xml,$namespaces);

Friday, December 9, 2011

Membase

Membase is high performance key value pair system used for cacheing data. Membase generally provide superset of memcached.

You can use Membase to and configure either "memcached" type or "membase" type buckets. A membase-type bucket provides additional features such as key-value persistence and replication, whereas a memcached-type bucket provides only memory-only caching.

Memcached has it’s limitations. Moving to large+1 machines is going to lose a lot of your data. There is no master to organize the re-balancing of the data.We can avoid data loss using membase bucket type, while adding new server to the clusters.

Moxi

Moxi is the component of Membase that handles the re-routing of requests to other Membase servers when the server receiving the original request is not the one responsible for the data requested.

You can install membase using the instructions here.

testing membase.

you can test it using telnet utility.

shell> telnet localhost 11211 Trying 127.0.0.1... Connected to localhost.localdomain (127.0.0.1). Escape character is '^]'

set test_key 0 0 1 a STORED
or you can run a PHP script to check if membase is installed properly or not.

connect("localhost",11211); // try 127.0.0.1 instead of localhost
// if it is not working

echo "Server's version: " . $memcache->getVersion() . "
\n";

// we will create an array which will be stored in membase serialized
$testArray = array('horse', 'dog', 'pig');
$tmp = serialize($testArray);
$memcache->add("key", $tmp);
echo "Data from the cache:
\n";
print_r(unserialize($memcache->get("key")));
?>




Thursday, September 22, 2011

Working with memcached

memcached is a general-purpose distributed memory caching system used to speed up dynamic database driven websites by caching data in RAM to reduce the number of times an external data source to be read.

Here is how memcached can be useful.The system uses a client server architecture. Server maintains associative array in key value pair. the clients populate this array and query it. Keys are up to 250 bytes long and values can be at most 1 MB size. by default server runs on 11211 port. A client should be installed in order to access memcached data. client can connect to multiple server by adding new server to it's pool. gettting data from memcached there are several methods to use memcached. yo can go to official site for more information on memcached.

Using memcached from a script. [I've used PHP in example.]

1. Memcached class should exist if memcached client is installed properly. Create an object of memcached.
                  $obj = new Memcached();
    if object created means memcached service is running. If not then you can start the service from command prompt.using command  svc -u path/to/memcached/ [eg:  /usr/local/memcache/bin/memcached ]

2. Add the server to the pool.
                $obj->addServers($servers); [$servers = array( '172.18.1.69', 11211) where 1st param. is IP of the server and second is port.]

3 Now you can use different methods to add/fetch memcached data. [example get($key),set($key,$value)]. for more information visit php.net site and search for memcached based function.


Checking memcache log.

1. Go to memcashed directory  /service/memcached

2.write the following command to get log
tail -f log/main/current | tai64nlocal


Using telnet to connect to memcache server.

1. telnet server_IP port [telnet 127.0.01 11214]

Once connected, you can check if memcache key is set, by typing  get memcache_key_name to get the memcached data for the key memcache_key_name and press enter. You can also set and delete key using set and delete.

Well that's all folks. We'll see membase in the next session.





Thursday, May 28, 2009

acessing xml in php sent by other script

There are several situation where we need to accept xml as input in php file which is sent by other scripts like flash/php/perl etc.

To accept xml as input in php, first you need to check that content-type which is being passed by source script has to be in "text/xml" format.

Now in your PHP script you can accept xml input by the following code.
$xml_str=file_get_contents("php://input");
//where $xml_str will have xml string passed by the source script.


Wednesday, March 25, 2009

Testing web Application


Nowadays lot's of effort is gone for testing and quality assurance of the web application which can be minimized by using web based testing tools available on the web.

There are lot's of Ad-ons available for mozila firfox for different kind of the testing which Includes such as iMacros for Firefox, WASP, Fireshot, Window Resizer, Selenium IDE, Web Developer, SwitchProxy, IE Tab, Molybdenum, HackBar, and many more.

Selenium IDE
is an integrated development environment for Selenium tests.allows you to record, edit, and debug tests.You can choose to use its recording capability, or you may edit your scripts by hand.

Web Developer The Web Developer extension adds a menu and a toolbar to the browser with various web developer tools. It is designed for Firefox, Flock and Seamonkey, and will run on any platform that these browsers support including Windows, Mac OS X and Linux.

Hackbar allow you to test your web pages against sql injections, XSS holes and site security.It is not used for executing standard exploits.

These are few ad-ons which I use and It help me as a developer/tester to test website more rapidly.

Wednesday, December 17, 2008

ADODB with PHP and oracle

Oracle is the popular commercial database which is being used with the PHP.There are vaious ways to connect to oracle database.ADODB library is one of the fastest way to connect php with the oracle database.It has Has multi-tier design. Simple high-level design for beginners, and also lower-level advanced Oracle functionality.ADODB provide very high speed databse connectivity with catching and fastest database abstaction.It also allow multiple prepare statement.

An example to connect php with oracle using ADODB library is as follows.

include"/path/to/adodb.inc.php";
$db = NewADOConnection("oci8");
$db->Connect($tnsName, "scott", "tiger");

$rs = $db->Execute("select * from emp where empno>:emp order by empno",
array('emp' => 7900));
while ($arr = $rs->FetchRow())
{
print_r($arr);

}
The Execute( ) function returns a recordset object, and you can retrieve the rows returned using $recordset->FetchRow( ).
You can also query the database using the standard Microsoft ADO MoveNext( ) metaphor. The data array for the current row is stored in the fields property of the recordset object, $rs. MoveNext( ) offers the highest performance among all the techniques for iterating through a recordset:

$rs = $db->Execute("select * from emp where empno>:emp", array('emp' => 7900));
while (!$rs->EOF) {
print_r($rs->fields);
$rs->MoveNext();
}

For easy pagination support, we provide the SelectLimit function. The following will perform a select query, limiting it to 100 rows, starting from row 201 (row 1 being the 1st row):

$offset = 200; $limitrows = 100;
$rs = $db->SelectLimit('select * from table', $limitrows, $offset);

Caching

You can define a database cache directory using $ADODB_CACHE_DIR, and cache the results of frequently used queries that rarely change. This is particularly useful for SQL with complex where clauses and group-by's and order-by's. It is also good for relieving heavily-loaded database servers.The following example will cache the following select statement for 7200 seconds

$ADODB_CACHE_DIR = '/var/tmp';
$rs = $db->CacheExecute(7200, "select names from allcountries order by 1");
Using Prepare statements

Prepare( ) is for compiling frequently used SQL statement for reuse. For example, suppose we have a large array which needs to be inserted into an Oracle database. The following will result in a massive speedup in query execution (at least 20-40%), as the SQL statement only needs to be compiled once:


Friday, October 10, 2008

PHP Security

Now-a-days web security has been a major concern.During development, when the code is being written, it is important to consider illegitimate uses of your application. Often, the focus is on making the application work as intended, and while this is necessary to deliver a properly functioning application, it does nothing to help make the application secure. fact that you are here is evidence that you care about security,

Since PHP is a growing language being used for the web development,It's very important to discuss about PHP security.

Input flaws
most common PHP security flaws is the unvalidated input error. User-provided data simply cannot be trusted and should be validated properly.

register_globals = OFF. The register_globals directive is disabled by default in PHP versions 4.2.0 and greater.Enabling register_globals may cause a security risk.
A common example to explain the problem is as follows.
this example that illustrates how register_globals can be problematic is the following use of include with a dynamic path:

With register_globals enabled, this page can be requested with ?path=http%3A%2F%2Fevil.example.org%2F%3F in the query string in order to equate this example to the following:




Avoid using $_REQUEST[] since as per GPC rule $_GET has higher priorities than $_POST, So $_POST variables may be overwritten.

Always validate input data against maxlength in PHP.you can use array and for each to do this.
50);
foreach($max as $key=>$val)
{
if(strlen($_POST[$key])>$val)
{
//display maxlength error
}
}
?>



Friday, September 12, 2008

understanding JSON

JSON stands for JavaScript Object Notation.It's lightweight data interchange format.It is a text-based, human-readable format for representing object and other data structures and is mainly used to transmit such structured data over a network connection (in a process called serialization).It is based on subset of javascript.

JSON is a self-contained unambiguous data representation format, and since it carries no executable or algorithmic meaning it is inherently secure by itself. However security issues may arise if a program incorrectly processes JSON-formatted data as if it were something else. Since the JSON syntax is by design a subset of the Javascript syntax, most security concerns involve having a Javascript interpreter directly process JSON text as if it were Javascript source code.

The following example shows the JSON representation of an object that describes a employe. The object has string fields for first name and last name,company name,designation contains an object representing the person's address, and contains a list of phone numbers (an array).


{
   "firstName": "Uttam",
   "lastName": "Kumar", 
   “companyName” :”magnet”, 
   “designation”:”Sr. web Developer”,
   "address": {      
     "streetAddress": "Patankar street", 
            "city": "Nsp(w)",
             "state": "MH",
            "postalCode":401203     
               },
 "phoneNumbers": [ "212 732-1234","646 123-4567"]
 }

Suppose the above text is contained in the JavaScript string variable employee. Since JSON is a subset of JavaScript's object literal notation, one can then recreate the object describing Uttam Kumar with a simple eval() function which is as follows

 var emp = eval("(" + employee + ")");  Now we can access firstName,city,phone number by the following. 
emp.firstName //property of object
emp.address.city //sub property of object 
emp.phoneNumbers[0]//array
 similerly we can access all the values.

Basic level Interview Questions - PHP

Difference between session and cookies?

Ans:- 1. session stored at server while cookie get stored at client’s web browser.

2. session are stored as an object on server side on the path specified in the php.in file for session_save path variable while cookies are passed as header and stored on client’s web browser as text file.

3. session variables are exists only when session doesn’t expires while cookies[persistent not session] can be stored for future time also and can be used to handle user’s preference.

what are encryption methods available in php and mysql?Difference between sha1 and md5?

Ans:- some encryption methods available in php are md5,sha1,encrypt,password.Difference between sha1 and md5 encryption is that sha1 take more space than md5 in terms of storing information in the database.Some encryption available in mySql are password,MD5,encrypt.

What is Ajax & how it works?

Ans:- AJAX stands for asynchronous javascript and xml.It’s asynchronous this script doesn’t wait for the response.Regardless of this it can make another request without waiting for the response.Fist of all it creates XMLHttpRequest object by which it makes a request.and when response comes back script handover it to another function which will check for the response readyStatus and returns the response.

Oops principles?

Ans:- Polymorphism [not supported in PHP]

Encapsulation

Abstraction

Dynamic binding

class and Object

for more detail please refer http://in2.php.net/manual/en/language.oop5.php

Mysql Joins?

Ans:- I don’t have idea but know about types.Cross,Left,right,inner and outer join.

Strings and array functions.array_walk,in_array?

Ans:- check function list available on

http://in2.php.net/manual/en/ref.array.php [for array]

http://in2.php.net/manual-lookup.php?pattern=string〈=en [for strings function]

Difference between include,include_once,require,require_once?

Ans:- Unlike include(), require() will always read in the target file, even if the line it’s on never executes. If you want to conditionally include a file, use include(). The conditional statement won’t affect the require(). However, if the line on which the require() occurs is not executed, neither will any of the code in the target file be executed.include() may give warning and proceed further but require() will hault whenever warning/error faced in the script.include_once(),require_once() as name suggest can be used to include a file only one.[useful in case we include a class file]

How can we submit a form without a submit button?

Ans:- you can call a function in javascript onclick event of any form element/link and in the function you amy use document.formName.submit(); to submit the form

What is the difference between mysql_fetch_object, mysql_fetch_rows and mysql_fetch_array?

Ans:- mysql_fetch_object will return an object by which we can access the database fields records while mysql_fetch_aaray and mysql_fetch_rows return array of database records.mysql_fetch_row will not return associative array while mysql_array will return associative array too.

What is the difference between $message and $$message?

$message is used as a variable while $message can be used to assign a value as variable.for eg:

$message=’uttam’;

$message=’kumar’;

in this case $kumar will give you value as ‘uttam’.

What is meant by nl2br()?

Returns string with ‘
’ inserted before all newlines(\n).

$msg=”these are \n interview question”;

$nl2brmsg=nl2br($msg);

$nl2brmsg will return value as “these are
interview question”.