Thursday, December 18, 2014

How to log in/out Magento user to Wordpress blog - II

In the previous article How to log in/out Magento user to Wordpress blog - I, we have discussed how we can create Wordpress user during Magento 1.8 customer sign-up. Now we would check how we can make the user log in/out into/from Wordpress when the user signs in/out to/from Magento 1.8. 

As Wordpress functions are not available within Magento, we need to create a normal PHP page where we can include Wordpress core classes and use Wordpress functions for log in/out. So, when we call custom_login_wp.php?username=chandan&password=test123, this file calls Wordpress methods to log the user into Wordpress. Similarly, when we call custom_login_wp.php?logout=1 it logs the user out from Wordpress.

Our Wordpress folder is "wp" inside the Magento installation. We are creating this file "custom_login_wp.php" inside the "wp" folder, but it can be created anywhere. 

Let's check out the code in custom_login_wp.php.

<?php
// Include the  Wordpress Core
require("wp-load.php");   

// LOG OUT

if( isset($_GET['logout']) && $_GET['logout']== 1)
{
    // Log Out existing user
  if ( is_user_logged_in() ) { wp_logout(); }
    
}

// LOG IN

// Find URL Parameters in the URL
if(isset($_GET['username']) && $_GET['username']!="" && isset($_GET['password']) && $_GET['password']!="")
{
  
  // Log Out existing user
  if ( is_user_logged_in() ) { wp_logout(); }

  // GET Login Data from URL

  $creds = array();
  $creds['user_login']    = $_GET['username'];
  $creds['user_password'] = $_GET['password'];
  $creds['remember'] = false;

  // Wordpress LOGIN method
  $user = wp_signon( $creds, false );

  // ERROR  
  if ( is_wp_error($user) )
  {
   echo $user->get_error_message(); 
  }
}

// Always return the user to where

// Magento wanted to redirect
header("location:" . $_GET['current_url'] );
?>

The last line is a redirect; we better redirect the user to a URL where Magento user goes after a successful log in. So, in that case we need to call the custom_login_wp.php as shown below ::

custom_login_wp.php?username=chandan&password=test123&current_url=http://example.com/customer/account

Check out the "current_url" parameter ... it specifies where to return within Magento after Wordpress Log in.

Some points to be noticed here :

1. To Log any Wordpress user out, we use Wordpress function wp_logout()
2. To check if any user is logged in, we use Wordpress function is_user_logged_in()
3. To Log a user in, we use Wordpress function wp_signon()

Next let's check out the "loginPostAction()" method in Mage Customer's AccountController.php file which is responsible for logging the user into Magento. We need to append our Wordpress Login code to this method. We just need to remember here that during Wordpress signup, we had used the user's Firstname as Wordpress username and user's Magento password as Wordpress password. Here is the loginPostAction() method. 

<?php
public function loginPostAction()
{
  ...

  try 
  {
    $session->login($login['username'], $login['password']);

    if ($session->getCustomer()->getIsJustConfirmed()) 
    {
  $this->_welcomeCustomer($session->getCustomer(), true);
    }

    ////*** OUR CUSTOM CODE STARTS HERE **////
    /// At this position, user is successfully
    /// Logged into Magento, Now it's our scope to
    /// log the user into Wordpress
    /// Let's get username and password

    $customer       = $session->getCustomer();
    $first_name     = $customer->getFirstname();
    $user_pwd       = $login['password'];

    /// Build URL to our custom page "custom_login_wp.php"
    $base_url = str_replace("/index.php","",Mage::getBaseUrl()) ;
    $target_url = $base_url . "wp/custom_login_wp.php?username=$first_name&password=$user_pwd&current_url=";

    // Check if Magento redirects to DashBoard
    $rdrct2Dashb = Mage::getStoreConfigFlag( Mage_Customer_Helper_Data::XML_PATH_CUSTOMER_STARTUP_REDIRECT_TO_DASHBOARD );

    // If Not DashBoard
    if(!$rdrct2Dashb)
    {
        $p = $base_url;
    }
    // Redirect to CUstomer DashBoard
    else
    {
        $p = "{$base_url}index.php/customer/account";
    }

    // Final URL is ready
    $target_url .= $p;


    //// REDIRECT User for a WORDPress Login
    if (!headers_sent()) 
    {
header( "Location:$target_url" ); exit;
    }
    ////*** OUR CUSTOM CODE ENDS HERE ***////

 } 
 catch (Mage_Core_Exception $e) 
 {
...
 } 
 catch (Exception $e) 
 {
...
 }

 ...
}
?>

