Search This Blog

Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Mar 18, 2014

Auto Detection of CSV EOL using PHP

Different Operating  Systems always find a way to make developers life in uneasy. Just like what happened when we created a import contact script that will parse a csv file then save it to a database.

The script runs smoothly using a Windows CSV format but not with MS DOS format. The problem is with their EOL (end of lines). The MAC options convert the windows CR/LF to the MAC CR only standard and LF when it is used in LINUX. See more detailed variation of csv format here.

(CR - carriage return , LF - line feed)

This runtime setting does it for me. Technically what it does is detecting what EOL configuration of a file have. So no matter what OS you have created teh csv file it PHP will detect it.

See: http://us.php.net/manual/en/filesystem.configuration.php#ini.auto-detect-line-endings

 ini_set("auto_detect_line_endings", true); 

May 30, 2012

Magento: Check if user is on Secure Page or Not

Not all Magento developers know fully on how to use magento methods in building their site. They sometimes even think that some functionality have no equivalent magento methods. One of the common methods that I have seen been neglected by developers is the Mage::app()->getStore()->isCurrentlySecure() method. It use to check if either the user is on a secure page or not. Instead of using this method we use the native counterpart on php which is:

<?php if($_SERVER['https'] == 'on') : ?>
<?php // HTTPS tracking code goes here ?>
<?php else : ?>
<?php // HTTP tracking code goes here ?>
<?php endif; ?>

You can write it using isCurrentlySecure like this:
<?php if (Mage::app()->getStore()->isCurrentlySecure()): ?>
<?php // HTTPS tracking code goes here ?>
<?php else : ?>
<?php // HTTP tracking code goes here ?>
<?php endif; ?>


I know that it is not a big issue but it would be nicer if you use magento methods as possible. The above code is also applicable when you are planning to put tracking scripts that have HTTPS and HTTP version.

May 28, 2012

PHP: Example of OOP - Database Class

One of the common nightmares for developers is to maintain repeated code in a single program which happen to be declared over and over again. Basically, what I'm trying to say is that it is frustrating to mae simple changes on the code yet finding yourself debugging the program due to since there are so many untracked code. Thanks to immersion of Object Oriented Programming which lessen the bummer by introducing the DRY (Don't Repeat Yourself). A tenet that allows you to group similar tasks into classes to avoid repeatition and make an easy maintain code. It also save your time since you don't need to keep declaring your code over and over again. If you haven't learn OOP, it's time for you to step up, you can visit and learn more about PHP Objected Oriented Programming by the following resources.

http://en.wikipedia.org/wiki/Object-oriented_programming
http://net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/
http://php.net/manual/en/language.oop5.php

I have here an example of OOP code and please be reminded that this is only for demonstration purposes. This class is called "Database". It allows you to query, fetch record etc... by using the methods defined on the class.

First File:

<?php
class Database 
{ 
 public $host     = "hostname";
 public $database = "databasename"; 
 public $username = "username"; 
 public $password = "password"; 
 public $conId    = 0;  
 public $queryId  = 0;  
    public $record   = array();  
    public $row;          
    public $errNo    = 0; 
    public $error    = ""; 
    
 //call connection method upon constructing 
 public function __construct(){
  $this->createConnection(); 
 }
 
 //connection to the database
 public function createConnection() 
    { 
        if( 0 == $this->conId ) 
            $this->conId=mysql_connect( $this->host, $this->username, $this->password ); 
        if( !$this->conId ) 
   $this->stopExec( "Trying to connect.... Result: failed" ); 
        if( !mysql_query( sprintf( "use %s", $this->database ), $this->conId ) ) 
            $this->stopExec( "cannot use database ".$this->database ); 
 } 

 //execute query string 
 public function query($queryString) 
    { 
  $this->queryId = mysql_query( $queryString, $this->conId ); 
        $this->row = 0; 
        $this->errNo = mysql_errno(); 
        $this->error = mysql_error(); 
        if(!$this->queryId ) 
   $this->stopExec( "Invalid SQL String: ".$queryString ); 
  return $this->queryId; // return the resource id of query. You can either then call fetchRecord method. 
    } 
 
