Wednesday, October 10, 2012

how to encode and decode html tag using php


how to encode and decode html tag using php
you can encode using ->
html_entities(mysql_real_escape_string($variable));

you can decoe using
html_entity_decode(stripslashes($variable));

Tuesday, October 9, 2012

how to remove html tag in a string using php

<?php
    $input = "<div id='bikash'><b>this is the html tag remove in php</b></div><strong>me use for html you do nt use</strong>";

   echo  $b = strip_tags($input, "<strong><em>");
?>

Saturday, October 6, 2012

how to add new custom field virtuemart product category fields in joomla administrator

how to add new field from category virtuemart joomla
execute query for add new category fields
1stp->   ALTER TABLE `jos_vm_category` ADD ` cat_wholesaler` VARCHAR( 1 ) NOT NULL DEFAULT 'N' AFTER `products_per_row` ;

2stp-> GO TO D:\xampp\htdocs\mil-bar\administrator\components\com_virtuemart\html\product.product_category_form.php open
add your field in product.product_category_form.php

      if ($db->sf("cat_wholesaler")=="Y")
         {
          echo "<input type=\"checkbox\" name=\"accesscat\" value=\"Y\" checked=\"checked\" />";
         }else{
          echo "<input type=\"checkbox\" name=\"accesscat\" value=\"Y\" />";
         }

2stp->  administrator/components/com_virtuemart/classes/ps_product_category.php in (function add( &$d ))

a. first get new field value for insert paste below code line 253

      if (vmGet($d,'accesscat')==''){
                 $waccess='N';
        }else{
                 $waccess='Y';
              }

$fields = array('vendor_id' => $ps_vendor_id,
    'category_name' => vmGet( $d, 'category_name' ),
    'category_publish' => vmGet( $d, 'category_publish' ),
    'category_description' => vmGet( $d, 'category_description', '',VMREQUEST_ALLOWHTML ),
        'category_browsepage' => vmGet( $d, 'category_browsepage' ),
    'products_per_row' => vmRequest::getInt( 'products_per_row' ),
    'cat_wholesaler'=>$waccess,
    'category_flypage' => vmGet( $d, 'category_flypage' ),
    'category_thumb_image' => vmGet( $d, 'category_thumb_image' ),
    'category_full_image' => vmGet( $d, 'category_full_image' ),
    'cdate' => $timestamp,
    'mdate' => $timestamp,
    'list_order' => $list_order,
    );

b. for update field value from database same page line  315(function update(&$d))

                       if (vmGet($d,'accesscat')=='')
                          {
                 $waccess='N';
              }else{
                 $waccess='Y';
              }

$fields = array('category_name' => vmGet( $d, 'category_name' ),
           'category_publish' => vmGet( $d, 'category_publish' ),
           'category_description' => vmGet( $d, 'category_description', '',VMREQUEST_ALLOWHTML ),
       'category_browsepage' => vmGet( $d, 'category_browsepage' ),
                                        'products_per_row' => vmRequest::getInt( 'products_per_row' ),
                                        'cat_wholesaler'=> $waccess,
                                        'category_flypage' => vmGet( $d, 'category_flypage' ),
                                        'category_thumb_image' => vmGet( $d, 'category_thumb_image' ),
                                        'category_full_image' => vmGet( $d, 'category_full_image' ),
                                        'mdate' => $timestamp,
                                        'list_order' => vmRequest::getInt('list_order'),
                                    );


lastly enloy your custom field has been added you can insert value and update successfully in virtuemart

Thursday, October 4, 2012

How to prevent mysql injection in Php before it is submitted



SQL injection refers to the act of someone inserting a MySQL statement to be run on your database without your knowledge. Injection usually occurs when you ask a user for input, like their name, and instead of a name they give you a MySQL statement that you will unknowingly run on your database.

 This is the important bit, we take the $username and $password variables that we just filled with data, and we use the function mysql_real_escape_string
on it, what this does is remove and characters that should not be in there, it actually does the same job as stripslashes() apart from this is the correct
method used for MYSQL Databases.

