Friday, 26 August 2011

php interview question

What is php date difference

ANSWER:
If you want to get the difference between to dates or time values, then you first need to get the values in the same format. The best way is to convert both dates into Unix timestamp format. In this case the date and time information is stored as an integer so we can calculate the difference easily. You can get the Unix timestamp in various ways as you can see below:

Code:

1.
2.
// Get current time
3.
$date1 = time();
4.

5.
// Get the timestamp of 2006 October 20
6.
$date2 = mktime(0,0,0,10,20,2006);
7.
?>

Now as you have the values getting the difference is quite easy. However the result will be an integer value, but you probably want to get it in days, hours and minutes. To do so we need to convert back our int value into a usable date format. We know that the difference is in seconds so we can get how many full days it is. To get it we use the following code:

Code:

1.
2.
$dateDiff = $date1 - $date2;
3.
$fullDays = floor($dateDiff/(60*60*24));
4.
echo "Differernce is $fullDays days";
5.
?>



We used the floor function as we want to get only the complete days. Besides this the 60*60*24 represents that a day has 24 ours and each hour has 60 minutes and each minute has 60 seconds.As next step we need to get how many hours are still present in the remaining seconds. So from the original difference we need to remove the complete days in seconds and from the remaining value we can calculate the full hours similar to as we calculated the full days. Repeating these steps for minutes as well at the end we get the difference between the original dates. The complete calculation looks like this

Code:

1.
2.
$dateDiff = $date1 - $date2;
3.
$fullDays = floor($dateDiff/(60*60*24));
4.
$fullHours = floor(($dateDiff-($fullDays*60*60*24))/(60*60));
5.
$fullMinutes = floor(($dateDiff-($fullDays*60*60*24)-($fullHours*60*60))/60);
6.
echo "Differernce is $fullDays days, $fullHours hours and $fullMinutes minutes.";
7.
?>







program for paging



<?php
//mysql start position
$start=0;
//record per page
$pp=2;


//current page
if(!isset($_GET['page']))
{
$page=1;
}
else
{
$page=$_GET['page'];
}


//mysql start position


if($page<=1)
$start=0;
else
$start=$page * $pp - $pp;




//connect  db
$con=mysql_connect("localhost","","");
mysql_select_db("test",$con) or die("no msg");
$r="select * from tab1";
$dis="select * from tab1 LIMIT $start,$pp";
//how much records in db
$no_row=mysql_num_rows(mysql_query($r));
echo $no_row;
$no_pag=ceil($no_row/$pp);
//append 
//$dis.="LIMIT $start,$pp";
$res=mysql_query($dis);
while($row=mysql_fetch_array($res))
{
echo $row['name']."<br>";
}
//prev


$prev=$page-1;




//next
$next=$page+1;
//prev
if($prev > 0)
echo "<a href='?page=$prev'>prev</a>";




$number=1;
for($number;$number<=$no_pag;$number++)
{
echo "<a href='?page=$number'>$number</a> ";
}


if($page<ceil($no_row/$pp))
echo "<a href='?page=$next'>next</a>";


?>





<title>JQuery Form Example</title> 
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript">






FORM VALIDATION



<html>
<head>
<title>JQuery Form Example</title> 
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#myform").validate({ debug: false,rules: {
name: "required",
email: {required: true,email: true}},
messages: {name: "Please let us know who you are.",email: "A valid email will help us get in touch with you.",},
submitHandler: function(form) {
// do other stuff for a valid form
$.post('process.php', $("#myform").serialize(), function(data) {$('#results').html(data);});}
});
});
</script>
<style>
label.error { width: 250px; display: inline; color: red;}
</style>
</head>
<body>
<form name="myform" id="myform" action="" method="POST">  
<!-- The Name form field -->
    <label for="name" id="name_label">Name</label>  
    <input type="text" name="name" id="name" size="30" value=""/>  
<br>
<!-- The Email form field -->
    <label for="email" id="email_label">Email</label>  
    <input type="text" name="email" id="email" size="30" value=""/> 
<br>
<!-- The Submit button -->
<input type="submit" name="submit" value="Submit"> 
</form>
<!-- We will output the results from process.php here -->
<div id="results"><div>
</body>

Saturday, 25 June 2011

PHP FILES HANDLING - OPENING AND CLOSING FILES IN PHP