 public function fetchRecord($type = 1)
 { 
  //1 --> for array
  //2 --> for object
  if($type == 1){
   $record = mysql_fetch_array($this->queryId); //return array
  }else{
   $record = mysql_fetch_object($this->queryId); //return object
  }
  
  return $record;
 }
 //stop the execution of query when there's an error
 public function stopExec( $msg ) 
 { 
  printf( "Database error: %s <br>n", $msg ); 
  printf( "MySQL Error: %s (%s)<br>n", $this->errNo, $this->error ); 
 } 
 
 //get the number of row
 public function numRows() 
 { 
  return mysql_num_rows( $this->queryId ); 
 } 
         
} 

?>

To try the code above. Save it as "database.php" then create another php file and paste the code below. Make sure that the two files are on the same directory and you had change the following variable values on the database class.

 public $host     = "hostname";
 public $database = "databasename"; 
 public $username = "username"; 
 public $password = "password"; 
Second file:

<?php
include('database.php');
$db = new Database();
$sql = "SELECT * from tablename"; 
$db->query($sql);
print_r($db->fetchRecord(1));
?>

Since, it is only for demonstration, it is not advisable to use this code for big project because of insufficiency. Using ORM (Object Relation Mapping) is still the best way in managing database in larger project. Although you can still use this is small scale project provided that you still need to edit their visibility properties etc. I hope this somewhat helpful to all. 

May 26, 2012

How to use Final Keyword on PHP OOP

As the word "final" signify itself, adding this prefix to your method or class signify that it can't be overridden. For methods that have "final" prefix will thrown a fatal error when you're trying to create the same object in your class. Furthermore, classes that have "final" prefix cannot be extended.

Here are the following examples:

Method with final Keyword:



<?php
class MyParentClass {
   public function test() {
       echo "ParentClass::test() called\n";
   }
   
   final public function anotherTesting() {
       echo "BaseClass::anotherTesting() called\n";
   }
}

class MyChildClass extends MyParentClass {
   public function anotherTesting() {
       echo "ChildClass::moreTesting() called\n";
   }
}
// Results in Fatal error: Cannot override final method MyChildClass::anotherTesting()

?> 


Class with final Keyword:

<?php
final class MyParentClass {
   public function test() {
       echo "ParentClass::test() called\n";
   }
   
   final public function anotherTesting() {
       echo "BaseClass::anotherTesting() called\n";
   }
}

class MyChildClass extends MyParentClass {
   public function anotherTesting() {
       echo "ChildClass::moreTesting() called\n";
   }
}
// Results in Fatal error: Class MyChildClass may not inherit from final class (MyParentClass)
?>


As you can see in the two examples above, both method and class can’t be overridden by its subclass. Doing so will throw an exception error and will break your code.

May 16, 2012

Retrieving Messages from your GMAIL account using PHP

Using imap library of PHP language you can access and retrieve messages in your gmail account. This is useful when you’re trying to back up or store your gmail messages in your local database or whatever purpose you want to do in the messages.

I created an example on how to do it in PHP and I will explain in detail on how to implement it.

Before we proceed:

1.Please make sure that you enabled the php_imap extension. If you are using wamp server, you can enable it by clicking wamp icon tray then go to "PHP->PHP extensions" and then look for php_imap on the list. Click it to enable then restart your wamp.

Now, let’s get down on the code!
<?php

//these are the variables that you need in order to 
//access your gmail account
//in this example, we were using gmail impa hostname 

$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'yourgmail@gmail.com';  // please change this into your correct gmail address. 
$password = 'yourgmailpassword'; // gmail password


//connect to your gmail... die and show error if can't connect 
$inbox = imap_open($hostname,$username,$password,OP_READONLY) or die('Cannot connect to Gmail: ' . imap_last_error());