Some points need to be noticed here : 

1. We take the Magento user's first name as Wordpress username. We get the user's first name with the statement $customer->getFirstname();
2. We extract the password user gives at Magento login prompt from the POST data stored in $login['password'].
3. In Magento Admin Panel, there is a provision to choose whether the customer will be redirected to Dashboard after login. So, we get that option's value by calling Mage::getStoreConfigFlag() with appropriate parameter. So, if that option is set to 'Yes', we would redirect the customer to Dashboard after we Log him into Wordpress (in custom_login_wp.php). Any other logic can be easily implemented here also.

Next, we would look into the Logout part. The Magento method logoutAction() inside Mage_Customer's AccountController.php file, is called when Magento user is logged out. So, we need to call the same file custom_login_wp.php we have written earlier with parameter "logout=1". 

Check out the code below. 

<?php
public function logoutAction()
{
  $this->_getSession()->logout()->renewSession();

  ///**** Our Custom Code Starts ****//
  /// LOG OUT the USER from WordPress also
  /// Build the URL
  $base_url = str_replace("/index.php","",Mage::getBaseUrl()) ;
  $return_url = rtrim($base_url,"/") . "/index.php/customer/account/logoutSuccess/";
  
  $target_url = $base_url . "wp/custom_login_wp.php?logout=1&current_url=" . $return_url;

  if (!headers_sent()) 
  {
  header( "Location:$target_url" ); exit;
  }
  
  ///**** Our Custom Code Ends ****//
  $this->_redirect('*/*/logoutSuccess');
}
?>

Hope this helps. Another thing, we should not modify core files. It is always a good practice to create our own module to do such custom coding. Check the article "How to override Customer Account controller in Magento 1.8" to see how we can create our own Customer module extending the original Mage Customer module.

Monday, December 08, 2014

How to log in/out Magento user to Wordpress blog - I

This is a case where Wordpress blog is integrated inside Magento and we want a single sign-up/login/logout for users. It means the following things ::

1. Wordpress is installed in any subfolder within Magento installation.
2. When a user signs up for Magento, he is automatically signs up for Wordpress. Actually a new user needs to be created manually in Wordpress.
3. When a user logs on in Magento, he is also logs in Wordpress.
4. When a logged-in user logs out from Magento, he is also logged out from Wordpress.

As Magento user is automatically registered to Wordpress, the default Wordpress sign-up/registration should be disabled. To disable wordpress sign-up, we need to go to Settings > General in Wordpress Admin Panel and uncheck the option "Anyone Can Register".

Now, for our working, we need to know that sign-up, login and logout procedures are handled by AccountController.php inside the path app/code/core/Mage/Customer/controllers. So, the module name is Mage_Customer and the controller class name is Mage_Customer_AccountController.

We need to edit the AccountController.php and put our custom code inside it. Let's check out the registration process. There is an action called "createPostAction" which registers a Magento user. The form on registration page has an action "http://127.0.0.1/magento/customer/account/createpost/" (on my local machine), so the function createPostAction() is responsible for creating the customer account.  

First check out the final code below, then analyze it. Our Custom code is shown in blue below. Whole function is not shown below... only the section where customization is needed is shown.

