Showing posts with label php-interview-questions-answers. Show all posts
Showing posts with label php-interview-questions-answers. Show all posts

What is the use of PEAR in php?

PEAR is known as PHP Extension and Application Repository. It provides structured library to the PHP users and also gives provision for package maintenance.

Cookies Versus Sessions?

 Cookies

The setcookie( ) call needs to be before the HTML form because of the way the web works. HTTP operates by sending all "header" information before it sends "body" information. In the header, it sends things like server type (e.g., "Apache"), page size (e.g., "29019 bytes"), and other important data. In the body, it sends the actual HTML you see on the screen. HTTP works in such a way that header data cannot come after body datayou must send all your header data before you send any body data at all.
Cookies come into the category of header data. When you place a cookie using setcookie( ), your web server adds a line in your header data for that cookie. If you try and send a cookie after you have started sending HTML, PHP will flag serious errors and the cookie will not get placed.
There are two ways to correct this:
  • Put your cookies at the top of your page. By sending them before you send anybody data, you avoid the problem entirely.
  • Enable output buffering in PHP. This allows you to send header information such as cookies wherever you likeeven after (or in the middle of) body data. Output buffering is covered in depth in the following chapter.
The setcookie( ) function itself takes three main parameters: the name of the cookie, the value of the cookie, and the date the cookie should expire. For example:
 
setcookie("Name", $_POST['Name'], time( ) + 31536000);
 
In the example code, setcookie( ) sets a cookie called Name to the value set in a form element called Name. It uses time( ) + 31536000 as its third parameter, which is equal to the current time in seconds plus the number of seconds in a year, so that the cookie is set to expire one year from the time it was set.
Once set, the Name cookie will be sent with every subsequent page request, and PHP will make it available in $_COOKIE. Users can clear their cookies manually, either by using a special option in their web browser or just by deleting files.

print $_COOKIE["Name"];


 Sessions

Sessions store temporary data about your visitors and are particularly good when you don't want that data to be accessible from outside of your server. They are an alternative to cookies if the client has disabled cookie access on her machine, because PHP can automatically rewrite URLs to pass a session ID around for you.

 Starting a Session

A session is a combination of a server-side file containing all the data you wish to store, and a client-side cookie containing a reference to the server data. The file and the client-side cookie are created using the function session_start( ) it has no parameters but informs the server that sessions are going to be used.
When you call session_start( ), PHP will check to see whether the visitor sent a session cookie. If it did, PHP will load the session data. Otherwise, PHP will create a new session file on the server, and send an ID back to the visitor to associate the visitor with the new file. Because each visitor has his own data locked away in his unique session file, you need to call session_start( ) before you try to read session variablesfailing to do so will mean that you simply will not have access to his data. Furthermore, as session_start( ) needs to send the reference cookie to the user's computer, you need to have it before the body of your web pageeven before any spaces.

 Adding Session Data

All your session data is stored in the session superglobal array, $_SESSION, which means that each session variable is one element in that array, combined with its value. Adding variables to this array is done in the same way as adding variables to any array, with the added bonus that session variables will still be there when your user browses to another page.
To set a session variable, use syntax like this:
    $_SESSION['var'] = $val;
    $_SESSION['FirstName'] = "Jim";

Older versions of PHP used the function session_register( ); however, use of this function is strongly discouraged, as it will not work properly in default installations of PHP 5. If you have scripts that use session_register( ), you should switch them over to using the $_SESSION superglobal, as it is more portable and easier to read.
Before you can add any variables to a session, you need to have already called the session_start( ) functiondon't forget!
 

$_ENV and $_SERVER ?

PHP sets several variables for you containing information about the server, the environment, and your visitor's request. These are stored in the superglobal arrays $_ENV and $_SERVER, but their availability depends on whether the script is being run through a web server or on the command line.

Useful preset variables in the $_SERVER superglobal
Name
Value
HTTP_REFERER
If the user clicked a link to get the current page, this will contain the URL of the previous page, or it will be empty if the user entered the URL directly.
HTTP_USER_AGENT
The name reported by the visitor's web browser.
PATH_INFO
Any data passed in the URL after the script name.
PHP_SELF
The name of the current script.
REQUEST_METHOD
Either GET or POST.
QUERY_STRING
Includes everything after the question mark in a GET request. Not available on the command line.


Of those, HTTP_REFERER and HTTP_USER_AGENT are the most important, as you can use these two to find out a lot about your visitor and then take the appropriate action. For example:
 
<?php
            if (isset($_SERVER['HTTP_REFERER'])) {
          print "previously was {$_SERVER['HTTP_REFERER']}
      <br />";
            } else {
              print "You didn't click any links to get here<br />";
            }
    ?>

    <a href="refer.php">Click me!</a>

If you load that page in your browser by typing the URL in by hand, the "You didn't click any links to get here" text is shown because HTTP_REFERER has not been set. However, if once the page is loaded you follow the "Click me!" link, the page will reload itself; this time, HTTP_REFERER will be set and the other message should appear. Although it can be easily spoofed, HTTP_REFERER is generally a good way to make sure a visitor came from a certain pagewhether you want to use that to say, "You can't download my files because you came from another site" or "Welcome, Google users!" is up to you.

Web server compression?

The best way to understand web server compression is to think of sending ZIP files
instead of uncompressed files from your web server to your web user. Sending less data
over the network will minimize network latency and your web users will get the file
faster.
The same thing applies to web spiders, as the major ones support HTTP 1.1. In fact,
search engines would appreciate the fact that they will need to use a lot less network
bandwidth to do the same work.
Web server compression is a technology used on the web server where you are hosting
your pages. If you have full control of the web server, you can set up this compression
to occur automatically for all websites or pages this server is hosting.
If you do not have this luxury, you can set this up in your code. To set up web server
compression in PHP, you can use the following PHP code:
<?php
ob_start("ob_gler");
?>
<HTML>
<body>
<p>This is the content of the compressed page.</p>
</body>
</HTML>
You can enable web server compression in your code in another way that is even easier
than the approach we just discussed. You can use the php.ini file that usually sits in
your root web folder. If it does not exist, you can create it. You can also place this file
in your subfolders to override the root php.ini settings.

What is a cookie , explaing ?

Cookie is use to store the temporary data in browser memory, We can store data in cookies using setcookie('name','value','time');
we can use that rule for simple cookie, this value will store in the browser memory. If the browser is closed the cookie value will be deleted. Another way to store data in cookie file for long time:
persistent cookie using that way we can store data for long time in the user system.

How to prevent hijacking in PHP?

 Make Error_reporting to E_ALL so that all variables will be intialized before using them.
 Make practice of using htmlentities(), strip_tags(), utf8_decode() and addslashes() for filtering malicious data in php
 Make practice of using mysql_escape_string() in mysql.

What Is a Session?

It is stored at server side because PHP is server side scripting language

Session is stored on server side because how much time page will execute it doesn't depend on client it depends on server. Server decide the session of each page ..thats why session is stored on server side

Session is to store as the server side value
method $_session start('id');
and cookie is store the validation of client side

How do you define a constant in php?

by define() directive,
like define (“MYCONSTANT”, 500);

THE DIFFERENT TYPES OF ERRORS IN PHP?

1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script – for example, accessing a variable that has not yet been defined
2. Warnings: These are more serious errors – for example, attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.
3. Fatal errors: These are critical errors – for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP’s default behavior is to display them to the user when they take place.
Internally, these variations are represented by twelve different error types

What’s the special meaning of __sleep and __wakeup?

__sleep returns the array of all the variables than need to be saved,
while __wakeup retrieves them.

What is the difference between $age and $$age

They are both variables. But $age is a variable with a fixed name. $$age is a variable who’s name is stored in $age. For example, if $age contains “var”, $$age is the same as $var.

$test = ‘abcd';
is equivalent to
$holder = ‘test';
 $$holder = ‘abcd';

How many values can the SET function of MySQL take?

MySQL set can take zero or more values but at the maximum it can
take 64 values

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

By default the maximum size is 2MB.
 can change the size
 setup at php.ini
upload_max_filesize = 12M

How can we get the browser properties using PHP?

$_SERVER['HTTP_USER_AGENT'];

How can we encrypt the username and password using PHP?

The functions in this section perform encryption and decryption

encryption decryption
AES_ENCRYT() AES_DECRYPT()
ENCODE() DECODE()
DES_ENCRYPT() DES_DECRYPT()
ENCRYPT() Not available
MD5() Not available
OLD_PASSWORD() Not available
PASSWORD() Not available
SHA() or SHA1() Not available
Not available UNCOMPRESSED_LENGTH()

count the elements of an array?

sizeof($array) – This function is an alias of count()

 count($urarray) – This function returns the number of elements in an array.

sorting an array?

arsort()
sort()
natsort()

What are “GET” and “POST”?

GET: we are submitting a form to login.php, when we do submit or similar action, values are sent through visible query string (notice ./login.php?username=…&password=… as URL when executing the script login.php) and is retrieved by login.php by $_GET['username'] and $_GET['password'].

POST: we are submitting a form to login.php, when we do submit or similar action, values are sent through invisible standard input (notice ./login.php) and is retrieved by login.php by $_POST['username'] and $_POST['password'].

POST method data is sent by standard input (nothing shown in URL when posting while in GET method data is sent through query string.



  • PHP - Echo?php $myiString = "Hi!"; echo $myiString; echo "I love PHP!"; ?   Display: Hi! I love  PHP!  A simple form example     1 2 3 Building a Form 4 5 6 " 7 method="get" 8 9 Search: 10 1… Read More
  • PHP Array Functionsarray_change_key_case — Changes all keys in an array array_chunk — Split an array into chunks array_combine — Creates an array by using one array for keys and another for its values array_count_values — Counts all the value… Read More
  • Php Directory Functionschdir — Change directory chroot — Change the root directory closedir — Close directory handle dir — Return an instance of the Directory class getcwd — Gets the current working directory opendir — Open directory handle read… Read More
  • Php Mysql Image upload?php // 1. Gem modtagne formulardata i variabler: $navn = $_POST['navn']; $alder = $_POST['alder']; $postnr = $_POST['postnr']; $mail = $_POST['mail']; $billede = $_FILES['profilbillede']; $password = $_POST['… Read More
  • PHP MySQL Functionsmysql_field_len — Returns the length of the specified field mysql_field_name — Get the name of the specified field in a result mysql_field_seek — Set result pointer to a specified field offset mysql_field_table — Get … Read More
  • Length of a StringThe length property of a string is determined with the strlen( ) function, which returns the number of eight-bit characters in the subject string: integer strlen(string subject) We used strlen( ) earlier in the chapter t… Read More
  • Defining FunctionsThere are already many functions built into PHP. However, you can define your own and organize your code into functions. To define your own functions, start out with the function statement: function some_function([argumen… Read More
  • PHP HTTP Functionsob_deflatehandler — Deflate output handler ob_etaghandler — ETag output handler ob_inflatehandler — Inflate output handler http_parse_cookie — Parse HTTP cookie http_parse_headers — Parse HTTP headers http_parse_message — P… Read More
  • PHP Date / Time Functionscheckdate — Validate a Gregorian date date_add — Alias of DateTime::add date_create_from_format — Alias of DateTime::createFromFormat date_create — Alias of DateTime::__construct date_date_set — Alias of DateTime::setDate …Read More
  • PHP Zip File Functionszip_close — Close a ZIP file archive zip_entry_close — Close a directory entry zip_entry_compressedsize — Retrieve the compressed size of a directory entry zip_entry_compressionmethod — Retrieve the compression meth… Read More
  • Including and Requiring PHP FilesTo make your code more readable, you can place your functions in a separate file. Many PHP add-ons that you download off the Internet contain functions already placed into files that you simply include in your PHP program… Read More
  • Creating ArraysPHP provides the array( ) language construct that creates arrays. The following examples show how arrays of integers and strings can be constructed and assigned to variables for later use: $numbers = array(5, 4, 3, 2, 1);… Read More
  • File Manipulation11.3. File Manipulation There may be times when you don't want to store information in a database and may want to work directly with a file instead. An example is a logfile that tracks when your application can't co… Read More
  • PHP Configuration DirectivesAlthough the focus of this book is application security, there are a few configuration directives with which any security-conscious developer should be familiar. The configuration of PHP can affect the behavior of the cod… Read More
  • Showing the Browser and IP AddressHere is a simple page that prints out the browser string and the IP address of the HTTP request. Create a file with the following content in your web directory, name it something like example.php3, and load it in your bro… Read More
PHP Functions
Php tutorial - imagemagick
php.ini Basics
PHP Sessions
Cookies Versus Sessions
PHP Web-Related Variables
PHP ERRORS
maximum size of a file uploaded
Php Image upload
php file_get_contents
MySQL Data on the Web
What are GET and POST
php and pdf
$_ENV and $_SERVER
PEAR with php
SELECTING DATA PHP
prevent hijacking with PHP
LAMP
PHP MySQL Functions
PHP Zip File Functions
Substrings PHP
PHP Variable names
PHP magic methods
How to get current session id
Add variables into a session
$_GET , $_POST,$_COOKIE
different tables present in mysql
PHP CURL
php Sessions page
PHP-sorting an array
PHP-count the elements of array
Operators for If/Else Statements
PHP file uploading code
PHP global variables
Testing working using phpinfo
PHP Code for a Valid Number
PHP-Associative Arrays
PHP mvc tutorial
PHP get_meta_tags-Extracts
difference between print and echo
PHP best tutorial-PHP variables
Reading DOC file in PHP
PHP interview questions
convert time PHP
PHP implode array elements
header function-PHP
PHP-Renaming Files Directories
PHP Classes
in_array function in PHP
keep your session secure PHP
Web Application with PHP
What is SQL Injection
PHP-extract part of a string
PHP urlencode
PHP- know browser properties
PHP- Extracting Substrings
Checking Variable Values /Types
PHP-best 20 Open Source cms
IP AddressPHP
PHP-Scope Resolution Operator
how create new instance of object
how eliminate an object
PHP- ob_start
XML file using the DOM API
PHP- MVC
PHP- CAPTCHA
PHP- Position of a Value in an Array
PHP-Mail Functions
PHP-difference include vs require
calculate the sum of values in an array
PHP-total number of rows
Show unique records mysql
MySQL Triggers
MySQL data directory
MySQL Subqueries
PHP- Networking Functions
PHP- Operators
Restore database
Conditional Functions mysql
PHP-function overloading
Friend function
mysql_connect /mysql_pconnect
PHP-Error Control Operators
what is IMAP
Apache-Specific Functions
Send Email from a PHP Script
SQL inherently
WAMP, MAMP, LAMP
Php tutorial-SYMBOLS
Table Types-MySQL
PHP-Encryption data management
PHP Array
Running MySQL on Windows
Maximum Performance MySQL
XML-RPC
PHP-static variables
Advanced Database Techniques
FTP
Codeigniter
Apache Pool Size
Why NoSQL
MySQL Server Performance
Database software
SQL Interview Answers
PHP Redirect
PHP Interview Questions with Answers
Advanced PHP

What is the default session time in php and how can I change it?

The default session time in php is until closing of browser

What are the MySQL database files stored in system ?

Data is stored in name.myd
Table structure is stored in name.frm
Index is stored in name.myi