//search messages on your gmail inbox. You can set other parameter
//in imap_search function and you can also further filter 
//this search function
//@ FROM "emailaddress@gmail.com" - you can change this to 
//the email address you want to retrieve the message 
$emails = imap_search($inbox,'FROM "emailaddress@gmail.com"');

//check if there are results on imap_search.... 
if($emails){

 //declare limit variable... this will limit the # of email to show. 
 $limit = 0; 
 
 //loop each email retrieve.
 foreach($emails as $email_number){
  
  //fetch the email over view... if you want to see the overview of the email.(OPTIONAL)
  $overview = imap_fetch_overview($inbox,$email_number,0);
  
  //fetch the email content body... This will show only the email content. 
  $message = imap_fetchbody($inbox, $email_number,"1");
  //set the message format to UTF-8
  $message = imap_utf8($message);
  
  //strip existing HTML tags to display text content only.(JUST COMMENT IT IF YOU WANT TO DISPLAY IT IN AN HTML FORMAT)
  $message = strip_tags($message);
  
  //add break in each line of the image. 
  $message = nl2br($message);
  
  //Now, you can either echo the image or USE for for other functions like saving in database. 
  echo $message;
  
  // increment limit 
  $limit++;
  
  //if limit is true. Break the loop and exit. 
  if($limit === 1)
   break;
  }
 
}
 
//close the imap connection
imap_close($inbox);


?>
Change the username and the password variable value to your gmail credential.

$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'yourgmail@gmail.com';  
$password = 'yourgmailpassword';

The following block of code connects you to gmail using your credential. Then, it will search the message using imap_search function.

$inbox = imap_open($hostname,$username,$password,OP_READONLY) or die('Cannot connect to Gmail: ' . imap_last_error());
$emails = imap_search($inbox,'FROM "emailaddress@gmail.com"');

If there are results on the imap_search. You are going to use the foreach loop to get each message content by using the imap_fetchbody. After that, you will need to set the message format to UTF-8, strip the message using strip_tags to exclude HTML tags. The nl2br function add break to your message. You also has option to limit the number of message by changing the "1" on the $limit === 1 conditional code. After the loop, imap_close is called to terminate the imap connection.

if($emails){

 
 $limit = 0; 
 
 foreach($emails as $email_number){
  
  $overview = imap_fetch_overview($inbox,$email_number,0);
  $message = imap_fetchbody($inbox, $email_number,"1");
  $message = imap_utf8($message);
  $message = strip_tags($message);
  $message = nl2br($message);
  
 
  echo $message;
  
  // increment limit 
  $limit++;
  
  
  if($limit === 1)
   break;
  }
 
}
 
imap_close($inbox);

Mar 1, 2012

Listrak and PHP Integration

Listrak is a full service email firm founded in 1999 that provides solutions and services that increases the value of your customer’s email. They developed strategies and marketing solutions that help the company to drive their ROI (Return of Investment) to its full potential.
Like most email service company, Listrak build their own API in order to manipulate web services. Listrak used SOAP (Simple Object Access Protocol) and WSDL (Web Service Definition Language). They also recommend SoapUI, a tool that provides the ability to invoke, inspect and stimulate web services.

Requirements
In order to integrate Listrak API on PHP you need the following requirements:
a. Listrak Account (Username and Password).
b. PHP Soap library

PHP Integration Sample Code
<?php
/**
* LISTRAK INTEGRATION
* @Requirements 
* 1. Listrak Account, Username and Password
*/

 $sh_param = array(
    'UserName' => "GTan", 
    'Password' => "Admin12345"
   ); 
        
  $authvalues = new SoapVar($sh_param, SOAP_ENC_OBJECT);
        
  $headers[] = new SoapHeader("http://webservices.listrak.com/v31/", 'WSUser', $sh_param ); 
 
  $soapClient = new SoapClient("https://webservices.listrak.com/v31/IntegrationService.asmx?WSDL", array('trace'=> 1, 'exceptions' => true, 
        'cache_wsdl' => WSDL_CACHE_NONE, 'soap_version' => SOAP_1_2));
         
          
   $soapClient->__setSoapHeaders($headers); 
  
  
 $params = array(
             'WSContact' => array(
      'EmailAddress' => 'test@test.com', 
             'ListID' => 259048, 
      'ContactProfileAttribute' => array(
    array('AttributeID' => 1480218 , 'Value' => 'duanereade')
         
   )  
   ), 
      'ProfileUpdateType' => 'Overwrite',
      'ExternalEventIDs' => "",
      'OverrideUnsubscribe' => TRUE
      );
  
try {

     $rest = $soapClient->SetContact($params);
  //  echo $rest->SetContactResult;

} catch (SoapFault $e) {
 
    echo '<pre>';
     print($e->getMessage());
     echo '</pre>';

}

?>
Code Breakdown


Note: If you don't have any idea on how to use SOAP it is better to read PHP SOAP Manual first.
Here is the detailed explanation of the code:

First off is supply the correct listrak credential. 
$sh_param = array(
    'UserName' => "YourListrakUsername", 
    'Password' => "YourListrakPassword"
   ); 

The second thing is to prepare the SoapVar and SoapHeader. Listrak use "http://webservices.listrak.com/v31/" for the namespace of the header element and "WSUser" for the name of the SoapHeader Object.
$authvalues = new SoapVar($sh_param, SOAP_ENC_OBJECT);
$headers[] = new SoapHeader("http://webservices.listrak.com/v31/", 'WSUser', $sh_param ); 

Connect to Listrak SoapClient using the defined headers and Listrak credentials.
$soapClient = new SoapClient("https://webservices.listrak.com/v31/IntegrationService.asmx?WSDL", array('trace'=> 1, 'exceptions' => true, 
        'cache_wsdl' => WSDL_CACHE_NONE, 'soap_version' => SOAP_1_2));
There are two parameters that you need to pass when calling SoapClient. The first is the WSDL URL, Listrak WSDL is https://webservices.listrak.com/v31/IntegrationService.asmx?WSDL. The second parameter are array option of the SoapClient. In this parameter you can set up several options such as soap version, exceptions etc. Please refer PHP SoapClient for more info.

Next, you need to set the Soap Header using the following setSoapHeader Object.

$soapClient->__setSoapHeaders($headers); 

In order to subscribe or set contact info on Listrak, you need to used their defined web methods. View complete list.
In this particular code, I used setContact method. This method will attempts to subscribe or update a contact to a specified list of with profile data and external events.


     $params = array(
             'WSContact' => array(
      'EmailAddress' => 'test@test.com',  
             'ListID' => 259048, 
      'ContactProfileAttribute' => array(
    array('AttributeID' => 1480218 , 'Value' => 'duanereade')
         
   )  
   ), 
      'ProfileUpdateType' => 'Overwrite',
      'ExternalEventIDs' => "",
      'OverrideUnsubscribe' => TRUE
 );

You can view the complete information about setContact method here.

Now, the last part is to pass the parameter to setContact method.
  
try {

     $rest = $soapClient->SetContact($params);
   echo $rest->SetContactResult;

} catch (SoapFault $e) {
 
    echo '<pre>';
     print($e->getMessage());
     echo '</pre>';

}

Jun 14, 2011

Hash-based Message Authentication Code Insight

Hash-based Message Authentication Code also known as HMAC is a specific construction in order to calculate a MAC or Message Authentication Code which primarily include cryptographic hash function that combined with secret key.

It is used to test the integrity and authenticity of a message. Most common HMAC Function is MD5 and SHA-1. Strength of the HMAC is based on the following.

1. The size of its HASH Output in bits
2. The quality and size of the KEY.

HMAC is commonly used in online transactions such as online orders. (e-commerce). The flow is that customer orders are encrypted with a secret key from the time it was processed. Then the owner, knowing the secret key will digest the encrypted order and confirm it if it’s not tampered.

HMAC sample Function

/**
* initialize key and message
* call function hmac
*/

<?php
$key = '4554ddeedd';
$message ='this is your message before encryption';

$encrypted_message = hmac($key, $message);