<?php
public function createPostAction()
{
  ......
 
  $customer = $this->_getCustomer();

  // GET CUSTOMER PASSWORD
  $pwd = $this->getRequest()->getPost('password'); 

  try 
  {
    $errors = $this->_getCustomerErrors($customer);
         if (empty($errors)) 
    {

$customer->save();
$this->_dispatchRegisterSuccess($customer);

// PUT The password in SESSION
// So That we can LOG him in WordPress also
Mage::getSingleton('core/session')->setPwd($pwd);

$this->_successProcessRegistration($customer);
return;
    } 
    else 
    {
$this->_addSessionError($errors);
    }
  } 
  catch (Mage_Core_Exception $e) 
  {
     ...
  }

  catch (Exception $e) 
  {
     ...
  }
?>

The above piece of code accepts user inputs, processes and validates by calling other functions like _getCustomerErrors(), and finally saves the new customer (if everything is fine) information to DB through the statement $customer->save() and finally calls the _successProcessRegistration() function to show Success Message, send mails and other tasks. Now we are supposed to create a Wordpress account with an username and password; username can be created from user's first name which can be retrieved any time, it is difficult to retrieve the password. Hence we had to receive the password from the user and put it on session. Now  let's make a little changes to the function _successProcessRegistration().

<?php
protected function _successProcessRegistration(Mage_Customer_Model_Customer $customer)
{
  $session = $this->_getSession();
  if ($customer->isConfirmationRequired()) 
  {
     ...

     // at the end of existing code 
     // INSERT the USER into WORDPRESS
     $this->insertToWordpress( $customer, $c );
  } 
  else 
  {

     // before the existing code
     // INSERT the USER into WORDPRESS
     $this->insertToWordpress( $customer, $c );

     ...
  }

  $this->_redirectSuccess($url);
  return $this;
}
?>

So, we just call our custom function insertToWordpress() from within _successProcessRegistration() to create new wordpress user. Check out the code for insertToWordpress() below.

<?php
protected function insertToWordpress(Mage_Customer_Model_Customer $customer, $customer_group)
{
 
  // Create Capabilities
  $usr_typ_arr["author"] = true;
  
  $session = $this->_getSession();

  // Customer ID
  $Magento_customer_ID = $customer -> getId();  
  
  // GET Tables 
  $wp_user_table = "wp_users";
  $wp_usermeta_table = "wp_usermeta";
  
  // GET Fields which will be written to USER TABLE
  $user_login      = $customer->getFirstname();
  $user_pass       = md5( Mage::getSingleton('core/session')->getPwd() );
  $user_nicename   = $user_login;
  $user_email      = $customer->getEmail();
  $user_url        = "";
  $user_registered = date("Y-m-d h:i:s");
  $user_activation_key = "";
  $user_status     = 0;
  $display_name    = $user_login;
  
  // Unset PASSWORD from SESSION
  Mage::getSingleton('core/session')->unsPwd();
  
  // DEFINE DB Handle
  // To read from the database
  $read  = Mage::getSingleton( 'core/resource' )->getConnection( 'core_read' ); 
  // To write to the database
  $write = Mage::getSingleton( 'core/resource' )->getConnection( 'core_write' ); 
  
  // GET Table Name
  $userTable = Mage::getSingleton( 'core/resource' )->getTableName( $wp_user_table );
  
  $userMetaTable = Mage::getSingleton( 'core/resource' )->getTableName( $wp_usermeta_table );
  
  // INsert into USER Table
  $query = "INSERT into " . $userTable . " values ('', '$user_login', '$user_pass', '$user_nicename', '$user_email', '$user_url', '$user_registered', '$user_activation_key', '$user_status', '$display_name')";
  $write->query( $query );
  
  // GET Last Insert ID (user ID)
  $last_insert_id = $write->lastInsertId();
  
  // BUIL SQL for Inserting into user Meta Table
  $q = array();
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'first_name','".$customer->getFirstname()."')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'last_name','".$customer->getLastname()."')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'nickname','$user_nicename')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'description','')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'rich_editing','true')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'comment_shortcuts','false')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'admin_color', 'fresh')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'use_ssl', '0')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'show_admin_bar_front', 'true')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'wp_capabilities', '".serialize($usr_typ_arr)."')";
  
  // 2 for Author, who can manage/publish their content
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'wp_user_level', '2')"; 
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'dismissed_wp_pointers',  'wp350_media,wp360_revisions,wp360_locks,wp390_widgets')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'magento_user_id',  '$Magento_customer_ID')";
  
  // ACTUAL INSERT to User Meta Table
  for($i=0;$i<count($q);$i++) 
     $write->query( $q[$i] );

}
?>

