08 November, 2010

Check if email is opened using php

Yesterday i had a problem to check if email is opened by a user using php. After some google search,i came to know that, checking if our sent email is opened by a user can be done by some simple trick.
Though this idea might not be applicable for all the cases, but can be of some help. This can be helpful in tracking users for newsletter, campaigns, etc. So following is the code snippet to detect if email is opened using php.
Step 1:
insert a 1 pixel image in the body of email that you create, like

$emailBody = 'This is a test message.';
$emailBody .='';
$emailBody .='Please feel free to contact me..!';
....
.....
//send email using mail() function of php


Step 2:
Create the file take_action_open.php and add following code

//get the userid from url of image source
$userId = $_GET["userid"];
//add code to insert this user to database
//or do something with it.
//this user has opened the email that you have sent.

And thats it. You can track opened emails using this method. As i already
said this method may not be applicable for all cases, since images can be
disabled by some mail services as well. So need to find some other solution
in such cases. However, i think this code might be of some help to someone
like me.

Get path of a file in PHP

Once i have to get location of a file using a single line of code in php. Here's how i did it.

$filePath = substr($_SERVER["SCRIPT_FILENAME"], 0, strrpos($_SERVER["SCRIPT_FILENAME"], "/"));
echo $filePath; // this gives the full file path

Hope it helps someone.

01 November, 2010

CSV to Multi-Dimensional Array in PHP

Once i needed to convert a csv file contents to a multi-dimensional array in php. Converting a csv to a multi-dimensional array
can be done by reading the file by using php's fopen function and then looping through to insert data to the array.
Following is a code snippet that is used to get csv to multi-dimensional array in php.
My csv file was in the format "name" "email_address" without any column names.

$formattedArr = array();
$filename = "test.csv";
//csv format was
//name test@this.com
//tester tester@mail.com
//sudhir sudhirconscious@gmail.com
if (($handle = fopen($filename, "r")) !== FALSE) {
$key = 0; // Set the array key.
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$count = count($data); //get the total keys in row
//insert data to our array
for ($i=0; $i < $count; $i++) {
$formattedArr[$key][$i] = $data[$i];
}
$key++;
}
fclose($handle); //close file handle
}
//csv to multidimensional array in php
echo "
";
print_r($formattedArr);
echo "
";
And thats it.

Get elements by class name in javascript

At times, i need function to get all the elements using class name in javascript. But since such function does not exist as in javascript, so i thought of creating a similar function that can be used to get elements by class name.
Here is the code snippet:

function getElementByClassName(strClassName) {
var eleNames = new Array();
var totalFrms = document.forms.length;
for(var i = 0; i < totalFrms; i++) {
//alert(document.forms[i].elements.length);
var eleLen = document.forms[i].elements.length;
for(var j = 0; j < eleLen; j++) {
if(strClassName === document.forms[i].elements[j].className) {
eleNames.push(document.forms[i].elements[j]);
}
}
}
return eleNames;
/*
for(t = 0; t < eleNames.length; t++) {
alert(eleNames[t].type);
}
*/
}
getElementByClassName("user_text");
Thats is. Hope this helps someone.

31 October, 2010

Get all month names between two dates in php

Yesterday i faced a problem regarding date manipulation in php. I had to get all month names between two dates, after some work around, i managed to make it work. I created a function "get_months" and passed two dates i.e. start date and end date to find list of months between the two dates.
Here's the function:

function get_months($date1, $date2) {
//convert dates to UNIX timestamp
$time1 = strtotime($date1);
$time2 = strtotime($date2);
$tmp = date('mY', $time2);

$months[] = array("month" => date('F', $time1), "year" => date('Y', $time1));

while($time1 < $time2) {
$time1 = strtotime(date('Y-m-d', $time1).' +1 month');
if(date('mY', $time1) != $tmp && ($time1 < $time2)) {
$months[] = array("month" => date('F', $time1), "year" => date('Y', $time1));
}
}
$months[] = array("month" => date('F', $time2), "year" => date('Y', $time2));
return $months; //returns array of month names with year
}

Thats it. I hope this helps someone like me.

20 October, 2010

Compare dates using PHP

Some times before, one of my friend asked me how to compare two dates using php. As he was a beginner and didnt have much knowledge regarding date and time functions in php, i did some kind of explanation to him.
We can use a php function strtotime in order to compare two dates in php. strtotime converts any date format description to Unix timestamp, and what we can do is convert, dates that are to be compared, to unix timestamp and perform a simple comparision.
Let's assume, we need to check if our registration has expired.