You can use the PHP function fopen in order to open files in PHP; practically, fopen() will allow you to associate a file with a file handle (which will then permit the manipulation of this file). The PHP syntax to follow is:


fopen(filename,mode),
  • where filename is the (string) path to the file you wish to open
  • where mode is one of the following opening modes:

  • 'r': this is the read-only mode; the file pointer is set at the beginning of the file.
  • 'r+': this is the reading/writing mode; the file pointer is set at the beginning of the file.
  • 'w': this denotes the write-only mode. The file is reduced to length 0 if it already exists; if the file doesn't already exist, it is created. The file pointer is set at the beginning of the file.
  • 'w+': this is the reading/writing mode. The file is reduced to length 0 if it already exists; if the file doesn't already exist, it is created. The file pointer is set at the beginning of the file.
  • 'a': same as the w mode, except that the file pointer is set at the end of the file.
  • 'a+': same as w+, except that the file pointer is set at the end of the file.
  • 'x': creates the file specified and opens it for writing only; the file pointer is set at the beginning of the file. If the file specified already exists, an error is returned.
  • 'x+': creates the file specified and opens it for reading and writing; the file pointer is set at the beginning of the file. If the file specified already exists, an error is returned.
Remark:

We advise you to append the letter b after the letter of the opening mode you chose as a parameter for fopen() (e.g. 'ab+' instead of'a+', 'rb' instead of 'r', etc ...). Indeed, this will giuarantee that the file is opened in binary mode and will prevent any compatibility problem.

PHP FILES HANDLING - PHP LOOPS ON FILE CONTENT WITH THE PHP FUNCTION FEOF


When you wish to run a PHP loop over the content of a file, you must ascertain that your PHP loop does terminate; in order to achieve this, either you know the exact length of your file (in bits or in characters), in which case you will be able to tell your PHP script to stop as soon as the file pointer goes past this length, or you don't know the file size, in which case you might be interested in a function which would allow you to test at each step whether the end of the file has been reached. Such a PHP function exists and is called feof(file end of file). It syntax is as follows:

feof(file_handle),

where file_handle is a PHP file handle as defined by fopen() in the previous paragraph.
This PHP function will return TRUE if the file pointer is pointing to the end of the file and FALSE otherwise

PHP FILES HANDLING - READING FILES IN PHP


There are different ways to read a file in PHP; one of them is to read it character by character, another way is to read it line by line.

Of course, both options are implicitly assuming that the file is a text file. If you plan to manipulate files which are not text files, then you shall not need to read them since the way they are encoded in memory is not easily readable by humans; however, some binary-safe functions exist that still allow you to output the value of one (resp. several) bytes as one (resp. several) characters (binary-safe means that there is a bijection, aka a one-to-one correspondence between the characters output and the binary value of those; therefore, you can manipulate/copy/modify this binary safe data without alienating the original binary data of the source). For instance, we have seen that fopen() can be made binary safe by adding a 'b' after the first letter of the opening mode.

Reading a file character by character in PHP:

The PHP function fgetc allows you to read a file character by character (the function is binary safe). The syntax to use is:
fgetc(file_handle)
  • where file_handle is the file handle defined by fopen.
Reading a file line by line in PHP:

The PHP function fgets allows you to read a file line by line (the function is binary safe). The syntax to use is:
fgets(file_handle, length)
  • where file_handle is the file handle as defined by fopen.
  • where length denotes the number of bytes to be read per line (if this parameter is not specified, the PHP script will run until the end of the line)
Reading a portion of a file in PHP:

The PHP function file_get_contents allows you to read a portion of a file in PHP (the function is binary safe), and returns it as a string. The syntax to use is:
file_get_contents(filename, TRUE, NULL, offset, maxlength)
  • where filename is the string filename of the file to be read
  • where offset denotes the location (in bytes from the beginning of the file) at which the script will start reading the file
  • where maxlength denotes the maximum number of bytes to be read (the script will keep reading the file until maxlength bytes have been read or until the end of file is reached, whichever comes first).

Remark:

If you are using PHP 6 or higher, you can keep the parameters TRUE and NULL as above; for simplicity reasons, we will not explain the various options offered for these parameters.




PHP FILES HANDLING - WRITING FILES IN PHP


Writing a portion of a file in PHP:


Using the fwrite PHP function, you can write the content of a string to a file (designated by a file handle as created with fopen). The fwrite function is binary-safe.
Combining this PHP function with the file_get_contents function (which returns a string), you can thus copy parts of one file into another (this works because both PHP functions are binary safe).
In the example below, we copy the content of the file initial.bmp (which must already exists) into a newly created file new.bmp:

