Sanjoy Roy

[MCM, MCP, SCJP] – Senior PHP Programmer

Category Archives: Language

Javascript Validate two input fields with the same name?


<div style=”” id=”shipping-new”>
<table class=”form”>
<tr>
<td><span class=”required”>*</span> Post Code:</td>
<td><input type=”text” class=”large-field” value=”” name=”postcode”><span class=”error”>Sorry, we cannot deliver to your area!</span></td>
</tr>
</table>
</div> Read more of this post

Advertisements

www redirect issues Fix


How to change domain.com.au to http://www.domain.com.au?

if ($_SERVER['HTTP_HOST'] != 'www.domain.com.au') header('Location: http://www.domain.com.au' . $_SERVER['REQUEST_URI']);

If we use the cart, the cookies will be stored differently if we don’t use it. So, it will be always storing under domain http://www.domain.com.au. Applied for the client SHE Lights.

Where is Magento’s advanced search link?

Magento where is database configuration file?


Find the local.xml in local \\\magento\app\etc\local.xml
<pre class="brush:xml">
<config>

<db>
<table_prefix><![CDATA[]]></table_prefix>
</db>
<default_setup>
<connection>
<host><![CDATA[localhost]]></host>
<username><![CDATA[bobjaneg_user]]></username>
<password><![CDATA[tES@A$pGtOF&]]></password>
<dbname><![CDATA[bobjaneg_cmsdb]]></dbname>
<active>1</active>
</connection>
</default_setup>

</config>
</pre>

Magento storing in session


$storage = array('a'=>'b');

// store data so we can fetch it in subtotal methods
Mage::getSingleton('core/session')->setRbanhShipping(serialize($storage));

// get data
$rbanhShipping = Mage::getSingleton('core/session')->getRbanhShipping(); 
$rbanhShipping = unserialize($rbanhShipping);

Magento how to get shipping quote per item in cart