//first take today's date
$todaysDate = date("Y-m-d");

//get the expiration date, mat be from database or somewhere else
$expirationDate = "2010-12-06";

//now we convert both, today's date and expiration date to unix timestamp
$todaysDateStr = strtotime($todaysDate);
$expirationDateStr = strtotime($expirationDate);

//now simply compare the two variables
if($expirationDateStr > $todaysDateStr) {
echo "Your registration is valid!";
}
else {
echo "Your registration has expired!";
}

And that's it. The date format can be any like "-" or "/". Just convert it to unix timestamp and then compare the dates using php comparision operators.
I hope this helps someone.

12 October, 2010

How to check for numeric value using Javascript

We can use some simple function to check numeric value using javascript. The following is code snippet that checks if a value is numeric or not, returns false if not numeric else returns true.
Hope this helps someone.

//following function is used to check for a numeric value
function is_numeric(numVal) {
return (typeof(numVal) === "number" || typeof(numVal) === "string") && numVal != "" && !isNaN(numVal);
}
var testThis = "123";

//check as follows
alert(is_numeric(testThis));
//returns true

How to check for alphanumeric characters using javascript

Some times before, i was asked by one of my friend to check for alphanumeric characters using javascript. I did it for him using regular expressions.
Following is the code snippet for checking alphanumeric characters.

var testId = "1123ASD";
if((testId.search(/[^a-zA-Z0-9 ]/g)) {
alert("Matched");
}
else {
alert("Invalid");
}
//you can enter characters like + - *^$%^$, etc to check it

I hope this helps someone like me.

08 October, 2010

How to remove al element from array using Javascript

Yesterday, I got into a problem of removing any element from any array in javascript. After some testing, found the solution, thats better for me at least. The following code uses combination of plain javascript and jquery to remove element from an array.
Here is the code.

var arr = ['1', '2', '3'];
var usrId = '2';
//remove an element
arr.splice($.inArray(usrId, arr), 1);

Done

07 October, 2010

How to extend more than one class in php

Since multiple inheritance is not supported in php, we have to find a way to support it, so that we will be
able to extend more than one class at once. For this we can fake multiple inheritance in php using some
class and object functions provided by php.
I came across the problem where i had to extend more than once class using a single class, and for that
after some research came to a solution that can be used to make php support multiple inheritance, if i can say that.

//this is the Abatract class that implements fake multiple inheritance in php
//not allowed to create instance of this class
Abstract class MultipleExtension {

public $_this;
private $_extension = array(); //contains extended classes

//constructor function that passes $this to our private variable $_this
function __construct(){
$_this = $this;
}

//function to add the extended class objects
public function addExtension($obj) {
$this->_extension[]=$obj;
}

//overloading the members with getter function
public function __get($name) {
foreach($this->_extension as $ext) {
//check if the property defined as $name exists in the class $ext
if(property_exists($ext,$name))
return $ext->$name;
}
}

//member overloading using setter function
public function __set($name, $value) {
foreach($this->_extension as $ext) {
//check if the property $name exists in class $ext
//and if it does assign the value in $value to $name property of $ext class
if(isset($ext->$name)) {
$ext->$name = $value;
}
}
}

public function __call($method,$arguments) {
foreach($this->_extension as $ext) {
//check if function exists defined in method variable for the extended class
if(method_exists($ext,$method)) {
//call the user defined function with method and parameters
return call_user_func_array(array($ext, $method) ,$arguments);
}
}
}
}

And below is the implementation of above abstract class that supports multiple inheritance

//this is the first class that sets firstname of a user
class First {
private $_firstName;
public function setName($firstname){
$this->_firstName = $firstname;
}
public function getName(){
return $this->_firstName;
}
}
//this is the second class that sets location of a user
class Second {
private $_locationName;
public function setLocation($location){
$this->_locationName = $location;
}

public function getLocation(){
return $this->_locationName;
}
}
//this is a test class that extends multipleExtension class that fakes multiple inheritance
class Test extends MultipleExtension {
function __construct() {
//call the function that stores all the objects of classes as shown below
parent::addExtension(new First());
parent::addExtension(new Second());
}

public function __toString() {
return $this->getName().' located in: '.$this->getLocation();
}
}
//now create object of Test class and do as follows
$obj = new Test();
$obj->setName("Sudhir");
$obj->setLocation("Nepal");
echo $obj;
//This will output Sudhir located in: Nepal.