<?php
$b = file_get_contents("initial.bmp",TRUE, NULL);
$a = fopen("new.bmp","wb+");
fwrite($a,$b);
?>

We have seen that PHP file handles allow you to open, read and write files. In order to preserve the binary integrity of files, one must use binary-safe functions. Currently, most PHP functions are binary-safe or can easily be made binary-safe.

Monday, 13 June 2011

PHP COOKIES HANDLING - USING COOKIES IN PHP




How cookies work in PHP


We have just seen that the PHP session id is by default passed through the cookies. But what are cookies exactly ? 
  • Cookies are elements which allow a website to leave some information on a visitor's computer for a given period of time and access it at a later time when the visitor comes back to the website (even days, weeks or months after his last session was ended).
  • Cookies are managed at the level of the internet browser (i.e., the cookies made available to a browser will be treated independently from the cookies made available to another browser, if you happen to run two different internet browsers on your computer). In particular, it is possible to disable cookies on a browser, and people who do so won't be able to accept cookies from websites (actually, there exist different levels of permissions, but we won't enter such a level of details here).
  • Cookies are very useful, for instance in the case of authentication protocols when you want to "remember" a user, i.e. to keep him logged in for a given period of time even when his session is terminated, in order to save him the trouble of having to re-enter his username and password multiple times.
  • Creating a cookie in PHP

    In order to create a cookie in PHP, you must use the function setcookie(); the PHP syntax to follow is:

    setcookie(name_of_cookie, value_of_cookie, expiration_time),
    • where name_of_cookie is a string which indentifies the cookie
    • where value_of_cookie is the value of this cookie (also a string)
    • where expiration_time is the time at which the cookie will expire (i.e., is destroyed in the visitor's browser); this time is expressed in number of seconds from the current time (you can for instance decide that cookie will expire in one hour by using time()+3600).
  • eading a cookie in PHP

    Once a cookie has been set, you need to be able to retrieve it. You can do so by using the superglobal variable $_COOKIE, which is an array whose indexes (keys) are the cookies' names.

    Checking whether a cookie has been set

    In order to ascertain the existence of a cookie in PHP, you can use the expression isset($_COOKIE[name_of_cookie]) which returns TRUE if the cookie has been set, FALSE otherwise.

    Destroying a cookie in PHP
    In order to destroy a cookie in PHP, all you have to do is set his expiration time to the past; for instance, you could use the PHP syntax:

    setcookie(name_of_cookie, value_of_cookie, time()-1)

    The following example sets a cookie, checks that it has been set, retrieves it and then prints its value in the visitor's browser:

    Learn the PHP code:
    <?php
    setcookie('cookie1','this is my cookie', time() + 3600);
    // After the page has been reloaded if (isset($_COOKIE['cookie1']))
    echo 'The cookie has been set'.'<br>'
    echo 'Its value is "'.$_COOKIE['cookie1'].'"<br>';
    ?>

    Run the PHP script in your web browser

    Set a cookie in PHP with setcookie()
    Remark:

    Once a cookie is set, the page must be reloaded in order for the cookie to be retrieved. The same remark applies for the destruction of cookies: until the page is reloaded in the browser, the superglobal variable $_COOKIE['cookie1'] remains available.
    Reload the page in your web browser:

    Setting cookies with the PHP function setcookie()

    Security issues: cookies used in PHP authentication protocols
    Very often, you might want to allow a user to remain logged in for a certain number of time (in weeks or months ...). In order to achieve this, you must be able to set a cookie which will contain:
    • the identity of this user (his username, for instance)
    • a way to verify that this user has the rights to log into the requested account

    In order to achieve the last point, you might be tempted to store this user's password and compare it to the corresponding data in your MySQL database. The problem with this approach is that the cookie on your visitor's machine might be intercepted and read by an adverse party, who will thus gain unauthorized access to the account of your visitor.

    A way to remedy this problem is to encrypt the data stored in your cookie so that if it is intercepted by another party, it won't be decipherable. It is easy enough to achieve this using any encryption method of your choice, the idea being that PHP script will uncrypt that cookie and then compare the user's password with the information stored in your database.

    However, that method, though significantly better than the previous one, is still not that satisfactory: indeed, if someone came to steal your server's database, this person would automatically collect all of your users' usernames and passwords. In order to remedy this problem, you might want to encrypt the passwords in your database as well, and uncrypt them only at the moment of the authentication. Well, this is not really solving our problem: indeed, if you still need to uncrypt the password on both sides (that stored in the database and that stored within the cookie), then at one moment or another the key to decypher the information must appear in your script, and anyone who would be able to steal the source code of your script would also get access to these passwords. So, what could be a more acceptable solution ?

    The best solution would be that you encrypt the information both in your MySQL database and within your user's cookies, while at no time needing to uncrypt that information. In particular, you wouldn't even be able to uncrypt it yourself, which means that absolutely noone would be able to gain unauthorized access to your users' passwords, not even yourself -the owner of the server (this is of course assuming that your encryption method is reliable enough). The key of this method lies in the fact that if the password provided is the right one, then its encrypted version within the cookie and that stored in your database should be rigorously the same.

    However, how is that possible to come up with a method to reliably encrypt a password without being able to uncrypt it afterwards (even while knowing which encryption method was used) ? One solution is to devise an encryption method so that the way the data is encrypted depends on the data itself ... in this way, given a password, you know how to encrypt it (since you hold the encryption method and the password, i.e. the data, which you are not supposed to know) but once the password is encrypted, you have no way to decipher it (because you do not know how it was encrypted since the encryption method depended on the data to be encrypted).
    Practically, the PHP language proposes you to achieve such a one-way encryption by using the crypt() function.
    PHP cookies allow you to store information about your visitor on his own computer and to access it later (even a long time after his PHP session was ended).
    You can use cookies for several purposes; for instance, cookies can help you to implement authentication methods. They can also allow you to store a user's navigation preferences or its commercial profile without having to store those on your server's web database.

Friday, 10 June 2011

joomla question & answer


what is joomla?
Joomla is the content management system.It is all ready develop 
software. A lot of menu and tools provided by this system.A
developer or a owner of that site can change our contents
with the help of tools or menu.It is winner of content
management award of 2007.
  •  Joomla is the extented version of Mambo.
  • Joomla is famous Content Management system based on MVC 
    (Model view controller) architecture.
    

    Joomla! came into being as the result of the fork of
    Mambo by the development team on August 17, 2005.
    ---Open Source
    ---Customize modules
    ---Built-in modules & plugins
    ---Develop by PHP 
    ---MySql Support
    ---Admin & User Section
    ---User Management
    ---Media Manager
    ---Language Manager
    ---Banner Management & many more............







Q.1 What is joomla in php?

ANSWER: Joomla is an open source content management system.

Q.2 What is zend engine?

ANSWER: Zend engine is used internally by php as a compiler and runtime engine...

Q.3 Joomla! Features: 

ANSWER *
Completely database driven site engines
*
News, products or services sections fully editable and manageable
*
Topics sections can be added to by contributing authors
*
Fully customizable layouts including left, center and right menu boxes
*
Browser upload of images to your own library for use anywhere in the site
*
Dynamic Forum/Poll/Voting booth for on-the-spot results
*
Runs on Linux, FreeBSD, MacOSX server, Solaris and AIX

Q.4 What are some real world examples of what Joomla! can do?

ANSWER:
Joomla is used all over the world to power Web sites of all shapes and sizes. For example:

* Corporate Web sites or portals
* Corporate intranets and extranets
* Online magazines, newspapers, and publications
* E-commerce and online reservations
* Government applications
* Small business Web sites
* Non-profit and organizational Web sites
* Community-based portals
* School and church Web sites
* Personal or family homepages





\\\\\\\\form validation using php\\\\\\\\\\\\\\



<?php
if(isset($_POST['name'],$_POST['age'],$_POST['email']))
{
$name=$_POST['name'];
$age=$_POST['age'];
$email=$_POST['email'];
$error=array();
if(empty($name) || empty($age) || empty($email))
{
$error[]="all fields are empty";
}
else
{
if(strlen($name)>20)
{
$error[]="name is long";
}
if(!is_numeric($age))
{
$error[] = "age must be numeric";
}
else
{
if($age<=0)
{
$error[]= "Age must be positive";
}
}
if(filter_var($email,FILTER_VALIDATE_EMAIL)===FALSE)
{
$error[]="Enter the valid email address";
}
}
if(!empty($error))
{
foreach($error as $errors)
{ echo "<strong>",$errors,"</strong><br />";
}


}else{ 
header("Location:in.php ");
echo "ur login in";}
}




?>
<form action="form.php" method="POST">
<p>
name<input type="text" name="name" /><br>
age<input type="text" name="age" /><br>
email<input type="text" name="email" /><br>
<input  type="submit"></form>












\\\\\\\\\\\\\\\\\\\\\check form from database and insert\\\\\\\\\\\\\\\\\\





<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{

$('#feedback').load('check.php').show();
$('#name').keyup(function()
{

$.post('check.php', { name:form.name.value},
function(result)
{

$('#feedback').html(result).show();


});
});
});