The above function builds some values out of customer object, and then makes entries to wordpress "user" and "usermeta" tables. The "usermeta" table in Wordpres holds various information about the user including user capabilities and user level. As said earlier, we are using the customer's first name as Wordpress login name and Magento password as Wordpress password. After we create the Wordpress user, we unset the password we had put in session by calling Mage::getSingleton('core/session')->unsPwd();  

This way, we create users for both Magento and Wordpress. 

So, the Registration process is complete. For logging in/out simultaneously in Magento and Wordpress, check the part 2 of this article How to log in/out Magento user to Wordpress blog - II

Thursday, December 04, 2014

How to add custom attribute to Customer in Magento 1.8

For this we need to create a module. Check the article Building a basic Hello World module in Magento 1.8 to know how to build a basic module in Magento 1.8. 

So, now let's checkout the files we need to create this module. I am using my name "Chandan" as the Namespace name for my module and the module name is "ExtraCustomerAttributes". And I am going to add a field called 'isapproved' (Is Approved) to customer entity. With this field we can do various thing which can be discussed later. 

Here is the file list :

1. app/etc/modules/Chandan_ExtraCustomerAttributes.xml 
2. app/code/local/Chandan/ExtraCustomerAttributes/etc/config.xml 
3. app/code/local/Chandan/ExtraCustomerAttributes/sql/customerattribute_setup/mysql4-install-0.1.0.php

The above three files are just what we need to add our custom field to Customer. Now let's check out each of them one by one.

Here is the content for app/etc/modules/Chandan_ExtraCustomerAttributes.xml 

<?xml version="1.0"?>
<config>
  <modules>
    <Chandan_ExtraCustomerAttributes>
      <active>true</active>
      <codePool>local</codePool>
      <version>0.1.0</version>
    </Chandan_ExtraCustomerAttributes>
  </modules>
</config>

The file Chandan_ExtraCustomerAttributes.xml tells Magento that we have an active Module "Chandan_ExtraCustomerAttributes" which runs from 'local' code pool. "Chandan" is the namespace name and "ExtraCustomerAttributes" is the name of the module.

Next, let's check the content of app/code/local/Chandan/ExtraCustomerAttributes/etc/config.xml

<?xml version="1.0"?>
<config>
  <modules>
    <Chandan_ExtraCustomerAttributes>
      <version>0.1.0</version>
    </Chandan_ExtraCustomerAttributes>
  </modules>
  <global>
<resources>
 <customerattribute_setup>
<setup>
 <module>Chandan_ExtraCustomerAttributes</module>
 <class>Mage_Customer_Model_Entity_Setup</class>
</setup>
<connection>
 <use>core_setup</use>
</connection>
 </customerattribute_setup>
 <customerattribute_write>
<connection>
 <use>core_write</use>
</connection>
 </customerattribute_write>
 <customerattribute_read>
<connection>
 <use>core_read</use>
</connection>
 </customerattribute_read>
</resources>
  </global>
</config> 

And finally, here is the content of the file app/code/local/Chandan/ExtraCustomerAttributes/sql/customerattribute_setup/mysql4-install-0.1.0.php

This file creates necessary attribute for Customer. 

<?php
$installer = $this;
$installer->startSetup();

// new attribute name is 'isapproved'

// Type Integer
$installer->addAttribute("customer", "isapproved",  array(
    "type"     => "int",
    "backend"  => "",
    "label"    => "Is Approved",  
    "input"    => "select", 
    "source"   => "eav/entity_attribute_source_boolean", 
    "visible"  => true,
    "required" => false,
    "default"  => "No",
    "frontend" => "",
    "unique"   => false,
    "note"     => "To determine whether a customer is approved"

));


$attribute   = Mage::getSingleton("eav/config")->getAttribute("customer", "isapproved");


$used_in_forms = array();