foreach ($session->getQuote()->getAllItems() as $item) 
{
    $output .= "

"; $output .= $item->getWeight(); $output .= "
"; $output .= $item->getName() . "
"; $output .= "QTY:" . $item->getQty() . " | $" . number_format($item->getPrice(), 2); $output .= "

"; $temp_product = Mage::getModel('catalog/product') ->setCurrentStore(1) ->load($item->getProduct()->getId()); $quote2 = Mage::getModel('sales/quote'); //$quote2->setDestPostcode($session->getQuote()->getShippingAddress() ->getPostcode()); //$quote2->getShippingAddress()->setCountryId('US'); $quote2->setShippingAddress($session->getQuote() ->getShippingAddress()); $temp_product->getStockItem()->setUseConfigManageStock(false); $temp_product->getStockItem()->setManageStock(false); $quote2->addProduct($temp_product); $quote2->setPackageWeight($item->getWeight()); $quote2->getShippingAddress()->setCollectShippingRates(true); $quote2->getShippingAddress()->collectTotals(); $rates = $quote2->getShippingAddress()->getShippingRatesCollection(); //$rates = $quote2->getShippingAddress()->getAllShippingRates(); //var_export($rates); foreach ($rates as $rate) { $output .= " rbanh = ".$rate->getPrice()." " . $rate->getCode() . " END
"; } }

Magento auto add product custom options


// *Special note: make sure you check your sql table name, 
//  and change the option title from what i have below.

// rbanh special methods
private function rbanh_get_custom_option_id($product_id)
{
    $sql = "
        select 
            o.option_id 
        from 
            catalog_product_option o
        inner join
            catalog_product_option_title t on t.option_id = o.option_id
        where
            t.title = 'Shipping Description'
            and o.product_id = '".$product_id."'
        limit 1
            ";
    $data = Mage::getSingleton('core/resource') ->getConnection('core_read')->fetchAll($sql);
    if (count($data) > 0)
    {
        return current($data[0]);
    }
    return false;
}

// rbanh special methods
private function rbanh_add_custom_option($product_id)
{
    // make the option active
    //$write = Mage::getSingleton('core/resource')->getConnection('core_write');
    //$write->query("update catalog_product_entity set has_options = 1 where entity_id='$product_id'"); 
    $write = Mage::getSingleton('core/resource')->getConnection('core_write');
    $sql  = "update catalog_product_entity set has_options = 1 where entity_id=?";
    $write->query($sql, $product_id); 
    
    $product = Mage::getModel('catalog/product');
    $product->load($product_id);
    $opt = Mage::getModel('catalog/product_option');
    $opt->setProduct($product);
    $option = array(
        'is_delete' => 0,
        'is_require' => false,
        'previous_group' => 'text',
        'title' => 'Shipping Description',
        'type' => 'field',
        'price_type' => 'fixed',
        'price' => '0.0000'
    );
    $opt->addOption($option);
    $opt->saveOptions();
    
    return $this->rbanh_get_custom_option_id($product_id);
}

Magento How to add new products



require_once 'app/Mage.php';
Mage::app();
 
// instatiate Product
$product = Mage::getModel('catalog/product');
 
$product->setWebsiteIds(array(1));
$product->setSku('rand-sku-' . rand());
$product->setPrice(rand(100,2000));
$product->setAttributeSetId(4); 
$product->setCategoryIds(array(3));
$product->setType('Simple Product');
$product->setName('Product Name'.rand(1,200000));
$product->setDescription('The Product Description');
$product->setShortDescription('Brief Description');
$product->setStatus(1);	
$product->setTaxClassId('2');
$product->setWeight(0);				
$product->setCreatedAt(strtotime('now'));
 
/* ADDITIONAL OPTIONS 
 
   $product->setCost();
   $product->setInDepth();
   $product->setKeywords();
 
*/
 
$product->save();
 
// "Stock Item" still required regardless of whether inventory
// control is used, or stock item error given at checkout!
 
$stockItem = Mage::getModel('cataloginventory/stock_item');
$stockItem->loadByProduct($product->getId());
$stockItem->setData('is_in_stock', 1);
$stockItem->save();
 
header("Location: /checkout/cart/add/product/".$product->getId()."/); 

Magento observer sales order



/**
 * Register an event trigger after the order has been saved
 *
 * Is triggered by sales_order_save_after event 
 *
 */
public function hookSalesOrderSaveAfter ($observer)
{
    $order = $observer->getEvent()->getOrder(); // returns the Mage_Sales_Model_Order Object
    Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); // Magento can only save attributes in admin mode
    $order->setVendor('LoremIpsum');
    $order->getResource()->saveAttribute($order, "vendor");
    $order->setCallToAction('ANC');
    $order->getResource()->saveAttribute($order, "call_to_action");
    $order->setKeycode('0x7474');
    $order->getResource()->saveAttribute($order, "keycode");
    return $this;
}

Magento displaying store id

Display Magento sub categories


    $currentCat = Mage::registry('current_category');

    if ( $currentCat->getParentId() == Mage::app()->getStore()->getRootCategoryId() )
    {
        // current category is a toplevel category
        $loadCategory = $currentCat;
    }
    else
    {
        // current category is a sub-(or subsub-, etc...)category of a toplevel category
        // load the parent category of the current category
        $loadCategory = Mage::getModel('catalog/category')->load($currentCat->getParentId());
    }
    $subCategories = explode(',', $loadCategory->getChildren());

    foreach ( $subCategories as $subCategoryId )
    {
        $cat = Mage::getModel('catalog/category')->load($subCategoryId);

        if($cat->getIsActive())
        {


            echo 'getURL().'">'.$cat->getName().'
'; echo $cat->getDescription(); echo 'getImage().'">'; } }

Magento cart total + items


getSummaryQty(); ?>
There are  items  in your cart
					getQuote()->getAllItems() as $item) {
    $output .= "

"; $output .= $item->getName() . "
"; $output .= "QTY:" . $item->getQty() . " | $" . number_format($item->getPrice(), 2); $output .= "
"; } print $output;?>

Magento shopping cart total


helper('checkout')->formatPrice(Mage::getSingleton('checkout/cart')->getQuote()->getGrandTotal()); ?>

Modify Magento TAX Calculation


Change the following file: magento\app\code\core\Mage\Tax\Model\Calculation.php

/**
     * Calculate rated tax abount based on price and tax rate.
     * If you are using price including tax $priceIncludeTax should be true.
     *
     * @param   float $price
     * @param   float $taxRate
     * @param   boolean $priceIncludeTax
     * @return  float
     */
    public function calcTaxAmount($price, $taxRate, $priceIncludeTax=false, $round=true)
    {
        $taxRate = 10;
		$taxRate = $taxRate/100;
		$this->insertInLog('taxRate', $taxRate);
		$this->insertInLog('price', $price);
        if ($priceIncludeTax) {
            $amount = $price*(1-1/(1+$taxRate));
        } else {
            $amount = $price*$taxRate;
        }
		$this->insertInLog('Amount', $amount);
        if ($round) {
            return $this->round($amount);
        } else {
            return $amount;
        }
    }


    /**
     * Insert in to Log Table. It helps to trace and stores in table
     *
     * @param   varchar $title
     * @param   varchar $desc
     */

	function insertInLog($title, $desc){		
		mysql_connect("localhost","root","");
		mysql_select_db("magento");
		$sql = "insert into log_tbl values('".$title."', '".$desc."', '".date("Y-m-d h:i:s")."')";
		mysql_query($sql);
	}

How to retrieve customer name/firstname in Magento


require_once 'app/Mage.php';
umask(0);
Mage::app('default');
$session = Mage::getSingleton('customer/session');
if($session->isLoggedIn()) {
   $customer = $session->getCustomer();
   echo $customer->getName();
   echo $customer->getFirstname();
}

Magento isRecurring


    /**
     * Whether there are recurring items
     *
     * @return bool
     */
    public function hasRecurringItems()
    {
        foreach ($this->getAllVisibleItems() as $item) {
            if ($item->getProduct() && $item->getProduct()->isRecurring()) {
                return true;
            }
        }
        return false;
    }

Top PHP 5 Projects


icon.png Kumbia PHP Framework php Framawork spanish, mvc, full support, forms generation, AJAX and Web 2,0 focused
latus_logo.gif LATUS LATUS is the Site Management System developed by MoveNext from Leiden, the Netherlands
live_agent_logo.gif Live Agent Chat LiveAgent live chat software is THE live chat solution for your website. This PHP / MySQL / AJAX script is completely web based.
LoveCMS LoveCMS is a simple content managment system for producing websites without learning curve.
logo_s.jpg Magike Magike is a powerful blog software based on PHP5.

Read more of this post

PHP Not Accepting <? Tag; Only Accepting <?php and <script> Tag


short_open_tag = boolean (php.ini file)

This ‘short_open_tag’ directive determines whether or not PHP will recognize code between <? and ?> tags as PHP source which should be processed as such. It’s been recommended for several years that you not use the short tag “short cut” and instead to use the full <?php and ?> tag combination. With the wide spread use of XML and use of these tags by other languages, the server can become easily confused and end up parsing the wrong code in the wrong context. But because this short cut has been a feature for such a long time, it’s currently still supported for backwards compatibility, but it is recommend we don’t use them.
Default Value: On
Development Value: Off
Production Value: Off

short_open_tag = On

for more info, visit: http://php.net/short-open-tag

Use PHP functions in JavaScript


php.js Logo php.js is an open source project that brings high-level PHP functions to low-level JavaScript platforms such as webbrowsers, AIR, V8 and rhino.

If you want to perform high-level operations on these platforms, you probably need to write JS that combines it’s lower-level functions and build it up until you have something useful like: md5(), strip_tags(), strtotime(), number_format(), wordwrap().

That’s what we are doing for you.

No server component required. To use php.js you can either:

WampServer


WampServer is a Windows web development environment. It allows you to create web applications with Apache, PHP and the MySQL database. It also comes with PHPMyAdmin to easily manage your databases.

https://i1.wp.com/www.wampserver.com/en/data/image_menu_wamp.gif
WampServer installs automatically (installer), and its usage is very intuitive. You will be able to tune your server without even touching the setting files.
WampServer is the only packaged solution that will allow you to reproduce your production server. Once WampServer is installed, you have the possibility to add as many Apache, MySQL and PHP releases as you want.
WampServer also has a trayicon to manage your server and its settings.

WampServer’s functionalities are very complete and easy to use so we won’t explain here how to use them.
With a left click on WampServer’s icon, you will be able to:

  • manage your Apache and MySQL services
  • switch online/offline (give access to everyone or only localhost)
  • install and switch Apache, MySQL and PHP releases
  • manage your servers settings
  • access your logs
  • access your settings files
  • create alias

With a right click:

  • change WampServer’s menu language
  • access this page

Download Link

Parse .xls (Excel) using PHP


XLSParser.php:

if ($fileType !='' && $fileType == 'application/vnd.ms-excel'){
		//parse xsl file
		 $ext = 'xls';
		 $filename 	= $user.'.'.$section.'.upload.'.date('Ymd').'.'.$ext;
		 copy($_FILES['file']['tmp_name'], $UPLOAD_CSV_PATH.$filename);
		 require_once '../includes/reader.php';

		$data = new Spreadsheet_Excel_Reader();
		 //set output encoding
		$data->setOutputEncoding('CP1251');
		//read the excel file through api
		$data->read($UPLOAD_CSV_PATH.$filename);
		//prepare to retun result
		$actual_data = $data->sheets[0]['cells'];

		$rowsLength	= array();
		for($i=1; $i<$max_nos; $j++){
				$allColumns[$j] = $actual_data[$i][$j];
			}
			$newRowData[] =  $allColumns;
		}
		$data = $newRowData;
  }