echo encrypted_message;
?>
<?php
function hmac ($key, $data)
{
// RFC 2104 HMAC implementation for php.
// Creates an md5 HMAC.

$b = 64; // byte length for md5
if (strlen($key) > $b) {
$key = pack("H*",md5($key));
}
$key = str_pad($key, $b, chr(0x00));
$ipad = str_pad('', $b, chr(0x36));
$opad = str_pad('', $b, chr(0x5c));
$k_ipad = $key ^ $ipad ;
$k_opad = $key ^ $opad;

return md5($k_opad . pack("H*",md5($k_ipad . $data)));
}
?>

hope it helps. View Regular Expression Sample.

May 13, 2011

Unable to Find Socket Transport SSL

I decided to move my blogspot blog to wordpress platform this day. But before doing so, I need to do a minor revision and configuration to avoid penalty from search engine when migration happens. The best environment to apply the changes is in local so I follow the standard import procedure of Wordpress. I set up Wordpress blog, installed it with import plugin and so on. I’m in the moment of excitement to see the success of importation until an error occured. "unable to find socket transport url". :( !!!. It seems that Google coudn't connect to my local environment with a non-secure connection.


So I look for a solution in the internet and I found this one.

The open_ssl extension in your wamp server is not enabled. In that case the Blogger will not allow you to access your account in not secured connection.
Here are steps to enable the open_ssl extension in your Wamp Server (IDK may be it is also apply in xampp).

1. First, you need to stop your wamp server.
2. Open your WAMP directory (it is usually installed in drive C: drive). Go to, C:\wamp\bin\php\php5.2.6 and copy libeay32.dll.
3. Now Go to your Apache Folder, C:\wamp\bin\apache\apache2.2.8\bin then paste the copied dll file.
4. After that, uncomment the ;extension=php_openssl.dll by altering the semi-colon.
5. Restart your wampserver and try importing again your blog.

Apr 19, 2011

Preg_Match Regular Expression Samples

This PHP function is usually use in searching a string. It compares the two strings (search_pattern and string_given) and return 0 or 1 value. 1 denotes successful return while 0 is failure.

Preg_Match Parameter

preg_match(search_patter, $string_given)

search_pattern – string which formatted in regular expression.
$string_given - a given string that you’re comparing to.

When to use Preg_match function?

Preg_match is usually used for search string functionality, string validation, manipulation of text. The most common use of preg_match is in validating email, phone number, name etc….
Here are some basic regular expression in using preg_macth function.

Important Notes Before you begin.

1. Preg_macth is case sensitive so better to user strtolower function in your $string given parameter.
2. Observe "/ /" format. Regular expressions are formed by starting with a forward slash /, followed by a sequence of special symbols and words to match, then another slash and, optionally, a string of letters that affect the expression.

BASIC
<?php
    if (preg_match("/test/", "test")) {
        echo "Got match!\n";
    }

    if (preg_match("/php/i", "php")) {
        echo "Got match!\n";
    }
   
?>
EMAIL

<?php

if (preg_match('/^[^@]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$/', $email)){
 echo "Email is valid!\n";
}

?>

DOMAIN
<?php

preg_match('@^(?:http://)?([^/]+)@i', "http://www.webdosh.net/index.html", $match);
$hostname = $match[1];

// get last two segments of host name
preg_match('/[^.]+\.[^.]+$/', $hostname, $match);
echo "domain name is: {$match[0]}\n";

?>

PHONE
<?php
if(! preg_match('/^\d{2}(-\d{3}){2}(\d{2})?$/', $phone)) {
echo "<p> Error message</p>";
}
?>

to see more examples visit php.net

Apr 14, 2011

Using mysql_select_db function

Before we can use the mysql_select_db function, we need to create first a connection to a database.

Connecting to a database is very simple. Here is the sample code.

<?php

$connection= mysql_connect("your_host","your_username","your_password");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

?>
After connecting to the database, what we need to do next is to select the database we will be interacting with. We have to call it using mysql_select_db function.

Lets first look at the basic syntax:

<?php mysql_select_db("database_name", $connection);?>

for example, I have a database named "sampledb" and I had used a variable "$connection" for my mysql connection. The code would look like this:



That’s it, you are now successfully connected and you have selected your database as well.

Happy coding!!!

Mar 24, 2011

Simple PHP / jQuery Contact Form

My last PHP snippet is about creating PHP/MySQL Login Form for any particular PHP/MYSQL system. Today I will give you another snippet, a Simple PHP / jQuery Contact Form. Contact us is essential element when having a website especially when you’re catering products online. This is pre-requisite to all e-commerce website to make contact page in order for their customer reach them to ask question / for just sending feedback. In this post I will show you on how to create a simple PHP and jQuery Ajax Contact Form.

Step Summary

1. Create file contact.php.
2. Create file contact_send.php

Details

1. Create a file contact.php

- this includes your form with input field along with their corresponding fields.
CODE:

<form id="contact-form">
Name : <input class="text" name="contact-names" type="text" />
<span class="name-required"></span>
Email :<input class="text" name="contact-email" type="text" />
<span class="email-required"></span>
<div class="comment">
Comment :</div>
<textarea class="text-area" name="contact-comment"></textarea>
<span class="comment-required"></span>
<input class="send" id="submit-form" name="submit" type="submit" value="" />
</form>

2. The next step is to create a contact_send.php file

<?php
 $names = $_POST['names'];
 $email = $_POST['email_address'];
 $comment = $_POST['comment'];
 $to ='your@email.com';
 
 $message = "";
 $message .= "*Name: " . htmlspecialchars($names, ENT_QUOTES) . "<br>\n";
 $message .= "*Email: " . htmlspecialchars($email, ENT_QUOTES) . "<br>\n";
 $message .= "Comment: " . htmlspecialchars($comment, ENT_QUOTES) . "<br>\n";
 $lowmsg = strtolower($message);
  
 $headers = "MIME-Version: 1.0\r\nContent-type: text/html; charset=iso-8859-1\r\n";
 $headers .= "From: \"" . $names . "\" <" . $email . ">\r\n";
 $headers .= "Reply-To: " .  $email . "\r\n";
 $message = utf8_decode($message);  mail($to, "Note from the Contact Form", $message, $headers);
 
 if ($message){
   echo 'sent';
 }else{
    echo 'failed';
 }
?>

3. Then the last thing you need to do is to add the jQuery Ajax functions that will call your contact_send.php file. Edit your contact.php file and add the following code:

IMPORTANT:  Don't forget to add the jQuery javascript at the the top of this code.

<script>$(document).ready(function(){
$('#submit-form').click(function(){
   
 var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
 var names  = $('#contact-form [name="contact-names"]').val();  
 var email_address = $('#contact-form [name="contact-email"]').val();
 var comment  = $.trim($('#contact-form .contact-comment').val());
   
  var data_html ='' ;
   
   
  if(names == ""){
       $('.name-required').html('Please enter your name <br/>.');
     }else{
       $('.name-required').html('');
     }
     if(email_address == ""){
       $('.email-required').html('Your email is required.');
     }else if(reg.test(email_address) == false){
       $('.email-required').html('Invalid Email Address.');
     }else{
       $('.email-required').html('');
     }
     
     if(comment == ""){
       $('.comment-required').html('Comment is required.');
     }else{
       $('.comment-required').html('');
     }
     
   if(comment != "" && names != "" && reg.test(email_address) != false){
   
    data_html = "names="+ names + "&comment=" + comment + "&email_address="+ email_address;
    
    //alert(data_html);
    
     $.ajax({
      type: 'POST',
      url: 'contact_send.php',
      data: data_html,
      success: function(msg){
       if (msg == 'sent'){
        $('#success').html('Message sent!')  ;
        $('#contact-form [name="contact-names"]').val('');  
        $('#contact-form [name="contact-email"]').val('');
         $('#contact-form .contact-comment').val('');
        
       }else{
        $('#success').html('Mail Error. Please Try Again.!')  ; 
       }
      }
   });
   
    }
      
   return false;
  })
})
</script>

Validation Output

Mar 15, 2011

Creating CSV file from SQL

CSV (Comma Separated Value) is commonly used in creating reports especially in PHP programs that requires reports. Since csv is in tabular format and allow different separator such as comma, extensions to allow numbers, the separator character, or newline characters in text fields. CSV are created by PHP script which allows users to download and save it as a copy. Please take a look at this example.

This is an example of database table.

Firstname
Lastname
MiddleName
Gender
Age
Janzell
Jurilla
Valguna
male
22
Rose
Test
Sison
female
19


The above table of data may be represented in CSV format

Generating CSV File from SQL

1. In order to query data from SQL you need to create SQL connection (create a php file and name it as connection.php). Insert the following code.



<?php 
#credentials details
$server_host = 'your_host';
$sql_username = 'your_username';
$sql_password = 'your_password';
$db = 'database_name';


#connect to sql server
$link = mysql_connect($server, $mysql_user, $mysql_password); 
if (!$link) { 
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db($db, $link);
if (!$db_selected) {  
die ('Can\'t use ' . $soc_db . ' : ' . mysql_error()); 
}

?>

2. Create another php file and rename it as generate_csv.php.

code: 

<?php
#include connection.php file 


include('connection.php');


# set a filename for your csv file 
$file_name ="filename.csv";


#opening the csv file 
$fp = fopen('/'.$file_name, 'w');   //make your csv file writable


#create a header text for your csv file
fputcsv($fp, array('header1', 'header2', 'header3 '));

$contents = "header1, header2, header3 \n";

#create a query statement 
$order_query = "SELECT * FROM tablename WHERE  condition";


$result = mysql_query($order_query);


if (mysql_num_rows($result) > 0) {
     while ($row = mysql_fetch_assoc($result)) { 


     #loop the row value  in $content variable, take note that row data below are only examples. Please replace this with your correct table fields
fputcsv($fp, array($row['header1_data'] , $row['header2_data'] , $row['header3_data']));
        $contents .= $row['header1_data']." , ".$row['header2_data']." , ".$row['header3_data']."\n"; 
     }
}else{
   echo "no records found";
}


#To generate csv and download this as attachment. 


header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$file_name);
echo $contents;

#close the csv file 
fclose($fp);


?>


3. Now try to access generate_csv.php in your browser. Make sure your using wamp / xampp or other Apache, PHP package.

Feb 26, 2011

Creating a MySQL/PHP Login Form

Login form in PHP is pretty much easy to do. We only need to know first how functionality works in a site. The first thing to know is why where going to have log-in functionality in your site? The common answer for this question is to have a customer / user management, create a community, a part of marketing strategy, or you only want to incorporate this thing in your site for no reason ;).


Pre-requisite before we proceed.


1. You must know how to query in MySQL.
2. Basic knowledge in HTML Form.
3. Of course PHP Language.

Step 1


Create a php file that includes your login form code. Ex. Index.php

<form action="login.php" method="POST">
<input name="username" type="text" />
<input name="password" type="password" />
<input type="submit" value="Login" /></form>

Step 2

Please take note the code above. Create a php file and name it login.php this is where you’re pointing your form action by using method POST. In this file insert your database connection code. Ex. If you created a database connection file separate file you might use this code.

Your connection.php file codes look like this.

<?php
        $conn=mysql_connect(‘your_host’, ‘your_username’,’your_password’);
         if (!$conn)
 {
   die('could not connect: '. mysql_error());
              }
   
 mysql_select_db("mydbase", $conn);

?>

You’re login.php code summary.

<?php 
 //start session
 session_start();

 //include mysql_connection.php to connect to the database
 require_once("connection.php"); 
 
 // Define $myusername and $mypassword
 $myusername=$_POST['username'];
 $mypassword=$_POST['password'];
 
 // To protect MySQL injection
 $myusername = mysql_real_escape_string($myusername);
 $mypassword = mysql_real_escape_string($mypassword);
 
 // encrypt password
 $encrypt = "janzell is awe";
 $mySha1 = sha1($encrypt);
 $encrypted_mypassword=md5($mypassword.$mySha1);

 // mySql query 
 $sql="SELECT *  FROM tbl_user WHERE user_name='$myusername' and user_password='$ encrypted_mypassword ";
 $result=mysql_query($sql);
   
    
 $count=mysql_num_rows($result);
  if ($count==1) {
   
   $data = mysql_fetch_assoc($result);
 $_SESSION['user'] = array('user_id' => $data['user_id'], 'real'=> $data['Firstname']. ' ' .$data['LastName']);
   
      header("location: menu.php");
  } 
  else {
    $error = "ERROR: Invalid Username / Password";
  }
  
  mysql_close();