$used_in_forms[] = "adminhtml_customer";

        
$attribute->setData("used_in_forms", $used_in_forms)
->setData("is_used_for_customer_segment", true)
->setData("is_system", 0)
->setData("is_user_defined", 1)
->setData("is_visible", 0)
->setData("sort_order", 100)
;

// Save Attribute

$attribute->save();

$installer->endSetup();
?>

When the mysql4-install-0.1.0.php file is executed, it creates entries in various tables. 

First, it created a row in "eav_attribute" table. I had the following row added to "eav_attribute" table. It is column-wise shown below.

attribute_id    => 961
entity_type_id  => 1
attribute_code  => isapproved
attribute_model => NULL
backend_model   => NULL
backend_type    => int
backend_table   => NULL
frontend_model  => NULL 
frontend_input  => select
frontend_label  => Is Approved
frontend_class  => NULL
source_model    => eav/entity_attribute_source_boolean
is_required     => 0
is_user_defined => 1
default_value   => No
is_unique       => 0
note            => To determine whether a customer is approved

In "eav_attribute" table, we have "entity_type_id" set to "1" for Customer; the "attribute_id" is having an auto value. Various entity types can be found in table "eav_entity_type". Customer Address (customer_address) is set to have id "2" and Customer Payment (customer_payment) has an Id of "3". For example, if we add address to a Customer from backend, the table "customer_address_entity" gets a new entry with "entity_type_id" set to "2".

Ok, now getting back to our module, in the file mysql4-install-0.1.0.php, there is a line :

 "source" => "eav/entity_attribute_source_boolean",

The "eav/entity_attribute_source_boolean" provides a selection of "Yes" or "No". 
"customer/entity_address_attribute_source_country" provides a list of Countries.

This section can be modified to accommodate custom values like "Processing...", "No Yet.." against our field/attribute "isapproved". We need to modify our code as shown below ... only the "source" section needs editing...

$installer->addAttribute("customer", "isapproved",  array(
    
     "source" => "eav/entity_attribute_source_table",
     "option"=> array(
                  "values" => array(
                     0 => "Processing...",
                     1 => "Banned Completely",
                     2 => "Not Yet",
     3 => "Approved",
4 => "Not Approved"
                   ),
                )
));

Notice that we have used "eav/entity_attribute_source_table" as "source" here. In this case, "eav_attribute_option" and "eav_attribute_option_value" tables would have entries to hold the configuration. The table "eav_attribute_option_value" would be storing the values "Processing...", "Not Yet" etc.

The table "eav_entity_attribute" also gets an entry with "attribute_id" set to 961 (reference to 'eav_attribute' table) and 'entity_type_id' set to "1". 

The table "customer_form_attribute" gets an entry with "attribute_id" set to 961 and "form_code" set to "adminhtml_customer" as specified in the statement above :

$used_in_forms[] = "adminhtml_customer";

Here, we define the form where the attribute to be saved.

We also get an entry in table "customer_eav_attribute".

Now, let's check whether our module is working or not. First of all, Magento would show our new module in the Module List. From System > Configuration > Advanced, I saw the following ::


Next, from Customers > Manage Customers at top menu, I opened a customer in Edit mode and I was able to see our newly created attribute with a label "Is Approved" as shown below ...



Hope this helps.

Monday, November 10, 2014

How to override Customer Account controller in Magento 1.8

I once had a requirement to change/modify or add new functionalities to the "Customer Account Controller" which is responsible for new registration, customer log in, log out, redirect to Customer dashboard, Forgot Password procedures etc. In such cases, we better not modify the core files directly. If we change the core files, all our work would get lost if Magento is upgraded to other versions. So, it is better if extend the core controllers and add our custom codes in it. This way our custom code would be there even if Magento is upgraded.

To achieve this, we would create a new module. The following points need to be remembered. 

To know how a basic 'Hello World' module is created in Magento, check this article "Building a basic Hello World module in Magento 1.8".

1. The controller which we want to override is: app/code/core/Customer/controllers/AccountController.php

2. Our new module name is "Newcustom_Customer" where "Newcustom" is the namespace name and "Customer" is our module name.