The rest of the code is pretty much self explanatory, after we have checked all the data and made it A-Z characters, we then perform the mysql
query on the database and then we just check the returned information with a series of IF statement, these are all very self explanatory.

This concludes this article, for more information on this subject, checkout www.php.net this website is filled with information on everything php.

Use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.
You basically have two options to achieve this:
  1. Using PDO:
    $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
    
    $stmt->execute(array(':name' => $name));
    foreach ($stmt as $row) {
        // do something with $row
    }
    
  2. Using mysqli:
    $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
    $stmt->bind_param('s', $name);
    
    $stmt->execute();
    
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        // do something with $row
    }
    

PDO

Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:
$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass');

$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
In the above example the error mode isn't strictly necessary, but it is advised to add it. This way the script will not stop with a Fatal Error when something goes wrong. And gives the developer the chance to catch any error(s) (which are throwed as PDOExceptions.
What is mandatory however is the setAttribute() line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren't parsed by PHP before sending it the the MySQL server (giving a possible attacker no chance to inject malicious SQL).
Although you can set the charset in the options of the constructor it's important to note that 'older' versions of PHP (< 5.3.6) silently ignored the charset parameter in the DSN.

Explanation

What happens is that the SQL statement you pass to prepare is parsed and compiled by the database server. By specifying parameters (either a ? or a named parameter like :name in the example above) you tell the database engine where you want to filter on. Then when you call execute the prepared statement is combined with the parameter values you specify.
The important thing here is that the parameter values are combined with the compiled statement, not a SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters you limit the risk of ending up with something you didn't intend. Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the $name variable contains 'Sarah'; DELETE * FROM employees the result would simply be a search for the string "'Sarah'; DELETE * FROM employees", and you will not end up with an empty table.
Another benefit with using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.
Oh, and since you asked about how to do it for an insert, here's an example (using PDO):
$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');

$preparedStatement->execute(array(':column' => $unsafeValue));




 

MySQL & PHP Code:

// a good user's name
$name = "timmy"; 
$query = "SELECT * FROM customers WHERE username = '$name'";
echo "Normal: " . $query . "<br />";

// user input that uses SQL Injection
$name_bad = "' OR 1'"; 

// our MySQL query builder, however, not a very safe one
$query_bad = "SELECT * FROM customers WHERE username = '$name_bad'";

// display what the new query will look like, with injection
echo "Injection: " . $query_bad; 
 

Display:

Normal: SELECT * FROM customers WHERE username = 'timmy'
Injection: SELECT * FROM customers WHERE username = '' OR 1'' 
 
 

MySQL & PHP Code:

//NOTE: you must be connected to the database to use this function!
// connect to MySQL

$name_bad = "' OR 1'"; 

$name_bad = mysql_real_escape_string($name_bad);

$query_bad = "SELECT * FROM customers WHERE username = '$name_bad'";
echo "Escaped Bad Injection: <br />" . $query_bad . "<br />";


$name_evil = "'; DELETE FROM customers WHERE 1 or username = '"; 

$name_evil = mysql_real_escape_string($name_evil);

$query_evil = "SELECT * FROM customers WHERE username = '$name_evil'";
echo "Escaped Evil Injection: <br />" . $query_evil;

Display:

Escaped Bad Injection:
SELECT * FROM customers WHERE username = '\' OR 1\''
Escaped Evil Injection:
SELECT * FROM customers WHERE username = '\'; DELETE FROM customers WHERE 1 or username = \''
 
 

prime number using for loop in php





php using prime number program
for($i=2;$i<50;$i++){
$counter=0;
for($j=2;$j<$i;$j++){
if($i%$j==0){
$counter++;
break;
}
}
// you can check instead if($i==$j)
if($counter==0){
echo $i.",";
}
}

what is main difference between php4 and php5




PHP5 introduces many new features, I have mentioned some of them:

Unified Constructors and Destructors:
In PHP4, constructors had same name as the class name. In PHP5, you have to name your constructors as  __construct() and  destructors as __destruct().



Abstract:
In PHP5 you can declare a class as Abstract.

Startic Methods and properties:
Static methods and properties are also available. When you declare a class member as static, then you can access members using :: operator without  creating an instance of class.

_autoload()
PHP5 introduces a special function called __autoload()

Final:
PHP5 allows you to declare a class or method as Final 

Magic Methods
PHP5 introduces a number of magic methods.
__call, __get, __set and __toString

Visibility:
In PHP5, There are 3 levels of visibilities:
    Public: Methods are accessible to everyone including objects outside the classes.
    Private: only available to the class itself.
    Protected: accessible to the class itself and inherited class.

Exception:
PHP5 has introduced ‘exceptions’(exception errors)

Passed by reference
In PHP4, everything was passed by value, including objects. Whereas in PHP5, all objects are passed by reference.

Interfaces:
PHP5 introduces interfaces . An interface defines the methods a class must implement. All the methods defined in an interface must be public.

E_STRICT Error Level
PHP5 introduces new error level defined as ‘E_STRICT’
E_STRICT will notify you when you use depreciated code.

PHP5 also introduces new default extensions.

  •     SimpleXML: for easy processing of XML data
  •     DOM and XSL
  •     PDO .
  •     Hash :gives you access to a ton of hash functions.
New Functions
PHP5 introduces new functions. You can get a list of them from the PHP Manual.





PHP5 is a lot different than PHP4. With the vastly improved Object Oriented model in PHP5, PHP is now a lot closer to a fully fledged object orientated programming language and looks more like ASP.NET now. Here are 10 major differences between PHP4 and PHP5 that you need to know:
1. Unified Constructors and Destructors:
In PHP4, constructors had same name as the class name. This used to cause overhead because every time you changed the class name, you had to change all the occurrences of that name.
In PHP5, you simply need to name your constructors as __construct(). (the word ‘construct’ prefixed by double underscores). Similarly you can name your destructors as __destruct(). (the word ‘destruct’ prefixed by double underscores.) In destructors, you can write code that will get executed when the object is destroyed.
2. Abstract Class:
PHP5 lets you declare a class as ‘Abstract’. (i.e. a class whose object cannot be created. You can only extend an abstract class) Also, a class must be defined as abstract if it contains any abstract methods. And those abstract methods must be defined within the class which extend that abstract class. You can include complete method definitions within the abstract methods of abstract class.
3. Final Keyword:
PHP5 allows you to declare a class or method as ‘Final’ now. You just need to use ‘final’ keyword that will indicate that the class cannot be inherited or the method cannot be overridden.
4. Exception Handling:
PHP5 has introduced ‘exceptions’. An exception is simply a kind of error and the ‘exception error’ can be handled in an exception object. By using an exception, one can gain more control over the simple trigger_error notices we were stuck with before.
When you are about to perform something ‘risky’ in your code, you can surround your code with a ‘try…catch’ block. First you surround your code in a ‘try {…….}’ block, then if an exception is thrown, your following ‘catch{……}’ block is there to intercept the error and handle it accordingly. You can write some PHP code in your ‘catch’ block which will get executed when an error occurs in the ‘try’ block. If there is no ‘catch’ block, a fatal error occurs.
5. E_STRICT Error Level:
PHP5 introduces new error level defined as ‘E_STRICT’ (value 2048). This error levels notifies you when you use depreciated PHP code. It is not included in E_ALL, if you wish to use this new level you must specify it explicitly.
6. Autoloading (the __autoload() function):
PHP5 introduces a special function called ‘__autoload()’ (the word ‘autoload’ prefixed by double underscores). This function allows you to avoid writing a long list of includes at the top of your script by defining them inside this function. So you can automatically load object files when PHP encounters a class that hasn’t been defined yet.
Example:
function __autoload ($class_name) {
include $class_name . '.php';
}
7. Visibility:
In PHP5, class methods and properties now have ‘visibility’. There are 3 levels of visibilities:
Public: ‘Public’ is the most visible. Methods are accessible to everyone including objects outside the classes. And properties readable and writable by everyone including objects outside the classes.
Private: ‘Private’ makes class members only available to the class itself.
Protected: ‘Protected’ makes class members accessible to the class itself and any inherited class (subclass) as well as any parent classes.
PHP4′s method of declaring a variable as ‘var’ keyword is still supported in PHP5. The ‘var’ keyword is now a synonym for the ‘public’ keyword now.
8. Pass by Reference:
In PHP4, everything was passed by value, including objects. Whereas in PHP5, all objects are passed by reference. Take a look at this PHP4 code for example -
$peter = new Person();
$peter->sex = ’male’;
$maria = $peter;
$maria->sex = ’female’;
echo $peter->sex; // This will output ‘female’
As you can see in the code above, if you wanted to duplicate an object in PHP4, you simply copied it by assigning it to another variable (Pass by value). But now in PHP5 you must use the new ‘clone’ keyword. So the above PHP4 code, will now look like this in PHP5 -
$peter = new Person();
$maria = new Person();
$peter->sex = ’male’;
$maria = clone $peter;
$maria->sex = ’female’;
echo $peter->sex; // This will output ‘female’
9. Interfaces:
PHP5 introduces ‘interfaces’ . An interface defines the methods a class must implement. All the methods defined in an interface must be public. An interface helps you design common APIs. It is not designed as a blueprint for classes, but just a way to standardize a common API. A big advantage of using interfaces is that a class can implement any number of interfaces. You can still only ‘extend’ on parent class, but you can ‘implement’ an unlimited number of interfaces.
10. New Functions:
PHP5 introduces new functions which are not found in PHP4. You can find the list of these new functions in the PHP manual.

Difference between MySQL function and mysql procedure

 


 

 

What are the differences between stored procedure and functions in mysql

A FUNCTION is always returns a value using the return 
statement. A  PROCEDURE may return one or more values 
through parameters or may not return at all.
b. Functions are normally used for computations where as 
procedures are normally used for executing business logic.
c. A Function returns 1 value only. Procedure can return 
multiple values (max 1024).
d. Stored procedure returns always integer value by default 
zero. Whereas function returns type could be scalar or 
table or table values
e. Stored procedure is precompiled execution plan where as 
functions are not.
f. A function can call directly by SQL statement like 
select func_name from dual while procedure cannot.
g.Stored procedure has the security and reduces the network 
traffic and also we can call stored procedure in any no. of 
applications at a time.
h. A Function can be used in the SQL Queries while a 
procedure cannot be used in SQL queries .that cause a major 
difference b/w function and procedures.
 
--------------------------------  
 
Stored procedures are a set of actions already written and 
stored inside the database for acheiving a particular task 
where as functions are general database objects which are 
used for general purpose programming
 
there are 3 main differences between sp and function.
1 sp takes input,output parameters, function takes only 
input parameters.
2 temparary variables required to store return values of 
sp. in functions temparary variables will be optinale.
3 sp can not be called directly into DML statements , 
functions can be called directly into DML statements.
   
 
1. Functions can be used inline with a select statement 
while sprocs can't.

2. EXEC command can't be used inside a Function where it 
can be used inside an sproc.



Function :
1. Should return atleast one output parameter.Can return more than one parameter using OUT argument.
2. Parsed and compiled at runtime.
3.Cannot affect the state of database.
4.Can be invoked from SQL statement e.g. SELECT.
5. Functions are mainly used to compute values.
Procedure:
1. Doesn't need to return values, but can return value.
2.Stored as a pseudo-code in database i.e. compiled form.
3.Can affect the state of database using commit etc.
4.Cannnot be invoked from SQL statements e.g. SELECT.
5.Procedures are mainly used to process the tasks

difference between unset and unlink in php



unlink() is used to delete physical files...So lets say you have foo.txt somewhere on your server... unlink(foo.txt) would delete it. unset() is used to null out the value of a given variable. So for instance:

x = 200;

echo(x); // 200

unset(x);

echo(x); // null


The difference between the functions unlink and unset
unlink() is a function for file system handling.
It will simply delete the file in context.

Example for unlink() :

<?php
$fh = fopen('test.html', 'a');
fwrite($fh, '<h1>Hello world!</h1>');
fclose($fh);

unlink('test.html');
?>



unset() is a function for variable management.
It will make a variable undefined.
(or)

Unset () is used to destroy a variable in PHP. In can be used to remove a single variable, multiple variables, or an element from an array. It is phrased as Unset ($remove).
Also Known As: Unset Variable, Destroy Variable

Example for unset() :

<?php
// remove a single variable
unset($a);

// remove a single element in an array
unset($my_array['element']);

// remove multiple variables
unset($a, $b, $c);
?>

Wednesday, October 3, 2012

retrive frineds list from facebook and post wall easlly




1stp-> create app for your website from facebook


2stp->download facebook library class file and put your connection  information

3rd-> call facebook class object and pass for friend list

4rth->get your friends list from facebook
lastly you post wall to your friends wall

Saturday, September 29, 2012

Difference between session_register and $_SESSION[] in phpsession_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.


We know that Webpages are getting displayed using stateless Protocol.
So there should be someway for keeping the session of the user navigating the webpages within a website.

Session variables and Cookie variables can be used for this purpose.
Basically Session variables are maintained by webserver. (i-e)Physically the value of any Session variable will be written to a file located in the web server.

In php, we can set/use the session variable using $_SESSION. Say for example, if we need to put the user email (e.g $email) in session, we can use it as $_SESSION['email'] whose value should be set as $_SESSION['email']=$email.

Whenever assigning this session variable, a file will be written to the web server at location specified by session_path variable in php.ini file.

Suppose 1000 users are using your website, there will be 1000 files created for storing one session variable.

So it will become a big memory issue if you are not managing the session properly. (i-e) we should unset the session variables during logout. Appropriate session timeout value should be specified to enable automatic expiration of the session if the user forgets to logout. And also we need to take additional care to manage session if security is more important for your website.

Or alternatively we can use cookie variables which are stored by the web browser in the users machine. As the cookie variables are stored in the client machine, it can be available till it gets deleted either by browser setting, or by the code or by the user manually.

Since cookie variables can live even after closing the browser session, it can be very useful for improving user experience. (i-e) Lot of data related to user preferences can be stored in the cookie. So whenever the same user logs in, his previous settings can be applied automatically by using these cookie values. For example if the user allows the website to store his password in cookie variable, he can log in to the website without typing his password again.

In php, cookie variables can be set using setcookies function. 
But anyway, privacy is important for you, you can restrict the cookies by changing the browser settings.
More Articles...

Thursday, September 27, 2012

