Archive for category PHP

Extract/Import Object properties into Currect Symbol Table in PHP

If we want to import an associative array into current symbol table then we can use extract function. This function treats associative array keys as variable name and values as variable values.

But we can not use extract function directly if we want to import class object properties into current symbol table in similar way. So, for this first we need to get the properties of object as an associated array. We can use get_object_vars function for this purpose. get_object_vars function take object as parameter and return associative array of all non-static properties of passed object. For any unassigned property it will return NULL value.

Now we can pass this returned associative array into extract function to import objects non-static properties into current symbol table.

Code Snippet:-

<?php
// For associative array
 
$sampleArray = array('name' => 'John', 'age' => 25);
 
extract($sampleArray);
 
echo $name; // Output is "John"
echo $age; // Output is "25"
 
// For object
$sampleObject = new stdClass;
 
$sampleObject->name = 'Peter';
$sampleObject->age = 27;
 
$returnArray = get_object_vars($sampleObject);
 
extract($returnArray);
 
echo $name; // Output is "Peter"
echo $age; // Output is "27"
?>

,

No Comments


Generate Random Alphanumeric Password in PHP

This is a very simple and one of the way to generate random alphanumeric password in PHP.

Code Snippet:-

<?php
function generateCharacter() {
	$possible = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
	$char = substr($possible, mt_rand(0, strlen($possible) - 1), 1);
	return $char;
}
 
function generatePassword($length) {
	static $password;
 
	if ($length) {
		$password .= generateCharacter();
 
		generatePassword(--$length);
	}
 
	return $password;
}
 
// Use of this function
 
echo generatePassword(10); // Qz1GUfkWFT
echo generatePassword(15); // GPB1hA8pVVWsgLZ
echo generatePassword(8);  // 20e3Bvec
?>

,

1 Comment


PHP Class for converting XML to Object and Object to XML

Sometimes in PHP we need to convert PHP object into XML string and vice versa. Conversion of XML string to PHP object is pretty simple. You just need to call simplexml_load_string() function (available in PHP 5+) and need to pass your XML string. This will return the object which you can use. The only requirement is your XML string need to be well-formed XML string otherwise PHP will through E_WARNING error message.

Conversion of Object into XML string is little bit tricky. We need to recursively parse the Object and need to create XML tags for object attributes (keys). I’m using XmlWriter class for that purpose. Three important methods of this class which I’m using is startElement(), endElement(), and writeElement(). We need to check the passed mixed variable in getObject2XML() method and add the XML tags with values one by one.

<?php
class ObjectAndXML {
	private static $xml;
 
	// Constructor
	public function __construct() {
		$this->xml = new XmlWriter();
		$this->xml->openMemory();
		$this->xml->startDocument('1.0');
		$this->xml->setIndent(true);
	}
 
	// Method to convert Object into XML string
	public function objToXML($obj) {
		$this->getObject2XML($this->xml, $obj);
 
		$this->xml->endElement();
 
		return $this->xml->outputMemory(true);
	}
 
	// Method to convert XML string into Object
	public function xmlToObj($xmlString) {
		return simplexml_load_string($xmlString);
	}
 
	private function getObject2XML(XMLWriter $xml, $data) {
		foreach($data as $key => $value) {
			if(is_object($value)) {
				$xml->startElement($key);
				$this->getObject2XML($xml, $value);
				$xml->endElement();
				continue;
			}
			else if(is_array($value)) {
				$this->getArray2XML($xml, $key, $value);
			}
 
			if (is_string($value)) {
				$xml->writeElement($key, $value);
			}
		}
	}
 
	private function getArray2XML(XMLWriter $xml, $keyParent, $data) {
		foreach($data as $key => $value) {
			if (is_string($value)) {
				$xml->writeElement($keyParent, $value);
				continue;
			}
 
			if (is_numeric($key)) {
				$xml->startElement($keyParent);
			}
 
			if(is_object($value)) {
				$this->getObject2XML($xml, $value);
			}
			else if(is_array($value)) {
				$this->getArray2XML($xml, $key, $value);
				continue;
			}
 
			if (is_numeric($key)) {
				$xml->endElement();
			}
		}
	}
}
?>

How to use it.
1. If you want to convert XML string into PHP object.

<?php
$obj = new ObjectAndXML();
 
$str = <<<STR
<?xml version="1.0" encoding="utf-8"?>
<records>
    <person>
    	<name>XYZ</name>
        <age>28</age>
        <gender>Male</gender>
    </person>
    <person>
    	<name>ABC</name>
        <age>25</age>
        <gender>Male</gender>
    </person>
</records>
STR;
 
$recordsObj = $obj->xmlToObj($str);
echo '<pre>';
var_dump($recordsObj);
 
// Above code will give you this output on browser
/*
object(SimpleXMLElement)#3 (1) {
  ["person"]=>
  array(2) {
    [0]=>
    object(SimpleXMLElement)#4 (3) {
      ["name"]=>
      string(3) "XYZ"
      ["age"]=>
      string(2) "28"
      ["gender"]=>
      string(4) "Male"
    }
    [1]=>
    object(SimpleXMLElement)#5 (3) {
      ["name"]=>
      string(3) "ABC"
      ["age"]=>
      string(2) "25"
      ["gender"]=>
      string(4) "Male"
    }
  }
}
*/
 
// If you want to access value of "name" tag under second "person" tag then you can use 
echo $recordsObj->person[1]->name;
?>

2. If you want to convert PHP object into XML string.

<?php
$obj = new ObjectAndXML();
 
$objData1 = new stdClass;
 
$objData1->records->person[0]->name = 'XYZ';
$objData1->records->person[0]->age = '28';
$objData1->records->person[0]->gender = 'Male';
 
$objData1->records->person[1]->name = 'ABC';
$objData1->records->person[1]->age = '25';
$objData1->records->person[1]->gender = 'Male';
 
echo $recordsXML = $obj->objToXML($objData1);
 
// Output will be
/*
<?xml version="1.0"?>
<records>
 <person>
  <name>XYZ</name>
  <age>28</age>
  <gender>Male</gender>
 </person>
 <person>
  <name>ABC</name>
  <age>25</age>
  <gender>Male</gender>
 </person>
</records>
*/
 
$objData2 = new stdClass;
 
$objData2->records->person[0]->name[] = 'XYZ';
$objData2->records->person[0]->name[] = 'ABC';
$objData2->records->person[0]->name[] = 'PQR';
 
$objData2->records->person[1]->name[] = 'XYZ1';
$objData2->records->person[1]->name[] = 'ABC1';
$objData2->records->person[1]->name[] = 'PQR1';
 
echo $recordsXML = $obj->objToXML($objData2);
 
// Output will be
/*
<?xml version="1.0"?>
<records>
 <person>
  <name>XYZ</name>
  <name>ABC</name>
  <name>PQR</name>
 </person>
 <person>
  <name>XYZ1</name>
  <name>ABC1</name>
  <name>PQR1</name>
 </person>
</records>
*/
 
$objData3 = new stdClass;
 
$objData3->records->person->name = 'XYZ';
$objData3->records->person->age = '28';
$objData3->records->person->gender = 'Male';
 
echo $recordsXML = $obj->objToXML($objData3);
 
// Output will be
/*
<?xml version="1.0"?>
<records>
 <person>
  <name>XYZ</name>
  <age>28</age>
  <gender>Male</gender>
 </person>
</records>
*/
?>

, ,

2 Comments


Verify the iTunes Account access information with the help of cURL

<?php
// URLs of iTunesconnect.
$urlBase = 'https://itts.apple.com';
$urlWebsite = $urlBase . '/cgi-bin/WebObjects/Piano.woa';
 
// function to check finance role acounts validity. This function return true is the detail is still valid.
function isAccountValid($username, $password) {
	global $urlBase, $urlWebsite;
 
	$html = curlRequest($urlWebsite, null); // First cURL request to get the login form
 
	preg_match('/" action=".*"/', $html, $matches); // Search the form action URL because all URLs are dynamic
 
	$urlActionLogin = $urlBase . substr($matches[0], 10, -1);
 
	$postData = array('theAccountName' => $username, 'theAccountPW' => $password, '1.Continue.x' => '1', '1.Continue.y' => '1'); // Creating the form POST data
 
	$html = curlRequest($urlActionLogin, $postData); // Second cURL request with form data for login
 
	if (strpos($html, 'Report Options') === false) { // If the return HTML contain 'Report Options' text then its successful login
		return false;
	}
 
	return true;
}
 
// function send the curl request on given URL with post variables and return the html output
function curlRequest($url, $postVars) {
	$ch = curl_init();
 
	curl_setopt($ch, CURLOPT_URL, $url);
 
	if (!is_null($postVars)){ 
		curl_setopt($ch, CURLOPT_POST, count($postVars));
 		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postVars));
	}
 
 	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
 	curl_setopt($ch, CURLOPT_HEADER, FALSE);  
 	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);  
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
 
 	$html = curl_exec($ch);
 
	if (curl_errno($ch)) {
		die(curl_error($ch));
	}
 
	curl_close($ch);
 
	return $html;
}
 
// Examples 01
if (isAccountValid('anil@test.com', 'test@anil')) {
	echo "anil@test.com account is valid.<br/>";
}
else {
	echo "anil@test.com account is not valid.<br/>";
}
 
// Examples 02
if (isAccountValid('invalid_address@test.com', 'wrong_password')) {
	echo "invalid_address@test.com account is valid.<br/>";
}
else {
	echo "invalid_address@test.com account is not valid.<br/>";
}
 
?>

, ,

No Comments


How know Base Path of Drupal in JavaScript

Sometimes you want to know about the Base Path of your Drupal installation in JavaScript. You may want to know about this path for sending the AJAX request at correct URL relatively, load the image or some other type of file on client side through JavaScript etc.

Drupal provide a variable called Drupal.settings.basePath for this purpose in JavaScript. But this variable is only available if you include any custom JavaScript file or JavaScript block in your module. By default Drupal doesn’t include the ‘jquery.js‘ and ‘drupal.js‘ file in generated output. It only add these files if you add your custom JavaScript file or JavaScript block. We can include our custom JavaScript file in Drupal like this:-

drupal_add_js(drupal_get_path('module','my_module'). '/my_module.js');

The my_module.js file should reside in same directory where my_module module exist. This will force Drupal to add jquery.js and drupal.js files in output.

These two files initialize the Base Path variable. In drupal.js file, on top you can see the initialization of setting object in Drupal object. Like this:-

var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'themes': {}, 'locale': {} };

Drupal generate some JavaScript code in Script block inside head tag of each page for extending the settings object with the help of jQuery. Like this:-

jQuery.extend(Drupal.settings, { "basePath": "/" });

You can test the Base Path by adding following code in my_module.js file.

$(document).ready(function() {
	alert(Drupal.settings.basePath);
});

This will alert the Base Path for Drupal installation after loading of the page.

, ,

1 Comment