3. Next we create an xml file called "Newcustom_Customer.xml" inside app/etc/modules/Newcustom_Customer.xml 

4. So, we create a folder structure like this :: app/code/local/Newcustom/Customer and inside it, we create 2 more folders namely "etc" and "controllers".

5. Inside the app/code/local/Newcustom/Customer/etc folder, we create the configuration file for the module called config.xml

6. Inside the app/code/local/Newcustom/Customer/controllers folder, we copy paste the original app/code/core/Customer/controllers/AccountController.php

So, we need to work on mainly 3 files :: 

a. app/etc/modules/Newcustom_Customer.xml
b. app/code/local/Newcustom/Customer/etc/config.xml
c. app/code/local/Newcustom/Customer/controllers/AccountController.php

1. Let's start with the first file Newcustom_Customer.xml. It's content should be like this ::

<?xml version="1.0"?>
<config>
 <modules>
  <Newcustom_Customer>
    <active>true</active>
    <codePool>local</codePool>
  </Newcustom_Customer>
 </modules>
</config>

The above piece of XML tells Magento that this module would run from "app/code/local" codepool. 

2. Next check out the config.xml file for our module. 

<?xml version="1.0"?>
<config>
  <modules>
    <Newcustom_Customer>
      <version>0.1.0</version>
    </Newcustom_Customer>
  </modules>

  <frontend>
   <routers>
    <customer>
<use>standard</use>
     <args>
       <modules>
         <Newcustom_Customer before="Mage_Customer">Newcustom_Customer</Newcustom_Customer>
       </modules>
     </args>
    </customer>
   </routers>
  </frontend>
</config>

This XML would help to override the core Mage_Customer's controller.

3. And finally, the controller file itself (AccountController.php) needs to be modified. But it should extend the Mage_Customer's AccountController.php file's Mage_Customer_AccountController class.

<?php
// Include the Original Mage_Customer's AccountController.php file
// where the class 'Mage_Customer_AccountController' is defined
require_once Mage::getModuleDir('controllers', 'Mage_Customer').DS.'AccountController.php'; 

// Now extend the class 'Mage_Customer_AccountController'

class Newcustom_Customer_AccountController extends Mage_Customer_AccountController  
{

  // We can add more functionality

  public function test()
  {   

  }
  
  // Re-Write the Old Methods
  public function loginPostAction()
  {
        
  }      

}

?>

Now, we are done. As we have extended the original 'Mage_Customer_AccountController' class, all the original functions are automatically available to this new over-ridden controller. And we can still add some more functionality by adding our custom functions to our class.  Some points need to be noted here :

1. Check how our extended class is defined with a name "Newcustom_Customer_AccountController".
2. We are extending the original Mage_Customer's controller class 'Mage_Customer_AccountController' to get the original functionality.

Hope this helps.

Wednesday, November 05, 2014

Manual Login and Logout in WordPress

Very recently, I had a situation where I needed to take user's username and password as inputs and log him/her onto Wordpress manually. And this is how I came up with the solution. Check the code below.

<?php
// This is a very important step
// We need to get the wp object
require("wp-load.php");   

// Log Out if anyone is already logged
// in from same browser
if ( is_user_logged_in() ) 

   // Default Wordpress function 
   // to log a user out
   wp_logout(); 
}

// GET user's Inputs (username, password)
$creds = array();
$creds['user_login']    = $_POST['username'];
$creds['user_password'] = $_POST['password'];

// Extra settings, for Remember me
$creds['remember'] = false;

// The Wordpress function which Logs
// the user in
$user = wp_signon( $creds, false );

// Track ERROR if any
if ( is_wp_error($user) )
{
  echo $user->get_error_message(); 
}
// Login Success
else
{
  echo "You have logged in successfully";
}
?>

The code above is quite self-explanatory. Some points to be noted : 

1. wp_signon() -- It logs any user in with username and passwords passed to it in Array. This function takes a 2nd parameter to mention whether secured cookies are to be used.
2. wp_logout() -- It logs out if any user is logged in
3. The array $cred must be built with the keys ('user_login' and 'user_password') shown above.

Thursday, October 30, 2014

Number summation problem

Very recently, I have come across an interesting programming problem which is shown below.

Problem :: We have an array of various numbers. From that array we need to find those numbers which can be written as sum of 2 or more consecutive numbers existing within the same array.

Say for example, in an array of numbers (5,1,3,2,4,6), the first number "5" can be written as "3+2" but not "1+4" as "1" and "4" are not appearing consecutively. Similarly "6" can be written as "5+1" and "2+4" etc. 

So, we need to find out all the numbers which are sum of other consecutive numbers and print them.

1. So, will be requiring a loop which would inspect every number in the array (starting from 5,1 and so on). Let's examine the case of "5".

2. Inside the above loop, we start with adding-numbers (which would be added to produce "5") "1" and start checking if consecutive numbers "3", "2" (i.e 1+3+2+...) and so on can produce the sum "5".
   So, we need a second loop for this. This would find the starting point of adding-numbers. A successful series may be "1+3+..." or "3+2+.." or "2+4+.." etc. So, 1,3,2 etc are starting numbers from which we start to add consecutive numbers.

3. Now, let's consider a case where we have such a starting number say "1". We need a third loop which would run through rest of the array to add consecutive numbers "3", "2" etc  to "1" and produce a sum of "5". This third loop will produce the actual sum.

4. We keep a track whether minimum 2 numbers are added to produce the final result "5" through a counter.

Let's check the code part to understand our approach to solve the problem. The inspection of number "5" have been discussed in comments in the code below.

<?php
// Define the array
$arr = array(5,1,3,2,4,6);

// Here we have the FIRST loop to inspect 
// each number in the array
for($i=0;$i<count($arr);$i++)
{
  // Store the Current number we are inspecting
  // Let's examine the case of 5
  $current_number = $arr[$i];
  
  // Second Loop
  for($j=0;$j<count($arr);$j++)
  {
      // Set $sum variable to hold SUM
      $sum = 0;
      $str = "";
 
      // $count variable makes sure that minimum
      // two numbers are added
      $count = 0;
 
      // We would ignore the Number we are inspecting
      // while Addint. We won't add "5" to $sum 
      // (initially set to 0) to product "5". 
      // Hence we just ignore the situation
      if($j == $i) continue;  
 
      // Otherwise, We move ahead
      if($j != $i) 
      {
  
        // Third Loop, it keeps on Adding to $sum from 
        // the starting point say "1" or "3" or "2" and so on.
        for( $k=$j;$k<count($arr);$k++)
{

          // Avoid the chance of adding the Number
           // which is being inspected (5 in our test case)
          if($k == $i) break;
 
       // Add to SUM ($sum variable)
          $sum += $arr[$k];
  
   // When we add, we increase the counter
   // We need to make sure that minimum 2 numbers
   // are added to produce "5"
   $count++;
  
   // We build a String of numbers we are adding
   $str .= $arr[$k] . ",";
  
    // If summation is already higher than 
           // the Number being inspected, we discard 
           // that combination. This way we can 
           // discard "1+3+2" resulting 6 etc and 
    // save some precious CPU time
    if($sum>$current_number) 
           { 
              break; 
           }
  
          // If minimum 2 digits are added
           // and Sum is "5" let's PRINT the result 
           // and break. This means if we find that 
           // "3+2" is acceptable, then we need to 
           // move to next starting point say "2" and                          // check combinations like "2+4+..." etc
          if($count >= 2 && $sum == $current_number) 
          { 
            // Show Result
            echo "<br> ($i position)" .
                 " $current_number is summation" .
                 " of numbers ". rtrim($str,","); 
            break; 
          } 
      } // Third Loop Ends
    
     }// If ends
 
  } // Second Loop ends

} // First Loop Ends

?>

The above code is explained within the accompanied comments. 

Now, Check the output below :

(0 position) 5 is summation of numbers 3,2
(4 position) 4 is summation of numbers 1,3
(5 position) 6 is summation of numbers 5,1
(5 position) 6 is summation of numbers 1,3,2
(5 position) 6 is summation of numbers 2,4