?>



IMPORTANT:

Please put this code in every protected php file which is not visible in user unless they login.
<?php
 //start session
 session_start();
 session_regenerate_id();
 $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
 
 //is session set? if not, redirect the page to index.php
 if(!isset($_SESSION['user'])){
  header("location:index.php");
 }
 
 //checks if the user agent is not equal to current user agent. If not, destroy the session.
 if ($_SESSION['user_agent'] != $_SERVER['HTTP_USER_AGENT']){  
  session_destroy();
  exit();
 }
  
?>


You can also try this video tutorial.



Feb 1, 2011

PHP Image Replacement Dynamic Font Size

Most of web browser supports standard font-family in rendering a specific site. Some of these fonts are Arial, Times New Roman, Myriad Pro etc. So if you were using different font in your mock up design. You should cut those texts as image to maintain the looks and feel of your design. But what if there are bunch of text that using that font? Is it time consuming right?

One solution that work for that kind of stuff is to create a script which automatically create an image from a text you specified by class or id. The script will look for the class or id attributes and create images from the inner text of that class / id.


Marcofolio.net has already built up this script and finds it so far so good. I used this script in one of my client who use ziggurat font for their site as product title (Magento Site). The only flaws that I notice are that the script doesn’t support a font-size dynamically. You need to declare the font size variable with specific size.
Download it now.

How to make it run?


1. Once you download the files, extract it in your localhost.
2. Run the sample index.php and you can see the text in h1 tag is converted to images.

What if I’m using two or more class?


- As what I said earlier that the script doesn’t support dynamic font size (detecting the text font size of your class) you need to add some changes.
1. Open the ifr.js and find this -- replaceSelector(".title","ifr.php",true); --
.title - Tag (or Class) that will be replaced with images
ifr.php - Location of the PHP file that generates the images
true - Enable / Disable line breaks (Splits each word into an image so it can float)
test.png - Location of the test image

this is for single class only. To add another one you need to duplicate this replaceSelector(".yourClass","ifr.php",true);

2. Find the replacement() function and find this code:

var tokens = items[i].wordwrap ? text.split(' ') : [text] ;

Replace it with

var tokens = items[i].wordwrap ? text.split(' ') : [text] ;
var selectorChoose = items[i].selector.substr(1);
var size = document.getElementsByClassName(selectorChoose)[i].style.fontSize;

3. Below that code: edit this line:
var url = items[i].url + "?text="+escape(tokens[k]+' ')+"&selector="+escape(items[i].selector)+"&size="+size;

Replace with:
var url = items[i].url + "?text="+escape(tokens[k]+' ')+"&selector="+escape(items[i].selector)+"&size="+size;

4. Save it .
5. Now, Open the ifr.php file and replace the $font_size variable with $font_size = $_GET['size'] ;
6. Test it.


If you have any question, Please feel free to add comment.

Nov 25, 2010

Simple PHP script to change background color base on computer's date.

If you want to change you background color everyday, just copy the code below and try running it on your server supporting PHP. I do use wampserver to test and run it.

The lowercase L on the date function is used to display the full name of the day, like Monday. While changing it to d, it will display values or numbers from 1-7 which represents 7 days of the week. Changing it to D will display 3 letters, like for example: Mon, Tue, Wed, Thu, Fri, Sat, Sun.