Tuesday, 11 June 2013

How to convert data type from one format to another in PHP

PHP is a loosely typed language that means We do not need to define the data type of variable in php.

Data types of variables are implicitly converted to another format based upon the context in which it is used.

So it relies on the developer to use correct code while comparing 2 or more values.

How to search a value in array in php

If you want to search an array in php and find it's corresponding key you can use in built array function.
array_search.

Example with Code and syntax :

<?php
$myarr=array("x"=>"Amol","y"=>"Sagar","z"=>"ganesh");

//search for Amol in myarr

echo (array_search("Amol",$myarr));

//This will print x

?>

This is how we can find the key corresponding to the value in php

How to remove duplicate values from array in php

In php we have in built array function that can be used to remove duplicate values from the array.

Example with code and syntax:

<?php
$myarr=array("x"=>"Amol","y"=>"Sagar","z"=>"Amol");
print_r(array_unique($myarr));
?>


Above code will remove the third element z=Amol from array and return the array with unique values.

This is how we can remove duplicate values from an array in PHP.



How to check if array contains particular value in php

In php we have one function called in_array that can be used to find if the value exists in array

Example with Code and Syntax - 

<?php
$myarr = array("Amol", "Sagar");

if (in_array("Amol",$myarr))
  {
  echo "Amol exists in array";
  }
else
  {
  echo "Amol does not exist in array";
  }
?>

Please remember that if the first parameter is a string and the third parameter is TRUE, searching  is case-sensitive.

This is how we check if particular value exists in an array in php.

How to get the size of array in php?

We can find out the size of array in 2 ways in php.

  1. Sizeof function
  2. Count function

Example with code and syntax - 


So if you have an array say 

$myarr = array('sd','fgf')

echo count($myarr) ;

//This will print 2 .

Both functions take second argument as 0 or 1.

If you pass 0, then it will not count all elements of multi dimensional array
If you pass 1, then it will count all elements of multi dimensional array

This is how you can get the size of array. Or total number of elements in array in php.

How to use Ajax in php to get data from server?

Ajax is a technology that helps us load the data from server without loading the whole page.
We can make ajax calls that send requests to server and display the result on the fly without loading the page.

Below java script code will demonstrate how we can use ajax in php.

<script>
function getajaxdata(param)
{

  xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
      {
         alert ( xmlhttp.responseText );
      }
  }

 xmlhttp.open("GET","ajaxserverpage.php?p="+param,true);
 xmlhttp.send();
}
</script>

As shown above We have made an ajax call using below line

 xmlhttp.open("GET","ajaxserverpage.php?p="+param,true);

Here what we are trying to do is calling the script in ajaxserverpage.php page .

When the server sends the response we are showing it to user. Normally you will display the response in some section on your page.









Monday, 10 June 2013

How to read contents of xml file in php?


To read an xml file in php we have 3 ways.

  • SimpleXML (in php 5 and onwards)
  • Expat Parser
  • XML DOM
I am going to show you the easiest way to process/read xml file in php using SimpleXML.

Example with Code and Syntax:




<?xml version="1.0" encoding="ISO-8859-1"?>
<book>
<name>PHP</name>
<price>68</price>
</book>


<?php
$xml=simplexml_load_file("book.xml");
echo $xml->name. "<br>";
echo $xml->price. "<br>";
 ?>



As show in above example, I have loaded book.xml file and read the contents using simplexml_load_file function.

How to connect to Microsoft Access database in php

To connect to any ODBC database like MS-Access, php provides odbc_connect method.
Before you connect to any ODBC database you have to create a DSN for that database using Admin.Tools
You follow below steps to create a DSN.

  • Go to Administrative tools in control panel
  • Click on Data Sources (ODBC)
  • Follow steps on screen to create a dsn for database 
  • You can create dsn for any database which provides ODBC API.
Now Let's assume you have created one DSN called mydsn.

Example with code and syntax :-


// Connect to ODBC DB
$myconn=odbc_connect('mydsn','','');


$mysql="SELECT * FROM emp_db";

// Execute a query on ODBC db

$myrecordset=odbc_exec($myconn,$mysql);

//fetch records from recordset from ODBC database
while (odbc_fetch_row($myrecordset))
  {
  $age=odbc_result($myrecordset,"age");
 echo $age;

  }

odbc_close($myconn);
//Close database connection


Above example show how we can connect to ODBC database like MS-Access using dsn and execute query on it.


How to read a record from mysql database in php - Where clause


Getting a data from mysql database is again very simple task in php.
You have to follow below steps -

  • Connect to MYSQL DB
  • Execute any select query ....This will return the record set
  • Use while loop to iterate through each record 



<?php
$mysqlcon=mysqli_connect("localhost","uid","password","emp_db");

// connect to mysql database using userid and password

if (mysqli_connect_errno())
  {
  echo "Error while connecting to MySQL: " . mysqli_connect_error();
  }

//***********Connection Successful to emp_db database  in mysql************


// Now you can add a record in mysql database

$dbresult = mysqli_query($mysqlcon,"SELECT * FROM emp_db
WHERE age=20");

//dbresult contains the recordset....Now read each record from that set.

while($myrecord = mysqli_fetch_array($dbresult ))
  {
  echo $
myrecord ['name'] ;
  echo "<br>";
  }

?>

This is how we can read values from a mysql database table.

How to insert a record in mysql database in php

Inserting a record or data into mysql database  tables is very easy task.
We can use mysqli_query function to execute the query to add a record in table.

Example with code and syntax : 

<?php
$mysqlcon=mysqli_connect("localhost","uid","password","emp_db");

// connect to mysql database using userid and password

if (mysqli_connect_errno())
  {
  echo "Error while connecting to MySQL: " . mysqli_connect_error();
  }

//***********Connection Successful to emp_db database  in mysql************


// Now you can add a record in mysql database



mysqli_query($mysqlcon,"INSERT INTO emp_db(empname,empid)
VALUES ('sagar', 234343)");

mysqli_close($mysqlcon);

//close the connection from mysql database
?>

If there is any error while running above script, we are printing that as well.

How to create a MYSQL database in PHP

Creating a MYSQL database in php is a simple task. 

There are 2 steps in the process
  • Connect to MYSQL database
  • Fire a query to create a database in MYSQL
Example with Code and Synatx:



<?php
$mysqlcon=mysqli_connect("localhost","uid","password");

// connect to mysql using userid and password

if (mysqli_connect_errno())
  {
  echo "Error while connecting to MySQL: " . mysqli_connect_error();
  }

//*********************Connection Successful**************************
// Now you can create database

$querysql="CREATE DATABASE EMP";
if (mysqli_query($mysqlcon,$querysql))
  {
  echo "Database EMP created .......";
  }
else
  {
  echo "Error creating database: " . mysqli_error($mysqlcon);
  }
?>


In above example we have created the database called EMP. If there is any error while connecting  to MYSQL server or creating a database in MYSQL we are printing that as well.

What is the use of filter_var function in PHP


In any web application development you must ensure that data coming from user is valid. To validate the user input data or any variable you can use the function filter_var .

Synatx and example of filter_var  function is given below

filter_var(variable_to_Filetr, type_of_filter, filter_options)



<?php
$var= 44;

if(!filter_var($var, FILTER_VALIDATE_INT))
  {
  echo("Variable is not valid integer");
  }
else
  {
  echo("variable is Integer");
  }
?>

In above code you will find that we are validating the variable to check if it is integer or not.


What is the use of die function in php?

When error occurs in php script, it displays the error information to user in php.

Sometimes we have to stop the execution of the script, at that time you can use die function.

This function will stop the execution of php script. That means Script statements followed by die() will not execute.

die("Error occured .....stopping script");

Thus the use of die function is to suspend the execution of the script in php....

How to send an email in PHP?


To send an email in php you can use the in-built function provided by php.

mail($tomail,$subjectofmail,$mailbody,$mailheaders);

This is the syntax of  mail function in php.

For above function to work, there should be up and running mail server available on the web server.

There are below settings in php.ini that must be set properly for mail system to work.
  1. SMTP - name of mail server - Generally Localhost
  2. smtp_port -  Generally 25 .
  3. sendmail_from - from address of the mail

If you do not know configuration of your mail server, you must contact your server administrator to get it.

Apart from above mail function, You can use methods provided in popular php frameworks like cakephp, codeigniter etc.

Sunday, 9 June 2013

How to upload a word document or pdf file using php?

In web application development, many times you will need to upload files to server. For example, in case you are developing job portal, you will need to write the php script that will upload the resume to server.


You have to create the html form with below input element. This is required for browsing the file.

<input type="file" name="file" id="file"><br>

On submitting this form, the file that you have browsed will be stored on the server at temporary location.

You can access the file information in action script like below : -

<?php
  echo Name of file uploaded: " . $_FILES["file"]["name"] . "<br>";
  echo "Type of file uploaded : " . $_FILES["file"]["type"] . "<br>";
  echo "Size of file uploaded " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
  echo "Temp path where the file is stored " . $_FILES["file"]["tmp_name"];
?>

Now you can save the uploaded file from temporary location to other folder on the server.


      move_uploaded_file($_FILES["file"]["tmp_name"],"uploadfolder/" . $_FILES["file"]["name"]);

SO here we are saving the uploaded file in uploadfolder on the server. Before saving the file to said location you must check that file with that name does not exist there.

This is how you can upload a file on the server in PHP.

How to delete a session variable in php?

Before I tell you how to delete the session variable, Let me explain the use of session.

Sessions are used in web applications to store the information about the user on the server. So once you create the session variables, you can access those variables from all pages in the applications. Without sessions, it is not possible to access information from one page to another.

So How to create sessions and session variables?

<?php

session_start();   //function to start the session

$_SESSION['uid']=12323;  // store user id in session variable

?>
Now $_SESSION is a global variable and you can use it from any page of the application.



How to delete the session variable in PHP?

<?php
if(isset($_SESSION['uid']))   //check if session variable exists
  unset($_SESSION['
uid']);   // if exists, delete that session variable

?>


How to delete All session variables in PHP at one go?

<?php
Session_Destroy();

?>


How to Delete Cookies in PHP


Cookies are nothing but small text files stored on client computers via browser.  Cookies generally contain user information like userid, sessionid etc.

Main use of cookie is to store the user information permanently on the client computer. So that when that client visits the site sometime in future, Server knows who that client is and can customize the view of the webpage.

In php you can set the cookie as well as delete it.

Syntax:
setcookie(cname, cvalue, cexpire, cpath, cdomain);

As shown above, we can use setcookie function to set the cookie with name cname and value as cvalue.

We can also set the expiry date of the cookie.

Below program, I am accessing cookie with name myuser

if (isset($_COOKIE["myuser"]))
  echo "Hi " . $_COOKIE["myuser"] ;
else
  echo "Hi guest!";


To delete the cookie you can set the expiry time of the cookie to past.

<?php
// set the expiration date to one hour ago
setcookie("myuser", "", time()-6600);

?>



This is how we can set the cookie and delete it in PHP.

What is php pear package?

PHP PEAR stands for php extension and application repository.  PEAR's objective is to provide reusable components, provide best practices for PHP development.

Thus PEAR developer driven project which aims at best methodologies in php development.

The PEAR provides lot of packages that help us in writing the php code for database programming, authentication, Web services, XML processing etc.



What are extensions in php?

Php extensions are nothing but libraries that can be used to interact with different kinds of applications.

For example - php_soap is one of the php extensions and it is used to work with web services. You can create soap requests and get the response from the server.

Below is the list of important extensions in php that we use.

  • php_soap
  • php_mysql
  • php_mysqli
  • php_pdo_mysql
  • php_zip
  • php_sockets
  • php_ldap
To work with different kinds of databases php has got different extensions like php_mysql, php_oci8 etc.

You can enable or disable the php extensions in php.ini file

For example - 

To enable soap extension you can use below statement in php.ini
extension=php_soap.dll


To disable soap extension you have to prefix the statement with semicolon in php.ini
;extension=php_soap.dll








What are important settings in php.ini

Well - If you open the php.ini file, you will get to see lot of php settings. This file is located in your php installation folder.

Below is the list of important settings in php.ini that you will need to edit.

  1. max_execution_time : This setting is used to set the maximum execution time of your php script. By default it is 30 seconds. But if your script needs to fetch data from other server, it may take longer. In that case you need to increase this setting.
  2. error_reportingThis setting is used to set the level of error reporting. It controls what kinds of errors are displayed to user. default is E_ALL means php shows all kinds of errors to user.
  3. display_errorsThis setting is used to show or hide errors to user. If it is set to off, no errors are displayed to user.
  4. include_pathThis setting is used to set the path of directory from where you can include or require files.
  5. file_uploadsThis setting is used for uploading the file, if on, you can upload files to server using php.
  6. mysql.default_hostThis setting is used to specify default mysql server.
  7. post_max_sizeThis setting is used to specify the maximum size in mb that can be posted using post method.
  8. uploa_tmp_dirThis setting is used to specify the temporary directory for uploads.
There are many more settings in php.ini But above mentioned are very important settings in php.

How to read file line by line in php?


Example -

In php we can read the files just like c.

Code and Syntax


<?php
$file = fopen("myfile.txt", "r") or exit(“error !");

while(!feof($file))
  {
  echo fgets($file). "<br>";
  }
fclose($file);
?>

Explanation
In above program, we have used fopen method to open a file and fgets is used to read one line of file at a time. Feof is used to find the end of file.


For more php questions and answers, dumps, tutorials for beginners and experienced people visit http://www.top-php-interview-questions.blogspot.in  If you find any errors while executing this program, you can make your comments or mail me at reply2sagar@gmail.com









What is the difference between include and require in php?


Example -

In php we can use include and require statements to insert the contents of one file into another.  This helps in modular approach to web development.
Difference between require and include is given below.
  • require will produce a fatal error (E_COMPILE_ERROR) and stop the script
  • include will only produce a warning (E_WARNING) and the script will continue

Code and Syntax

File – sample.php

<?php
require ‘abc.php’;
include ‘xyz.php’;
require_once ‘tt.php’;
?>


Explanation
In above program, we have included 3 files in sample.php.


For more php questions and answers, dumps, tutorials for beginners and experienced people visit http://www.top-php-interview-questions.blogspot.in  If you find any errors while executing this program, you can make your comments or mail me at reply2sagar@gmail.com













How to get current server date in php?



Example -

 In below example, we have used the date function in php to find the current date on server.

Code and Syntax

<?php
// Print the current day…
echo date("l") . "<br>";

echo date(“dd-mm-y”);
?>


Explanation
We have used date function to print today’s date.

For more php questions and answers, dumps, tutorials for beginners and experienced people visit http://www.top-php-interview-questions.blogspot.in  If you find any errors while executing this program, you can make your comments or mail me at reply2sagar@gmail.com







Give multi-dimensional array example in php?


Example -

 In below example, we have used multi-dimensional array to store information about different employees

Code and Syntax

<?php
// A two-dimensional array
$emp = array
   (
   array("emp1",22,9600),
   array("emp2",30,5944),
     );
  
echo $emp[0][0].": age: ".$emp[0][1].". salary: ".$emp[0][2]."<br>";

?>

Explanation
We have printed the age and salary of first employee. So we have 2 arrays inside $emp array. We access elements in array using C convention.

 For more php questions and answers, dumps,tutorials for beginners and experienced people visit http://www.top-php-interview-questions.blogspot.in  If you find any errors while executing this program, you can make your comments or mail me at reply2sagar@gmail.com


















How to process forms in php?


Example -
When you submit the form you can use 2 types of methods.
  1. Post
  2. Get

You can use post method if you want to send large number of variables to server and in hidden manner. You can’t bookmark the page as values are not displayed in the browser.
Information sent from a form with the POST method is invisible to others  By default there is an 8 MB max size for the POST method. (You can change post_max_size in the php.ini file to send data with more size).

Get method is used to send information to server that is visible in browser and you can bookmark that page.

The PHP $_REQUEST Variable has the contents of both $_GET, $_POST, and $_COOKIE. The $_REQUEST variable can be used to collect form data sent with both the GET and POST methods.



Code and Syntax


Explanation

 For more php questions and answers, dumps,tutorials for beginners and experienced people visit http://www.top-php-interview-questions.blogspot.in  If you find any errors while executing this program, you can make your comments or mail me at reply2sagar@gmail.com










What are looping statements in php?


Example -
We have 4 looping statements in PHP.
  1. for
  2. for each
  3. while
  4. do…..while

Code and Syntax

<?php
$x=array("one","two","three");
foreach ($x as $value)
  {
  echo $value . "<br>";
  }
?>

Explanation




 For more php questions and answers, dumps,tutorials for beginners and experienced people visit http://www.top-php-interview-questions.blogspot.in  If you find any errors while executing this program, you can make your comments or mail me at reply2sagar@gmail.com



How to sort arrays in php?


Example -
We have in-built functions to sort arrays in php as shown below.
1.      sort() - sort indexed arrays in ascending order
2.      rsort() - sort indexed arrays in descending order
3.      asort() - sort associative arrays in ascending order, based upon the value
4.      ksort() - sort associative arrays in ascending order, based upon the key
5.      arsort() - sort associative arrays in descending order, based upon the value
6.      krsort() - sort associative arrays in descending order, based upon the key


Code and Syntax


Explanation

 For more php questions and answers, dumps,tutorials for beginners and experienced people visit http://www.top-php-interview-questions.blogspot.in  If you find any errors while executing this program, you can make your comments or mail me at reply2sagar@gmail.com






What are different types of arrays in php?



Example -
In php there are 3 types of arrays.
1.      Index arrays
2.      Associative arrays
3.      Multi-dimensional Arrays.

Code and Syntax

//Index arrays
$emp=array("e1","ba","cd");
$alength=count($emp);  // find the length of emp array.

//Associative arrays
$sal=array("sagar"=>"35000","amol"=>"390907","Jockey"=>"43000");
//$sal['ganesh']="398985";

//To iterate the associative array use below code
<?php
foreach($sal as $key=>$val)
  {
  echo "Key=" . $key . ", Value=" . $val;
  echo "<br>";
  }
?>



Explanation

In above examples, we have created indexed arrays and associative arrays. Difference between 2 arrays is that in index arrays we store the values based upon numerical index. While in associative array, we store the values based upon key.

 For more php questions and answers, dumps,tutorials for beginners and experienced people visit http://www.top-php-interview-questions.blogspot.in  If you find any errors while executing this program, you can make your comments or mail me at reply2sagar@gmail.com




How to use switch statement in php?


Example -
Switch statement can be used to execute the particular block of code based upon some condition.

Code and Syntax

<?php
$ind="one";
switch ($ind)
{
case "one":
  echo "You selected one!";
  break;
case "two":
  echo "You selected two!";
  break;
default:
  echo "you selected neither one or two!";
}
?>

Explanation

Above code will print one. If you have $ind=”233” then you will have output as "you selected neither one or two!";

This is how you can use the switch statement in PHP.

 For more php questions and answers, dumps,tutorials for beginners and experienced people visit http://www.top-php-interview-questions.blogspot.in  If you find any errors while executing this program, you can make your comments or mail me at reply2sagar@gmail.com





What are different string functions in php?


Example -
There are many string function available in php that help us find the length of the variable , concatenate 2 variables, reverse the string, remove spaces from string etc..

Code and Syntax

<?php
$str = “hello”
$st1 = ‘hello’

// Concatenation operator
$txt1="Hello!";
$txt2="What!";
echo $txt1 . " " . $txt2;
?>

// find the length of string
//The strlen() function returns the length of a string, in characters.

<?php
echo strlen("Hello!");      //this will print 6
?>

//strpos finds the position of the text in another string.
<?php
echo strpos("Hello sagar!","sagar");  // this will print 6
?>

Explanation

You can assign a string variable using single quote or double quote.



 For more php questions and answers, dumps,tutorials for beginners and experienced people visit http://www.top-php-interview-questions.blogspot.in  If you find any errors while executing this program, you can make your comments or mail me at reply2sagar@gmail.com



What are the types of variables in php?


Example -
PHP is a loosely typed language that means you do not need to declare the data type of variables in php. PHP statements and PHP variables are case-sensitive. All variables should start with $ sign. There are 4 types of variables in php.

1.      local
2.      global
3.      static
4.      parameter



Code and Syntax

<?php
$x=5; // global scope

function myvarTest()
{
global $x;   // access global variables from local scope
$p=10;         // local variable
echo $x;
}

myvarTest();

?>

Static variable example
<?php

function myvarTest()
{
static $vx=0;
echo $vx;
$vx++;
}

myvarTest ();
myvarTest ();
myvarTest ();

?>
Parameter variable example

<?php

function myvarTest($vx)
{
echo $vx;
}

myvarTest(45);

?>
                    
Explanation
Above example shows how we can use local and global variables in php.

This is how you can use variables in php.


 For more php questions and answers, dumps,tutorials for beginners and experienced people visit http://www.top-php-interview-questions.blogspot.in  If you find any errors while executing this program, you can make your comments or mail me at reply2sagar@gmail.com





How to add comments in php?


Example -
To write the php code, you have to use <?php   ?>  syntax as mentioned below.

Code and Syntax

<html>
<body>

<h1>PHP page</h1>

<?php
echo "Hello !";
//write hello world on page
?>

</body>
</html>

Explanation

To add comments, you have to use // or /*   */.
// is used to comment one line.
/*   */ is used to comment multiple lines.

This is how you can add comments in php.  For more php questions and answers, dumps,tutorials for beginners and experienced people visit http://www.top-php-interview-questions.blogspot.in  If you find any errors while executing this program, you can make your comments or mail me at reply2sagar@gmail.com



Saturday, 8 June 2013

How to check if php is installed on the Web server

To check if php is installed on or not on your web server, you have to create one file and upload it to server.

Code of the file should be like -

<?php
phpinfo();
?>

Name this file as getphp.php and try to access it from browser.
if php is installed on the server you will get to see the php information and php.ini settings. You will also find the php version on the top of the page. 


SystemWindows NT FORTITUD-A69E19 5.1 build 2600
Build DateMay 2 2008 18:01:20
Configure Commandcscript /nologo configure.js "--enable-snapshot-build" "--with-gd=shared" "--with-extra-includes=C:\Program Files (x86)\Microsoft SDK\Include;C:\PROGRA~2\MICROS~2\VC98\ATL\INCLUDE;C:\PROGRA~2\MICROS~2\VC98\INCLUDE;C:\PROGRA~2\MICROS~2\VC98\MFC\INCLUDE" "--with-extra-libs=C:\Program Files (x86)\Microsoft SDK\Lib;C:\PROGRA~2\MICROS~2\VC98\LIB;C:\PROGRA~2\MICROS~2\VC98\MFC\LIB"
Server APIApache 2.0 Handler
Virtual Directory Supportenabled
Configuration File (php.ini) PathC:\WINDOWS
Loaded Configuration FileC:\wamp\bin\apache\apache2.2.8\bin\php.ini

What is PHP

PHP is a server side programming language like asp.net, jsp etc. You can build dynamic web applications using PHP.

PHP stands for 'hypertext preprocessor'. PHP is a open source (PHP license) unlike ASP.net which has end user license with it.

There are many frameworks that are in place that help rapid application development using PHP.
Some of the popular frameworks are -

  • CakePHP
  • Symfony
  • CodeIgniter
  • Yii Frmework
  • Zend Framework
There are lot of content management systems that are developed using php like drupal, wordpress, joomla etc. So php is  very popular among web application programmers.