</script>
<style type="text/css">
#feedback
{display:inline}

</style>
</head>
<body>
</body>
<form name="form" action="insert.php" method="post">
Name
<input type="text" id="name" name="name" /> <div id="feedback"></div><br>
city
<input type="text" name="city" id="city" /><br>
phno
<input type="text" name="phno" id="phno" /><br>
Email
<input type="text" name="email" id="email" /><div id="f">hhh</div><br>
<input type="submit" />
 </form>


</html>






\\\\\\\\\\\\\\\\\\\\\\check.php\\\\\\\\\\\\\\\\\\\\\\\\\





<?php

mysql_connect("localhost","","") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());

$uname=mysql_real_escape_string($_POST['name']);

//$email=mysql_real_escape_string($_POST['email']);
$check=mysql_query("select * from tab1 where name='$uname'");

$chck_rows=mysql_num_rows($check);

if($uname=="")
echo "choose name";
else if(strlen($uname)<=4)
echo "Too low";
else
{
if($chck_rows==0)
echo "sucess";
else
echo "loserrrrrrrrrrrrr";

}


?>




\\\\\\\\\\\\\\\\\\\\\\\\\\\\\login program\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\


<?php
include 'oop.php';
if(logi())
{


header("Location:output.php");
}


if(isset($_POST['login']))
{


$name=$_POST['name'];
$pass=$_POST['pass'];
if(isset($_POST['rembr']))
$rembr=$_POST['rembr'];
else
echo "";


if($name&&$pass)
{


$login=mysql_query("select * from log where name='$name'");
while($row=mysql_fetch_assoc($login))
{
$dbp=$row['id'];


if($pass==$dbp)
$loginok=TRUE;
else
$loginok=FALSE;




if($loginok==TRUE)
{


if($rembr=="on")
setcookie("name",$name,time()+7200);


else if($rembr=="")
$_SESSION['uname']=$name;


header("Location:output.php");
exit();
}
else
{die("incorre password ");}


}


}
else
die("incorrect user name/password");


 }




?>
<form action="in.php" method="POST">
name<input type="text" name="name" /><br>
pass<input type="password" name="pass" /><br>
<input type="checkbox" name="rembr" /><br>
<input type="submit" name="login" value="submit"/><br>
</form>







\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\output.php\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

<?php
include 'oop.php';
if(!logi())
{
header("Location:in.php");
exit();
}

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\diffrence of dates\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

$date1 = "2009-03-24";
$date2 = "2009-06-24";


$diff = abs(strtotime($date2) - strtotime($date1));


$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));


printf("<br>%d years, %d months, %d days\n", $years, $months, $days);




?>
u r log in<p />
<a href="function.php">logout</a>
\\\\\\\\\\\\\\\\\\\function.php\\\\\\\\\\\\\\
<?php
session_start();
session_destroy();
setcookie("name","",time()-7200);
header("Location:in.php");



?>


\\\\\\\\\\\\\\\\\\\\\\\oop.php\\\\\\\\\\\\\\\\\\\\\\

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


//login check function
function logi()
{

if(isset($_SESSION['uname'])||isset($_COOKIE['name']))
{

$logi=TRUE;
return $logi;

}
}

















\\\\\\\\\\\\\\\\\\\\\insert.php\\\\\\\\\\\\\\\

<?php

$con=mysql_connect("localhost","","") or die(mysql_error());
mysql_select_db("test",$con) or die(mysql_error());
$name=$_POST['name'];
$city=$_POST['city'];
$phno=$_POST['phno'];
$email=$_POST['email'];
$ins=mysql_query("insert into tab1(name,city,phno,email) values ('$name','$city','$phno','$email')");
if($ins)
{
echo "sucessfully inserted";
}
else
{
echo "it will not insert";
}

?>