Parse .CSV using PHP


CSVParser.php:

if ($fileType !='' && $fileType == 'text/comma-separated-values'){
		//parse csv file
		 $ext = 'csv';
		 $filename 	= $user.'.'.$section.'.upload.'.date('Ymd').'.'.$ext;
		 copy($_FILES['file']['tmp_name'], $UPLOAD_CSV_PATH.$filename);

		 $row 				= 1;
		$fhandle 			= @fopen($UPLOAD_CSV_PATH.$filename, "r");
		$columnHeaders		= '';
		$columnNames		= '';
		$rawData			= array();
		$count = 0;
		while (($fdata = fgetcsv($fhandle, 1000, $terminated_by, $enclosed_by)) !== FALSE) {
			$len = count($fdata)-1;
			if (strlen($fdata[$len])==0) array_pop($fdata);
			$rawData[$count] = $fdata;
			$count++;
		}
		fclose($fhandle);

		$newRowData = array();

		for($i=0; $iencode($rawData);

  }

Parse XML Spreadsheet using PHP DOMDocument


xmlparser.html:

File Name:  
Options: Column Heading Included
Column Heading & Name Included
Just Data
 
Hidden Parameters:

 

xmlparser.php:

$fileType 	= isset($_FILES['file']['type']) ? $_FILES['file']['type']: '';
if ($fileType !='' && $fileType == 'text/xml'){
	  $ext = 'xml';
	  if ($_FILES['file']['tmp_name']){
	  	  //Copy to the backup directory
	  	  $filename 	= $user.'.'.$section.'.upload.'.date('Ymd').'.'.$ext;
		  copy($_FILES['file']['tmp_name'], $UPLOAD_CSV_PATH.$filename);
		  //parse xml spredsheet
		  $dom 		= DOMDocument::load($UPLOAD_CSV_PATH.$filename);
		  $rows 	= $dom->getElementsByTagName('Row');
		  $data		= array();

		  foreach ($rows as $row){
			  $index 	= 1;
			  $cells 	= $row->getElementsByTagName('Cell');
			  $tempdata = array();
			  foreach( $cells as $cell ){
				  $ind = $cell->getAttribute('Index');
				  if ( $ind != null ) $index = $ind;
				  //echo $cell->nodeValue."
"; $tempdata[] = $cell->nodeValue; $index += 1; }//inner for loop $data[] = implode(",", $tempdata); }//outer for loop }//outer if (file temp_name compare) }

Creating a Log File in PHP


Here is the code that can save the system process to a .log file using php:

//Function: writeToLogFile($content,$flag) - To write every steps to the specified log file.
function writeToLogFile($content,$flag){
global $LOG_FILE;
$strRootPath = dirname(__FILE__) . DIRECTORY_SEPARATOR;
$fp = fopen($strRootPath.$LOG_FILE,"a");
if ($flag)
$f_contents = date("Y-m-d H:i:s")."-".$content;
else
$f_contents = $content;
fwrite($fp,$f_contents."\r\n");
fclose($fp);
}

SWFUpload – JavaScript/Flash library to Upload Multiple Files


https://i2.wp.com/www.swfupload.org/sites/swfupload.org/themes/joel_pittet/Alina/images/logo.gif

SWFUpload is a small JavaScript/Flash library to get the best of both worlds. It features the great upload capabilities of Flash and the accessibility and ease of HTML/CSS.

* Upload multiple files at once by ctrl/shift-selecting in dialog
* Javascript callbacks on all events
* Get file information before upload starts
* Style upload elements with XHTML and css
* Display information while files are uploading using HTML
* No page reloads necessary
* Works on all platforms/browsers that has Flash support.
* Degrades gracefully to normal HTML upload form if Flash or javascript is unavailable
* Control filesize before upload starts
* Only display chosen filetypes in dialog
* Queue uploads, remove/add files before starting upload

PHP – Undefined Index


This error appears because of your PHP error reporting settings. Usually, it appears when your variable is not properly set. There are two ways to handle this issue:

1. Check if $_POST[‘action’] is set before using it. For example:

if (!isset($_POST['action']))
{
//If not isset -> set with dumy value
$_POST['action'] = "undefine";
}

2. Suppress Notice warnings

Notice warnings could be suppressed by changing the error_reporting variable in your PHP.ini. error_reporting could be set to show all errors except those for notices and coding standards warnings: error_reporting = E_ALL & ~E_NOTICE

The same is accomplished by adding the following line in your php page:

 error_reporting (E_ALL ^ E_NOTICE);

suPHP


https://i0.wp.com/www.suphp.org/images/suphp_logo.png

suPHP is a tool for executing PHP scripts with the permissions of their owners. It consists of an Apache module (mod_suphp) and a setuid root binary (suphp) that is called by the Apache module to change the uid of the process executing the PHP interpreter.

Use of PHP functions in Js


php.js Logo php.js is an open source project that brings high-level PHP functions to low-level JavaScript platforms such as webbrowsers, AIR, V8 and rhino.

If you want to perform high-level operations on these platforms, you probably need to write JS that combines it’s lower-level functions and build it up until you have something useful like: md5(), strip_tags(), strtotime(), number_format(), wordwrap().

That’s what we are doing for you.

No server component required. To use php.js you can either:

%d bloggers like this: