Home

Wednesday, January 2, 2013

Download Simple CRUD application in codeigniter with Pagination and Image Upload with Resize

Download Simple CRUD application in CodeIgniter with Pagination and Image Upload with Resize.

Download Zip File : codeIgniter_cms.zip

Monday, December 31, 2012

How to configure pagination and fetch data in codeigniter?

How to configure pagination and fetch data in codeigniter.

Download this 3 Files :

Controller File : users.php
Model File       : users_model.php
View File         : userlist.php

How to Create Login Form in CodeIgniter


Step : 1

Default Libraries

In the file application/config/autoload.php you can configure the default libraries you want to load in all your controllers.  For our case, we’ll load the database and session libraries, since we want to handle user sessions, and also the URL helper for internal link generation

Before Line No : 55  $autoload['libraries'] = array();
After   Line No : 55  $autoload['libraries'] = array('database','session');

Before Line No : 67  $autoload['helper'] = array();
After   Line No : 67  $autoload['helper'] = array('url');

Encryption Key

When you use the session library, you need to set the encryption_key in the file application/config/config.php.

Before Line No : 227 $config['encryption_key'] = '';
After   Line No : 227 $config['encryption_key'] = '90b9aa7e25f80cf4f64e990b78a9fc5e';



Step : 2 Create Controller PHP file name is login.php path:(application/controllers/login.php)

login.php
==>
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class login extends CI_Controller
{  
    public function index()
    {
        $this->load->helper(array('form', 'url'));
        ////////  Form Validation Library Load //////////
        $this->load->library('form_validation');
       
        ///////// Session Library Load //////////////////
        $this->load->library('session');      
       
        ////////// Check Validation Form ////////////////
        $this->form_validation->set_error_delimiters('<span class="error">', '</span>');
        $this->form_validation->set_rules('username', 'username', 'required|min_length[3]|max_length[12]|trim');
        $this->form_validation->set_rules('password', 'password', 'required|min_length[2]|md5');
      
        if(!$this->form_validation->run())
        {
            $this->load->view('loginform');
        }
        else
        {          
            ///////// Database Liberary Load //////
            $this->load->database();
           
            ///////// Model Call for Login Check/////
            $this->load->model('login_model');          
           
            ///////////  Authentication Check Here //////////////////
            $result = $this->login_model->login($this->input->post('username'),$this->input->post('password'));
           
            if($result)
            {
                $sess_array = array();
                foreach($result as $row)
                {
                    $sess_array = array('id_users' => $row['id_users'],'username' => $row['username']);
                    $this->session->set_userdata('logged_in', $sess_array);
                }                                              
                redirect('home', 'refresh');
                 return TRUE;                                  
            }else
            {                          
                /////////// If Auth. is fail //////
                $data['message'] = "<font class='error'>Invalid username or password..!!</font>";                              
            }
            $this->load->view('loginform',$data);
        }        
    }  
}
?>


Step : 3 Create Model PHP file name is login_model.php  path:(application/models/login_model.php)

login_model.php
==>
 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class login_model extends CI_Model { 
  
    function login($username,$password)
    {  
        $query = "SELECT * FROM ci_users WHERE username = '".$username."' AND password = '".md5($password)."' LIMIT 1";  
        $sql = $this->db->query($query);      
       
        if($sql -> num_rows() == 1)
        {
            return $sql->result_array();
        }
        else
        {
            return false;
        }          
    }
}
?>


Step : 4 Create View PHP file name is loginform.php  path:(application/views/loginform.php)

loginform.php
==>
<style>
h1{
    color:#369;
    text-align:center;
}
h3{
    color:#C39;
}
table{
    border:2px solid #0CF;
    border-radius:10px;
}
th{
    text-align:left;
}
input[type="submit"],[type="reset"]
{
    background-color:#000;
    color:#FFF;
}
 .error{
    color:#F00;
}
.success{
    color:#00F;
}
</style>

<style>
h1{
    color:#369;
    text-align:center;
}
h3{
    color:#C39;
}
table{
    border:2px solid #0CF;
    border-radius:10px;
}
th{
    text-align:left;
}
input[type="submit"],[type="reset"]
{
    background-color:#000;
    color:#FFF;
}
 .error{
    color:#F00;
}
.success{
    color:#00F;
}
</style>
<?php echo form_open('login'); ?>
       
<h1>Login Form</h1>          
<table cellpadding="10" cellspacing="10" align="center">
<?php
if(@$message)
{
    ?>
        <tR>
            <td colspan="3" align="center"><?php echo $message;?></td>
        </tR>
    <?php
}
?>
    <tR>
        <td colspan="3"><h3>Login information</h3></td>
    </tR>
    <tR>
        <th><label for="username">Username <span class="required">*</span></label></th>
        <td><input type="text" name="username" id="username" value="<?php echo set_value('username'); ?>" class="contact_textfield"/><br><span><?php echo form_error('username'); ?></span></td>                </tR>
    <tR>
        <th><label for="password">Password <span class="required">*</span></label></th>
        <td><input type="password" name="password" class="contact_textfield"/><br><span><?php echo form_error('password'); ?></span></td>                  
    </tR>
  
   <tR>
        <td colspan="2" class="height45"><input type="submit" value="Login"  class="big_btn dark"/> &nbsp; <input type="reset" value="Reset" class="big_btn dark"></td>
    </tR>
  
</table>
     
<?php echo form_close(); ?>


Step : 5 Create Controller PHP file name is home.php  path:(application/controllers/home.php)

home.php
==>
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends CI_Controller {

 function __construct()
 {
   parent::__construct();
 }

 function index()
 {
   if($this->session->userdata('logged_in'))
   {
     $session_data = $this->session->userdata('logged_in');
     $data['username'] = $session_data['username'];
     $this->load->view('home', $data);
   }
   else
   {
     //If no session, redirect to login page
     redirect('login', 'refresh');
   }
 }

 function logout()
 {
   $this->session->unset_userdata('logged_in');  
   redirect('home', 'refresh');
 }
}

?>

Step : 6 Create View PHP file name is home.php  path:(application/views/home.php)

home.php
==>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
   <title>Simple Login with CodeIgniter - Private Area</title>
 </head>
 <body>
   <h1>Home</h1>
   <h2>Welcome <?php echo $username; ?>!</h2>
   <a href="home/logout">Logout</a>
 </body>
</html>



Step : 7 Run in Browser Like this http://localhost/codeIgniter/index.php/login



           

How to Create Registration Form with Mysql Database in CodeIgniter

Step : 1 First Download CodeIgniter_2.1.3c

Step :2 Create Table
          
 CREATE TABLE IF NOT EXISTS `ci_users` (
  `id_users` bigint(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `password` varchar(32) NOT NULL,
  `email` varchar(255) NOT NULL,
  `artist` varchar(100) NOT NULL,
  PRIMARY KEY (`id_users`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 ;


Step : 3 Set Database Configuration path:(application/config/database.php)

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'codeigniter';



Step : 4 Create Controller PHP file name is signup.php path:(application/controllers/signup.php)

signup.php
==>
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class signup extends CI_Controller
{  
    public function index()
    {
        $this->load->helper(array('form', 'url'));
        ////////  Form Validation Library Load //////////
        $this->load->library('form_validation');
      
        ///////// Session Library Load //////////////////
        $this->load->library('session');      
      
        ////////// Check Validation Form ////////////////
        $this->form_validation->set_error_delimiters('<span class="error">', '</span>');
        $this->form_validation->set_rules('username', 'username', 'required|min_length[3]|max_length[12]|trim');
        $this->form_validation->set_rules('password', 'password', 'required|min_length[2]|md5');
        $this->form_validation->set_rules('email', 'email', 'required|valid_email|trim');
        $this->form_validation->set_rules('artist', 'artist', 'max_length[32]|trim'); 
       
        if(!$this->form_validation->run())
        {
            $this->load->view('signupform');
        }
        else
        {  
            ///////// Database Liberary Load //////
            $this->load->database();
          
            ///////// Model Call for Data Insert /////
            $this->load->model('signup_model');          
          
            ///////////  Username already Exists or not Check Here //////////////////
            $user_name = $this->signup_model->duplicate_usercheck($this->input->post('username'));
          
            if($user_name == 0)
            {
                ////////// Data Insert Function call //////
                $this->signup_model->signup_user();          
              
                /////////// If data is Insert then Set Success Message //////
                $data['message'] = "<font class='success'>Registration Successfully..!!</font>";
            }else
            {                          
                /////////// If Duplicate Entry in database then Set Error Message //////
                $data['message'] = "<font class='error'>Username is Allready in Database..!!</font>";              
            }
            $this->load->view('signupform',$data);          
        }       
    }   
}
?> 


Step : 5 Create Model PHP file name is signup_model.php  path:(application/models/signup_model.php)

signup_model.php
==>
 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class signup_model extends CI_Model {
  
    function signup_user()
    {      
        $data['username'] = $this->input->post('username');
        $data['password'] = sha1($this->input->post('password'));      
        $data['email'] = $this->input->post('email');
        $data['artist'] = $this->input->post('artist');
        $this->db->insert('ci_users', $data);
    }
  
    function duplicate_usercheck($username)
    {
         $q =  $this->db->select('username')
                   ->from('ci_users')
                   ->where(array('username' => $username))->get();
        return $q->num_rows();              
    }
}
?>


Step : 6  Create View PHP file name is signupform.php  path:(application/views/signupform.php)

signupform.php
==>
<style>
h1{
    color:#369;
    text-align:center;
}
h3{
    color:#C39;
}
table{
    border:2px solid #0CF;
    border-radius:10px;
}
th{
    text-align:left;
}
input[type="submit"],[type="reset"]
{
    background-color:#000;
    color:#FFF;
}
 .error{
    color:#F00;
}
.success{
    color:#00F;
}
</style>

<?php echo form_open('signup'); ?>
       
<h1>Registration Form</h1>           
<table cellpadding="10" cellspacing="10" align="center">
<?php
if(@$message)
{
    ?>
        <tR>
            <td colspan="3" align="center"><?php echo $message;?></td>
        </tR>
    <?php
}
?>
    <tR>
        <td colspan="3"><h3>Account information</h3></td>
    </tR>
    <tR>
        <th><label for="username">Choose a username <span class="required">*</span></label></th>
        <td><input type="text" name="username" id="username" value="<?php echo set_value('username'); ?>" class="contact_textfield"/><br><span><?php echo form_error('username'); ?></span></td>                </tR>
    <tR>
        <th><label for="password">Pick a password <span class="required">*</span></label></th>
        <td><input type="password" name="password" class="contact_textfield"/><br><span><?php echo form_error('password'); ?></span></td>                   
    </tR>
    <tR>
        <th><label for="email">Enter your valid email address <span class="required">*</span></label></th>
        <td><input type="text" name="email" id="email" value="<?php echo set_value('email'); ?>" class="contact_textfield"/><br><span><?php echo form_error('email'); ?></span></td>                </tR>
   
    <tR>
        <td colspan="3"><h3>About you</h3></td>
    </tR>
    <tR>
        <th><label for="band">Who's your favorite artist?</label></th>
        <td><input type="text" name="artist" value="<?php echo set_value('artist'); ?>" class="contact_textfield"/> <br><span><?php echo form_error('artist'); ?></span></td>                </tR>
   
   <tR>
        <td colspan="2" class="height45"><input type="submit" value="Register"  class="big_btn dark"/> &nbsp; <input type="reset" value="Reset" class="big_btn dark"></td>
    </tR>
   
</table>      
<?php echo form_close(); ?>
          




Step : 7 Run in Browser Like this http://localhost/codeIgniter/index.php/signup



           

Saturday, December 29, 2012

How can I overlay a div with semi-transparent opacity over a youtube iframe embedded video?

How can I overlay a div with semi-transparent opacity over a 
youtube iframe embedded video?
 
<iframe type="text/html"  
    src="http://www.youtube.com/embed/NWHfY_lvKIQ">
</iframe> 
 
Make sure its the first parameter in the URL. Other parameters must go after
  
Example :
<iframe type="text/html"   
  src="http://www.youtube.com/embed/NWHfY_lvKIQ?wmode=opaque">
</iframe>
 

Tuesday, December 18, 2012

How to insert data from excel into database using php

If you have Excel files that need to be imported into MySQL, you can import them easily with PHP. First, you will need to download some prerequisites:
 
Step 1 : you can use PHPExcel (download library )

Ster 2 : Create import.php file 

<?php
mysql_connect("localhost","root","");
mysql_select_db("test") or die(mysql_error());

require_once 'Classes/PHPExcel/IOFactory.php';
$objPHPExcel = PHPExcel_IOFactory::load("test.xlsx");

foreach ($objPHPExcel->getWorksheetIterator() as $worksheet)
{
    $worksheetTitle     = $worksheet->getTitle();
    $highestRow         = $worksheet->getHighestRow();
    $highestColumn      = $worksheet->getHighestColumn();
    $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
    $nrColumns = ord($highestColumn) - 64;   
   
    for ($row = 2; $row <= $highestRow; ++ $row)
    {
        $name = $worksheet->getCellByColumnAndRow(0, $row)->getValue();      
        $age = $worksheet->getCellByColumnAndRow(1, $row)->getValue();      
        $email = $worksheet->getCellByColumnAndRow(2, $row)->getValue();          
      
        $sql_get = "INSERT INTO user (name,code,sub_dept) VALUES ('".$name."','".$age."','".$email."')";
        mysql_query($sql_get) or die(mysql_error());
    }   
}
?>

 


Wednesday, December 12, 2012

How to create a simple and efficient PHP cache

Step one: Create the top-cache.php file

<?php
$url = $_SERVER["SCRIPT_NAME"];
$break = Explode('/', $url);
$file = $break[count($break) - 1];
$cachefile = 'cached-'.substr_replace($file ,"",-4).'.html';
$cachetime = 18000;

// Serve from the cache if it is younger than $cachetime
if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) {
    echo "<!-- Cached copy, generated ".date('H:i', filemtime($cachefile))." -->\n";
    include($cachefile);
    exit;
}
ob_start(); // Start the output buffer
?>
 

Step two: Create the bottom-cache.php file

<?php
// Cache the contents to a file
$cached = fopen($cachefile, 'w');
fwrite($cached, ob_get_contents());
fclose($cached);
ob_end_flush(); // Send the output to the browser
?>
 

Step three: Include cache files on your page

 <?php

include('top-cache.php'); 

// Your regular PHP code goes here
echo " How to create a simple and efficient PHP cache"; 
 
include('bottom-cache.php');
?>

 

 

 

Thursday, December 6, 2012

How to Create SEO friendly URL using .htaccess

Options +FollowSymlinks
RewriteEngine on

RewriteRule ^products/([0-9]+)/([A-Za-z0-9-]+)/?$ products_details.php?pd_id=$1&prd_name=$2 [NC,L] # Handle product requests


Example : www.xyz.com/products_details.php?pd_id=51&prd_name=laptop

And you want to change them to look like this:

www.xyz.com/products/51/laptop 

Friday, November 30, 2012

How do I rewrite .php to .html using .htaccess rules?


I want to convert .php extension to .html extension using .htaccess rules
RewriteEngine on
RewriteRule ^(.*)\.html$ $1.php [nc]
Example : index.php to index.html

Saturday, November 10, 2012

How To Create an IE-Only Stylesheet


Target ALL VERSIONS of IE

<!--[if IE]>
 <link rel="stylesheet" type="text/css" href="all-ie-only.css" />
<![endif]-->

Target everything EXCEPT IE

<!--[if !IE]><!-->
 <link rel="stylesheet" type="text/css" href="not-ie.css" />
 <!--<![endif]-->

Target IE 7 ONLY

<!--[if IE 7]>
 <link rel="stylesheet" type="text/css" href="ie7.css">
<![endif]-->

Target IE 6 ONLY

<!--[if IE 6]>
 <link rel="stylesheet" type="text/css" href="ie6.css" />
<![endif]-->

Target IE 5 ONLY

<!--[if IE 5]>
 <link rel="stylesheet" type="text/css" href="ie5.css" />
<![endif]-->

Target IE 5.5 ONLY

<!--[if IE 5.5000]>
<link rel="stylesheet" type="text/css" href="ie55.css" />
<![endif]-->

Target IE 6 and LOWER

<!--[if lt IE 7]>
 <link rel="stylesheet" type="text/css" href="ie6-and-down.css" />
<![endif]-->
<!--[if lte IE 6]>
 <link rel="stylesheet" type="text/css" href="ie6-and-down.css" />
<![endif]-->

Target IE 7 and LOWER

<!--[if lt IE 8]>
 <link rel="stylesheet" type="text/css" href="ie7-and-down.css" />
<![endif]-->
<!--[if lte IE 7]>
 <link rel="stylesheet" type="text/css" href="ie7-and-down.css" />
<![endif]-->

Target IE 8 and LOWER

<!--[if lt IE 9]>
 <link rel="stylesheet" type="text/css" href="ie8-and-down.css" />
<![endif]-->
<!--[if lte IE 8]>
 <link rel="stylesheet" type="text/css" href="ie8-and-down.css" />
<![endif]-->

Target IE 6 and HIGHER

<!--[if gt IE 5.5]>
 <link rel="stylesheet" type="text/css" href="ie6-and-up.css" />
<![endif]-->
<!--[if gte IE 6]>
 <link rel="stylesheet" type="text/css" href="ie6-and-up.css" />
<![endif]-->

Target IE 7 and HIGHER

<!--[if gt IE 6]>
 <link rel="stylesheet" type="text/css" href="ie7-and-up.css" />
<![endif]-->
<!--[if gte IE 7]>
 <link rel="stylesheet" type="text/css" href="ie7-and-up.css" />
<![endif]-->

Target IE 8 and HIGHER

<!--[if gt IE 7]>
 <link rel="stylesheet" type="text/css" href="ie8-and-up.css" />
<![endif]-->
<!--[if gte IE 8]>
 <link rel="stylesheet" type="text/css" href="ie8-and-up.css" />
<![endif]-->
 

Hacks

IE-6 ONLY

* html #div { 
    height: 300px;
}

IE-7 ONLY

*+html #div { 
    height: 300px;
}

IE-8 ONLY

#div {
  height: 300px\0/;
}

IE-7 & IE-8

#div {
  height: 300px\9;
}

NON IE-7 ONLY:

#div {
   _height: 300px;
}

Hide from IE 6 and LOWER:

#div {
   height/**/: 300px;
}
html > body #div {
      height: 300px;
}

 

 

Monday, October 29, 2012

PHP Interview Questions


PHP Interview Questions 
1. What's PHP ?

The PHP Hypertext Preprocessor is a programming language that allows web developers to create dynamic content that interacts with databases. PHP is basically used for developing web based software applications.

2. How can we know the number of days between two given dates using PHP?

$date1 = date('Y-m-d');
$date2 = '2006-07-01';
$days = (strtotime($date1) - strtotime($date2)) / (60 * 60 * 24);
echo "Number of days since '2006-07-01': $days";

3. How do you define a constant?
 define ("MYCONSTANT", 100);

4. What is meant by urlencode and urldecode?

urlencode() returns the URL encoded version of the given string. URL coding converts special characters into % signs followed by two hex digits.
For example:
urlencode("10.00%") will return "10%2E00%25". URL encoded strings are safe to be used as part of URLs.
urldecode() returns the URL decoded version of the given string.

5. How To Get the Uploaded File Information in the Receiving Script?

 Uploaded file information is organized in $_FILES as a two-dimensional array as:
$_FILES[$fieldName]['name'] - The Original file name on the browser system.
$_FILES[$fieldName]['type'] - The file type determined by the browser.
$_FILES[$fieldName]['size'] - The Number of bytes of the file content.
$_FILES[$fieldName]['tmp_name'] - The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES[$fieldName]['error'] - The error code associated with this file upload.

6. What is the difference between mysql_fetch_object and mysql_fetch_array?

MySQL fetch object will collect first single matching record where mysql_fetch_array will collect all matching records from the table in an array

7. How do you pass a variable by value?

Just like in C++, put an ampersand in front of it, like $a = &$b.

8. How can we send mail using JavaScript?
No. There is no way to send emails directly using JavaScript.

But you can use JavaScript to execute a client side email program send the email using the "mailto" code. Here is an example:

function myfunction(form)
{
tdata=document.myform.tbox1.value;
location="mailto:mailid@domain.com?subject=...";
return true;
}

9. What is the difference between ereg_replace() and eregi_replace()?

eregi_replace() function is identical to ereg_replace() except that it ignores case distinction when matching alphabetic characters.

10. How do I find out the number of parameters passed into function ?
func_num_args() function returns the number of parameters passed in.

11. Are objects passed by value or by reference?
Everything is passed by value.

12. What are the differences between DROP a table and TRUNCATE a table?

DROP TABLE table_name - This will delete the table and its data.
TRUNCATE TABLE table_name - This will delete the data of the table, but not the table definition.

13. How do you call a constructor for a parent class?
parent::constructor($value)

14. How can we submit a form without a submit button?

If you don't want to use the Submit button to submit a form, you can use normal hyper links to submit a form. But you need to use some JavaScript code in the URL of the link.
<a href="javascript: document.myform.submit();">Submit Me</a>

15. How can we extract string 'abc.com ' from a string http://info@abc.com using regular expression of php?

We can use the preg_match() function with "/.*@(.*)$/" as the regular expression pattern.
For example:
preg_match("/.*@(.*)$/","http://info@abc.com",$data);
echo $data[1];

16. What is the difference between the functions unlink and unset?

unlink() is a function for file system handling. It will simply delete the file in context.
unset() is a function for variable management. It will make a variable undefined.

17. What is the difference between characters \047 and \x47?
The first one is octal 47, the second is hex 47.

18. How can we create a database using PHP and mysql?

We can create MySQL database with the use of mysql_create_db($databaseName) to create a database.

19. How can we destroy the session, how can we unset the variable of a session?
session_unregister() - Unregister a global variable from the current session
session_unset() - Free all session variables

20. How can we know the count/number of elements of an array?

a) sizeof($array) - This function is an alias of count()
b) count($urarray) - This function returns the number of elements in an array.
Interestingly if you just pass a simple var instead of an array, count() will return 1

21. How many values can the SET function of MySQL take?

MySQL SET function can take zero or more values, but at the maximum it can take 64 values.

22. What are the other commands to know the structure of a table using MySQL commands except EXPLAIN command?

DESCRIBE table_name;

23. How can we find the number of rows in a table using MySQL?

SELECT COUNT(*) FROM table_name;

24. How can we find the number of rows in a result set using PHP?

$result = mysql_query($any_valid_sql, $database_link);
$num_rows = mysql_num_rows($result);
echo "$num_rows rows found";

25. What is the difference between CHAR and VARCHAR data types?

CHAR is a fixed length data type. CHAR(n) will take n characters of storage even if you enter less than n characters to that column. For example, "Hello!" will be stored as "Hello! " in CHAR(10) column.
VARCHAR is a variable length data type. VARCHAR(n) will take only the required storage for the actual number of characters entered to that column. For example, "Hello!" will be stored as "Hello!" in VARCHAR(10) column.

26. What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()?