PHP and MySQL Stored Procedure Exec Problem

  • <?php
  • $Server = "127.0.0.1";
  • $DataBase = "tedt";
  • $UserName = "root";
  • $PassWord = "124@#";
  • $Conn = mysqli_connect($host, $UserName, $PassWord);
  • if(!$Conn)
  • {
  • die("Could not connect to server : " . mysqli_error());
  • }
  • else
  • {
  • mysqli_select_db($Conn,$DataBase) or die("Could not connect to database");
  • }
  • ?>
  • <?php
  • print "Procedure #1";
  • $res= $Conn->query("CALL storepro;");
  • print_r($res) ;
  • ?>

    Monday, September 24, 2012

    json using php tutorial

    After reading this post, you will be able to understand, work and test JSON code with PHP.
    There are already lots of tutorials out there on handling JSON with PHP, but most of them don't go much deeper than throwing an array against json_encode and hoping for the best. This article aims to be a solid introduction into JSON and how to handle it correctly in combination with PHP. Also, readers who don't use PHP as their programming language can benefit from the first part that acts as a general overview on JSON.
    JSON (JavaScript Object Notation) is a data exchange format that is both lightweight and human-readable (like XML, but without the bunch of markup around your actual payload). Its syntax is a subset of the JavaScript language that was standardized in 1999. If you want to find out more, visit the official website.
    The cool thing about JSON is that you can handle it natively in JavaScript, so it acts as the perfect glue between server- and client-side application logic. Also, since the syntactical overhead (compared to XML) is very low, you need to transfer less bytes of ther wire. In modern web stacks, JSON has pretty much replaced XML as the de-factor payload format (aside from the Java world I suppose) and client side application frameworks like backbone.js make heavy use of it inside the model layer.
    Before we start handling JSON in PHP, we need to take a short look at the JSON specification to understand how it is implemented and what's possible.

    Introducing JSON

    Since JSON is a subset of the JavaScript language, it shares all of its language constructs with its parent. In JSON, you can store unordered key/value combinations in objects or use arrays to preserve the order of values. This makes it easy to parse and to read, but also has some limitations. Since JSON only defines a small amount of data types, you can't transmit types like dates natively (you can, but you need to transform them into a string or a unix timestamp as an integer).
    So, what datatypes does JSON support? It all boils down to strings, numbers, booleans and null. Of course, you can also supply objects or arrays as values.
    Here's a example JSON document:
    1. {
    2. "title": "A cool blog post",
    3. "clicks": 4000,
    4. "children": null,
    5. "published": true,
    6. "comments": [
    7. {
    8. "author": "Mister X",
    9. "message": "A really cool posting"
    10. },
    11. {
    12. "author": "Misrer Y",
    13. "message": "It's me again!"
    14. }
    15. ]
    16. }
    It contains basically everything that you can express through JSON. As you can see no dates, regexes or something like that. Also, you need to make sure that your whole JSON document is encoded in UTF-8. We'll see later how to ensure that in PHP. Due to this shortcomings (and for other good reasons) BSON(Binary JSON) was developed. It was designed to be more space-efficient and provides traversability and extensions like the date type. Its most prominent use case is MongoDB, but honestly I never came across it somewhere else. I recommend you to take a short look at the specification if you have some time left, since I find it very educating.
    Since PHP has a richer type handling than JSON, you need to prepare yourself to write some code on both ends to transform the correct information apart from the obligatory encoding/decoding step. For example, if you want to transport date objects, you need to think if you can just send a unix timestamp over the wire or maybe use a preformatted date string (like strftime).

    Encoding JSON in PHP

    Some years ago, JSON support was provided through the json pecl extension. Since PHP 5.2, it is included in the core directly, so if you use a recent PHP version you should have no trouble using it.
    Note: If you run an older version of PHP than 5.3, I recommend you to upgrade anyway. PHP 5.3 is the oldest version that is currently supported and with the latest PHP security bugs found I would consider it critical to upgrade as soon as possible.
    Back to JSON. With json_encode, you can translate anything that is UTF-8 encoded (except resources) from PHP into a JSON string. As a rule of thumb, everything except pure arrays (in PHP this means arrays with an ordered, numerical index) is converted into an object with keys and values.
    The method call is easy and looks like the following:
    1. json_encode(mixed $value, int $options = 0);
    An integer for options you might ask? Yup, that's called a bitmask. We'll cover them in a separate part a little bit later. Since these bitmask options change the way the data is encoded, for the following examples assume that we use defaults and don't provide custom params.
    Let's start with the basic types first. Since its so easy to grasp, here's the code with short comments on what was translated:
    1. <?php
    2. // Returns: ["Apple","Banana","Pear"]
    3. json_encode(array("Apple", "Banana", "Pear"));
    4.  
    5. // Returns: {"4":"four","8":"eight"}
    6. json_encode(array(4 => "four", 8 => "eight"));
    7.  
    8. // Returns: {"apples":true,"bananas":null}
    9. json_encode(array("apples" => true, "bananas" => null));
    10. ?>
    How your arrays are translated depends on your indexes used. You can also see that json_encode takes care of the correct type conversion, so booleans and null are not transformed into strings but use their correct type. Let's now look into objects:
    1. <?php
    2. class User {
    3. public $firstname = "";
    4. public $lastname = "";
    5. public $birthdate = "";
    6. }
    7.  
    8. $user = new User();
    9. $user->firstname = "foo";
    10. $user->lastname = "bar";
    11.  
    12. // Returns: {"firstname":"foo","lastname":"bar"}
    13. json_encode($user);
    14.  
    15. $user->birthdate = new DateTime();
    16.  
    17. /* Returns:
    18.   {
    19.   "firstname":"foo",
    20.   "lastname":"bar",
    21.   "birthdate": {
    22.   "date":"2012-06-06 08:46:58",
    23.   "timezone_type":3,
    24.   "timezone":"Europe\/Berlin"
    25.   }
    26.   }
    27. */
    28. json_encode($user);
    29. ?>
    Objects are inspected and their public attributes are converted. This happens recursively, so in the example above the public attributes of the DateTime object are also translated into JSON. This is a handy trick if you want to easly transmit datetimes over JSON, since the client-side can then operate on both the actual time and the timezone.
    1. <?php
    2. class User {
    3. public $pub = "Mister X.";
    4. protected $pro = "hidden";
    5. private $priv = "hidden too";
    6.  
    7. public $func;
    8. public $notUsed;
    9.  
    10. public function __construct() {
    11. $this->func = function() {
    12. return "Foo";
    13. };
    14. }
    15. }
    16.  
    17. $user = new User();
    18.  
    19. // Returns: {"pub":"Mister X.","func":{},"notUsed":null}
    20. echo json_encode($user);
    21. ?>
    Here, you can see that only public attributes are used. Not initialized variables are translated to null while closures that are bound to a public attribute are encoded with an empty object (as of PHP 5.4, there is no option to prevent public closures to be translated).

    The $option bitmasks

    Bitmasks are used to set certain flags on or off in a function call. This language pattern is commonly used in C and since PHP is written in C this concept made it up to some PHP function arguments as well. It's easy to use: if you want to set an option, just pass the constant as an argument. If you want to combine two or more options, combine them with the bitwise OR operation |. So, a call to json_encode may look like this:
    1. <?php
    2. // Returns: {"0":"Starsky & Hutch","1":123456}
    3. json_encode(array("Starsky & Hutch", "123456"), JSON_NUMERIC_CHECK | JSON_FORCE_OBJECT);
    4. ?>
    JSON_FORCE_OBJECT forces the array to be translated into an object and JSON_NUMERIC_CHECK converts string-formatted numbers to actual numbers. You can find all bitmasks (constants) here. Note that most of the constants are available since PHP 5.3 and some of them were added in 5.4. Most of them deal with how to convert characters like < >, & or "". PHP 5.4 provides a JSON_PRETTY_PRINT constant that may you help during development since it uses whitespace to format the output (since it adds character overhead, I won't enable it in production of course).

    Decoding JSON in PHP

    Decoding JSON is as simple as encoding it. PHP provides you a handy json_decode function that handles everything for you. If you just pass a valid JSON string into the method, you get an object of type stdClass back. Here's a short example:
    1. <?php
    2. $string = '{"foo": "bar", "cool": "attr"}';
    3. $result = json_decode($string);
    4.  
    5. // Result: object(stdClass)#1 (2) { ["foo"]=> string(3) "bar" ["cool"]=> string(4) "attr" }
    6. var_dump($result);
    7.  
    8. // Prints "bar"
    9. echo $result->foo;
    10.  
    11. // Prints "attr"
    12. echo $result->cool;
    13. ?>
    If you want to get an associative array back instead, set the second parameter to true:
    1. <?php
    2. $string = '{"foo": "bar", "cool": "attr"}';
    3. $result = json_decode($string, true);
    4.  
    5. // Result: array(2) { ["foo"]=> string(3) "bar" ["cool"]=> string(4) "attr" }
    6. var_dump($result);
    7.  
    8. // Prints "bar"
    9. echo $result['foo'];
    10.  
    11. // Prints "attr"
    12. echo $result['cool'];
    13. ?>
    If you expect a very large nested JSON document, you can limit the recursion depth to a certain level. The function will return null and stops parsing if the document is deeper than the given depth.
    1. <?php
    2. $string = '{"foo": {"bar": {"cool": "value"}}}';
    3. $result = json_decode($string, true, 2);
    4.  
    5. // Result: null
    6. var_dump($result);
    7. ?>

    Tuesday, September 18, 2012

    curl service example in php

    <?php
    
    $ch = curl_init("http://rss.news.yahoo.com/rss/oddlyenough");
    $fp = fopen("example_homepage.html", "w");
    
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    
    curl_exec($ch);
    curl_close($ch);
    fclose($fp);
    
    $xml = simplexml_load_file('example_homepage.html');
    print "<ul>\n";
    foreach ($xml->channel->item as $item){
      print "<li>$item->title</li>\n";
    }
    print "</ul>";
    
    ?>