mysql_fetch_array - Fetch a result row as an associative array and a numeric array.
mysql_fetch_object - Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows
mysql_fetch_row() - Fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

27. What is the difference between htmlentities() and htmlspecialchars()?

htmlspecialchars() - Convert some special characters to HTML entities (Only the most widely used)
htmlentities() - Convert ALL special characters to HTML entities

28. How can we get the properties (size, type, width, height) of an image using php image functions?

image size use getimagesize() function
image width use imagesx() function
image height use imagesy() function

29. How can we increase the execution time of a php script?

By the use of void set_time_limit(int seconds)

30. What are the difference between abstract class and interface?

Abstract class: abstract classes are the class where one or more methods are abstract but not necessarily all method has to be abstract. Abstract methods are the methods, which are declare in its class but not define. The definition of those methods must be in its extending class.
Interface: Interfaces are one type of class where all the methods are abstract. That means all the methods only declared but not defined. All the methods must be define by its implemented class.

31. What is the maximum size of a file that can be uploaded using PHP and how can we change this?

change maximum size of a file set upload_max_filesize variable in php.ini file

32. Explain the ternary conditional operator in PHP?

Expression preceding the ? is evaluated, if it’s true, then the expression preceding the : is executed, otherwise, the expression following : is executed.

33. What’s the difference between include and require?

It’s how they handle failures. If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.

34. How many ways can we get the value of current session id?

session_id() returns the session id for the current session.

35. What is the difference between $message and $$message?

They are both variables. But $message is a variable with a fixed name. $$message is a variable who's name is stored in $message. For example, if $message contains "var", $$message is the same as $var.

36. How can we get the browser properties using php?

<?php
echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";
$browser = get_browser(null, true);
print_r($browser);
?>

37. How can we know that a session is started or not?

A session starts by session_start()function.
this session_start() is always declared in header portion.it always declares first.then
we write session_register().

38. What is the use of obj_start()?

Its intializing the object buffer, so that the whole page will be first parsed (instead of parsing in parts and thrown to browser gradually) and stored in output buffer so that after complete page is executed, it is thrown to the browser once at a time.

39. What is the difference between Split and Explode?

split()-used for JavaScript for processing the string and the explode()-used to convert the String to Array, implode()-used for convert the array to String
Here the Example
<?php
$x="PHP is a ServerSide Scripting Language";
$c=explode(" ",$x);
print_r($c);
$d=implode(" ",$c);
echo "
".$d;
?>
Javascript Example:
list($month, $day, $year) = split('[/.-]', $date);

40. Which will execute faster on php POST or GET?

Both are same while performing the action but using POST security is there.
Because using GET method in the action, form field values send along with URL, so at the time of sending password, problem will occur means password also will shown in the URL.
Using of POST there is no problem.

GET method has a limit of sending parameters 100 characters but POST method does not have a limit of sending data

GET is faster than POST. Because GET fetch the data directly from the URL but POST method fetch the encrypted data from the page.

41. What is the use of sprintf() function?

The sprintf() function writes a formatted string to a variable.

42. What Is a Session?

Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same visitor.

43. What is the use of header() function in php?

The header() function is used for redirect the page.if you want to redirect one page to another we can use it.

44. How can i get ip address?

REMOTE_ADDR - the IP address of the client
REMOTE_HOST - the host address of the client

45. What is htaccess?

.htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis.

46. What is the diffrence between Notify URL and Return URL?

Notify URL is used to just notify the status while processing.
Return URL is used to return after processing.

47. What is the difference between ucfirst and ucwords?

ucfirst() to convert the first letter of every string to uppercase, and ucwords(), to convert the first letter of every word in the string to uppercase.

48. What is meant by nl2br()?

nl2br() inserts a HTML tag <br> before all new line characters \n in a string.

49. How To Read the Entire File into a Single String?

<?php
$file = file_get_contents("/windows/system32/drivers/etc/services");
print("Size of the file: ".strlen($file)."n");
?>

50. What are the different functions in sorting an array?

Sorting functions in PHP:
asort()
arsort()
ksort()
krsort()
uksort()
sort()
natsort()
rsort()  

Structure Of A WordPress Theme


There are a couple different types of pages in WordPress. Each type of page can have a customized look and feel. This customization is done by templates. Templates are how themes work. Each template is a seperate PHP file inside the theme’s directory. Here are the standard templates:
  • 404 Template = 404.php – It’s handy to create a custom 404 page (Page Not Found) template. You can list common links and ways for users to find what they are looking for.
  • Archive Template = archive.php
  • Archive Index Page = archives.php
  • Comments Template = comments.php – This template defines how comments look under individual posts on the “Post Template”.
  • Footer Template = footer.php – HTML that is placed at the bottom of each page, saves you time and produces less duplicate HTML code in your templates.
  • Header Template = header.php – HTML that is placed at the top of each page, usually has the <head> section in it.
  • Links = links.php
  • Main Template = index.php – Usually this page lists your most recent posts. This is the “home” page of your site.
  • Page Template = page.php – Used for single pages, instead of blog posts. Your “About” page uses this template. This is the default page template, you can make your own custom page templates. I’ll cover this more in detail later.
  • Popup Comments Template = comments-popup.php
  • Post Template = single.php – This is where you customize pages that display single posts. Click on a post title (permalink) and you will be at it’s single post page using the post template.
  • Search Form = searchform.php
  • Search Template = search.php
  • Sidebar Template = sidebar.php – Usually the right hand side bar of the page. Some themes have more than one side bar so you’ll see templates like left_sidebar.php.
  • Stylesheet = style.css – Default place to put your CSS. It also contains the name and description of the theme. You must always have this file with the name and description of your theme. Many themes will have multiple CSS files that are linked to from the header.php file or the individual page templates to customize individual pages with different style rules.   

Thursday, October 18, 2012

Display submenu on left side on all pages

<?php
if($post->post_parent)
$children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0");
else
$children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0");
if ($children) { ?>
    <?php echo $children; ?>
<?php } ?>

Tuesday, September 18, 2012

How to Upload and Unpack a Zip File using PHP


<?php
error_reporting(0);
if($_FILES["zip_file"]["name"]) {
 $filename = $_FILES["zip_file"]["name"];
 $source = $_FILES["zip_file"]["tmp_name"];
 $type = $_FILES["zip_file"]["type"];
 
 $name = explode(".", $filename);
 $accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
 foreach($accepted_types as $mime_type) {
  if($mime_type == $type) {
   $okay = true;
   break;
  } 
 }
 
 $continue = strtolower($name[1]) == 'zip' ? true : false;
 if(!$continue) {
  $message = "The file you are trying to upload is not a .zip file. Please try again.";
 }
 
 $target_path = "/home/var/yoursite/httpdocs/".$filename;  // change this to the correct site path
 if(move_uploaded_file($source, $target_path)) {
  $zip = new ZipArchive();
  $x = $zip->open($target_path);
  if ($x === true) {
   $zip->extractTo("/home/var/yoursite/httpdocs/"); // change this to the correct site path
   $zip->close();
 
   unlink($target_path);
  }
  $message = "Your .zip file was uploaded and unpacked.";
 } else { 
  $message = "There was a problem with the upload. Please try again.";
 }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
 
<body>
<?php if($message) echo "<p>$message</p>"; ?>
<form enctype="multipart/form-data" method="post" action="">
<label>Choose a zip file to upload: <input type="file" name="zip_file" /></label>
<br />
<input type="submit" name="submit" value="Upload" />
</form>
</body>
</html>

htaccess rewrite rule to remove a subfolder from a URL


This will assume you have http://domain.com/sub as where the content you want to load is.  And the resulting URL to only show http://domain.com butstill load the content in in the /sub folder.

This could be modified many ways to suit the needs for the application at hand.

RewriteEngine On
RewriteRule ^$ sub/
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)$ sub/$1
rathoddhirendra.blogspot.com-Google pagerank and Worth