Difference between echo and print?
void echo ( string $arg1 [, string $...] )
Outputs all parameters.
echo() is not actually a function (it is a language construct), so you are not required to use parentheses with it. echo() (unlike some other language constructs) does not behave like a function, so it cannot always be used in the context of a function. Additionally, if you want to pass more than one parameter to echo(), the parameters must not be enclosed within parentheses.
echo() also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign. This short syntax only works with the short_open_tag configuration setting enabled.
I have foo.
print --- out put a string
print behaves like a function and you can return values and echo can't
Prin can be used as a part of more complex operations
What is the use of ob_start in php?
ob_start — Turn on output buffering
According to PHP manual*
Description
bool ob_start ( [callback $output_callback [, int $chunk_size [, bool $erase]]] )
This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.
The contents of this internal buffer may be copied into a string variable using ob_get_contents(). To output what is stored in the internal buffer, use ob_end_flush(). Alternatively, ob_end_clean() will silently discard the buffer contents.
Warning
Some web servers (e.g. Apache) change the working directory of a script when calling the callback function. You can change it back by e.g. chdir(dirname($_SERVER['SCRIPT_FILENAME'])) in the callback function.
Output buffers are stackable, that is, you may call ob_start() while another ob_start() is active. Just make sure that you call ob_end_flush() the appropriate number of times. If multiple output callback functions are active, output is being filtered sequentially through each of them in nesting order.
How to reverse an array values using recursive method in php ?
$array=array(1,2,3,4,5,6);
rec($array,5);
echo $f1= substr($f,0,-1);
function rec($arr,$index)
{
global $f;
if($index==-1)
return;
$f.=$arr[$index].',';
$index--;
rec($arr,$index);
}
?>
//Output: 6,5,4,3,2,1
How to reverse a string in php with out using any built in functions?
function w3RevStr($str) {
$revStr = "";
$w=0;
while($c=$str[$w]){
$revStr = $c.$revStr;
$w=$w+1;
}
return $revStr;
}
echo w3RevStr("www.w3answers.com");
?>
How many HTTP headers will send to a web page(client side) from server when you use sessions (session_start()) in php ?.
There are three HTTP headers included in the response:
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
what are the advantages of storing sessions in database?
If you store a session in a database you have several advantages:
@ Improving the security because on many hosting packages (shared host)
PHP uses the same path for storing sessions for all the users,
somewhere that is not in your folders.
@ You can track who is online etc.
@ For application that are running on multiple servers, you can store
all the session data in one database.
The real beauty of this approach is that you don't have to modify your code or the way you use sessions in any way. $_SESSION still exists and behaves the same way, PHP still takes care of generating and propagating the session identifier, and changes made to session configuration directives still apply. All you have to do is call this one function.
You must call session_set_save_handler() prior to calling session_start(), but you can define the functions themselves anywhere.
The function is called session_set_save_handler(), and it takes six arguments,
1. Opening the session data store
2. Closing the session data store
3. Reading session data
4. Writing session data
5. Destroying all session data
6. Cleaning out old session data
How to get the contents of a web page using php?
you can achieve this using curl in php
see the example below.
function curl_get_con_url($url, $user_agent = '', $referer = '') {
// create a new CURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
/* This lines will make sure that you can save the web page into a variable */
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt($ch, CURLOPT_REFERER, $referer);
// grab URL
$page_content = curl_exec($ch);
if (curl_errno($ch)) {
$page_content = false;
}
// close CURL resource, and free up system resources
curl_close($ch);
return $page_content;
}
$referads_pc = curl_get_con_url('www.referads.com');
what are the security tips you should know before developing php/mysql web pages ?
1. Do not trust user input.
2. Validate user input on the server side.
3. Do not use user input directly in your MySQL queries.
4. Don't put integers in quotes In your MySQL queries.
5. Always escape the output using php built in functions.
6. When uploading files, validate the file mime type using php.
7. If you are using 3rd party code libraries, be sure to keep them up to date.
8. Give your database users just enough permissions.
9. Do not allow hosts other than localhost to connect to your database.
10. Your library file extensions should be PHP.
11. Have register globals off or define your variables first
12. Keep PHP itself up to date (use latest version php5 or above)
what are the database space-saving functions available in php ?
Use ip2long() and long2ip() to store the IP adresses as Integers instead of storing them as strings, which will reduce the space from 15 bytes to 4 bytes. This will also increase search speed and make it easy to see if a ip falls within a specified range.
# Use gzcompress() and gzuncompress() to reduce the strings before you store them in a database. The gzcompress can compress plain-text up to 90%. The only reason why you shouldn’t use it is when you need full-text indexing capabilities.
what you should know about cookies before start using in php?
There are a few things you should be aware of:
1. Since cookies are used to record information about your activities on a particular domain, they can only be read by the domain that created them
2. A single domain cannot set more than twenty cookies, and each cookie is limited to a maximum size of 4 KB
3. A cookie usually possesses six attributes, of which only the first is mandatory. Here they are:
* name: the name of the cookie
* value: the value of the cookie
* expires: the date and time at which the cookie expires
* path: the top-level directory on the domain from which cookie data can be accessed
* domain: the domain for which the cookie is valid
* secure: a Boolean flag indicating whether the cookie should be transmitted only over a secure HTTP connection
It's important to remember that, since cookies are stored on the user's hard drive, you as the developer have very little control over them. If a user decides to turn off cookie support in his or her browser, your cookies will simply not be saved. Therefore, avoid writing code that depends heavily on cookies; and have a backup plan ready in case cookie data cannot be retrieved from the client.
Two types of cookies
1) temporary and
2) persistent cookies
Given a line of text $string, how would you write a regular expression to strip all the HTML tags from it?
$stringOfText = "
This is a test
";$expression = "/<(.*?)>(.*?)<\/(.*?)>/";
echo preg_replace($expression, "\\2", $stringOfText);
what are the ways to check image mime types in php?
There are a few inbuilt options you can use however, for example getimagesize() can return the mimetype, as does some of the new fileinfo functions. The mime type in getimagesize is stored in 'mime', and can be accessed as shown below.
$parts = getimagesize($filename);
echo $parts['mime'];
?>
or
$parts = getimagesize($filename);
$allowedMimes = array('image/jpg', 'image/png', 'image/gif');
if(in_array($parts['mime'], $allowedMimes))
echo 'Valid Mimetype!';
?>
other way
$filename = 'maliciousScript.jpg.php'; // filename to check
$parts = explode('.', $filename); // common (but wrong) method used
echo $parts[1];
echo strrchr($filename, '.'); // correct method
?>
echo system('file -ib '. $filename);
?>
how to opening excel files in windows nad linux using php ?
if you're using PHP on Windows, you can use the inbuilt COM library
$excel = new COM("excel.application");
$excel->Workbooks->Open("filename.xls");
On Linux machines, is PHPExcelReader( download from sourceforgr.net), and it seems to work very efficiently and easily with only a few lines of code.
$data = new Spreadsheet_Excel_Reader();
$data->read("filename.xls");
And you can access the data with a simple loop:
for($i=1; $i <= $data->sheets[0]['numRows']; $i++)
{
echo 'Row '. $i .', Column a:' $data->sheets[0]['cells'][$i][1] . '
';
echo 'Row '. $i .', Column b:' $data->sheets[0]['cells'][$i][2] . '
';
}
How many ways your web server can utilize PHP to generate web pages?
Mainly there are three ways
***************************
The first method is to use PHP as a CGI "wrapper". When run this way, an instance of the PHP interpreter is created and destroyed for every page request (for a PHP page) to your web server. Because it is destroyed after every request, any resources that it acquires (such as a link to an SQL database server) are closed when it is destroyed. In this case, you do not gain anything from trying to use persistent connections -- they simply don't persist.
The second, and most popular, method is to run PHP as a module in a multiprocess web server, which currently only includes Apache. A multiprocess server typically has one process (the parent) which coordinates a set of processes (its children) who actually do the work of serving up web pages. When a request comes in from a client, it is handed off to one of the children that is not already serving another client. This means that when the same client makes a second request to the server, it may be served by a different child process than the first time. When opening a persistent connection, every following page requesting SQL services can reuse the same established connection to the SQL server.
The last method is to use PHP as a plug-in for a multithreaded web server. Currently PHP 4 has support for ISAPI, WSAPI, and NSAPI (on Windows), which all allow PHP to be used as a plug-in on multithreaded servers like Netscape FastTrack (iPlanet), Microsoft's Internet Information Server (IIS), and O'Reilly's WebSite Pro. The behavior is essentially the same as for the multiprocess model described before. Note that SAPI support is not available in PHP 3.
What is meant by Persistent Database Connections?
Persistent connections are links that do not close when the execution of your script ends. When a persistent connection is requested, PHP checks if there's already an identical persistent connection (that remained open from earlier) - and if it exists, it uses it. If it does not exist, it creates the link. An 'identical' connection is a connection that was opened to the same host, with the same username and the same password (where applicable).
Note
*****
People who aren't thoroughly familiar with the way web servers work and distribute the load may mistake persistent connects for what they're not. In particular, they do not give you an ability to open 'user sessions' on the same link, they do not give you an ability to build up a transaction efficiently, and they don't do a whole lot of other things. In fact, to be extremely clear about the subject, persistent connections don't give you any functionality that wasn't possible with their non-persistent brothers.
Its extremely simple and efficient. Persistent connections are good if the overhead to create a link to your SQL server is high. Whether or not this overhead is really high depends on many factors. Like, what kind of database it is, whether or not it sits on the same computer on which your web server sits, how loaded the machine the SQL server sits on is and so forth. The bottom line is that if that connection overhead is high, persistent connections help you considerably. They cause the child process to simply connect only once for its entire lifespan, instead of every time it processes a page that requires connecting to the SQL server. This means that for every child that opened a persistent connection will have its own open persistent connection to the server. For example, if you had 20 different child processes that ran a script that made a persistent connection to your SQL server, you'd have 20 different connections to the SQL server, one from each child.
List out some session functions in php?
session_save_path -- Get and/or set the current session save path
session_is_registered -- Find out whether a global variable is registered in a session
session_unset -- Free all session variables
session_cache_expire -- Return current cache expire
session_cache_limiter -- Get and/or set the current cache limiter
session_commit -- Alias of session_write_close()
session_decode -- Decodes session data from a string
session_destroy -- Destroys all data registered to a session
session_write_close -- Write session data and end session
session_encode -- Encodes the current session data as a string
session_get_cookie_params -- Get the session cookie parameters
session_id -- Get and/or set the current session id
session_module_name -- Get and/or set the current session module
session_name -- Get and/or set the current session name
session_regenerate_id -- Update the current session id with a newly generated one
session_register -- Register one or more global variables with the current session
session_set_cookie_params -- Set the session cookie parameters
session_set_save_handler -- Sets user-level session storage functions(Like storing to Databases like MySQl,Oracle etc)
session_start -- Initialize session data
session_unregister -- Unregister a global variable from the current session
What is the process that takes place when you upload a file in php?
There are two basic things covered here.
The form that will be used to post the file data to and the actual program that does the uploading. Further we will discuss the method that PHP itself suggests for uploading files.
Process 1 HTML PART
*******************
Note the enctype is set to "multipart/form-data".
This is crucial to the working of the application. If it is not specified here then the program will not work.
Next you'll notice that MAX_FILE_SIZE precedes the file input field. The MAX_FILE_SIZE for this demonstration is limited to 30000 bytes, or about 29K, but can easily be modified for larger files.
Finally you have the input sections. The first is set to create an input box that allows the user to choose his file and the second is the button that actually submits the file for upload. In the next section you'll notice that the name of the input element for type="file" will be used to determine the name to pull from the $_FILES array.
Form Method must be POST
Process 2 PHP PART
******************
$imgdir = '/imgdir/';
$uploadfile = $imgdir. basename($_FILES['smefile']['name']);
if (move_uploaded_file($_FILES[ 'smefile']['tmp_name'], $uploadfile)) {
echo "File successfully uploaded";
} else {
echo "Upload failed";
}
?>
Will persistent connection work in the CGI version of php ? mysql_connect() vs mysql_pconnect()
Persistent database connections work only in the module installation of PHP.
If you ask for a persistent connection in the CGI version,
you will simply get a regular connection.
if you become convinced that the sheer overhead of opening new database connections is killing your performance, you might want to investigate opening persistent connections.Unlike regular database connections, these connections are not automatically killed when your page exits (or even when mysql_close() is called) but are saved in a pool for future use. The first time one of your
scripts opens such a connection, it is opened in the same resource-intensive way as with a regular database connection. The next script that executes,however, might get that very same connection in response to its request, which saves the cost of reopening a fresh connection. (The previous connection will be reused only if the
parameters of the new request are identical.)
Other than offering a particular kind of increased efficiency, persistent
database connections do not provide any functionality beyond that of regular database connections.
What are the 'function problems' you have met in php?
1)Call to undefined function we_w3answers()
*****************************************
PHP is trying to call the function we_w3answers(), which has not been
because you misspelled the name of a function (built-in or user-defined)
simply omitted the function definition. If you use include/require
functions, make sure that you are loading the appropriate files.
2)Call to undefined function array()
***********************************
This problem has a cause that is similar to the cause of the previous problem, although it still baffled us completely the first time we ran into it. It can arise when you have code like the following:
$my_w3answers= array();
$my_w3answers(5) = “the fifth”;
3)Cannot redeclare my_function()
*******************************
This is a simple one—somewhere in your code you have two definitions of my_function(), which PHP will not stand for.
Make sure that you are not using include to pull in the same file of function definitions more than once. Use include_once or require_once to avoid
4)Wrong parameter count
***********************
Explain Parse Errors ? what are the most common causes of parse errors ?
The most common category of error arises from mistyped
or syntactically incorrect PHP code, which confuses the PHP parsing engine.
1)The missing semicolon
***********************
If each PHP instruction is not duly finished off with a semicolon,
a parse error will result. In this sample fragment, the first line lacks a semicolon and, therefore, the variable assignment is never completed.
What we have here is
$Problem = “a silly misunderstanding”
echo $Problem;
?>
2)No dollar signs
*******************
Another very common problem is that a dollar sign prepending
a variable name is missing.If the dollar sign is missing during
the initial variable assignment, like so:
What we have here is
Problem = “a big ball of earwax”;
echo $Problem;
?>.
A parse error message will result. However, if instead the
dollar sign is missing from a later
output of the variable, like this:
What we have here is
$Problem = “a big ball of earwax”;
print(“Problem”);
?>
3)Mode issues
**************
A parse error will result if you fail to close off a PHP block properly, as in:
What we have here is
$Problem = “an awful kerfuffle”;
echo $Problem;
4)Unescaped quotes
********************
5)Unterminated strings
**********************
What Are PHP Arrays?
PHP arrays are associative arrays with a little extra machinery thrown in.
The associative part means that arrays store element
values in association with key values rather than in a
strict linear index order. (If you have seen arrays in other programming languages, they are likely to have been vector arrays rather
than associative arrays.) If you store an element in an array,
in association with a key,all you need to retrieve it later from
that array is the key value. For example, storage is as
simple as this:
$state_location[‘San Mateo’] = ‘California’;
which stores the element ‘California’ in the array variable $state_location,
in association with the lookup key ‘San Mateo’. After this has been stored,
you can look up the stored value by using the key, like so:
$state = $state_location[‘San Mateo’]; // equals ‘California’
If all you want arrays for is to store key/value pairs, the preceding
information is all you need to know. Similarly,
if you want to associate a numerical ordering with a bunch of values,
all you have to do is use integers as your key values, as in:
$my_array[1] = “The first thing”;
$my_array[2] = “The second thing”;
Are php strings immutable ?
PHP strings can be changed, but the most common practice seems to be to treat strings as immutable. Strings can be changed by treating them as character
arrays and assigning directly into them, like this:
$my_string = “abcdefg”;
$my_string[5] = “X”;
print($my_string . “
”);
which will give the browser output:
abcdeXg
?>
what is Memcache?
Memcache is a technology which caches objects in memory where your web application can get to them really fast. It is used by sites such as Digg.com, Facebook.com and NowPublic.com and is widely recognized as an essential ingredient in scaling any LAMP application to handle enormous traffic.
How do I prevent Web browsers caching a page in php?
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Pragma: no-cache');
?>
what is the php solution to dynamic caching ?
PHP offers an extremely simple solution
to dynamic caching in the form of
output buffering.
what are the most common caching policy approaches ?
1)Time triggered caching (expiry timestamp).
2)Content change triggered caching (sensitive content has changed, so cache must be updated).
3)Manually triggered caching (manually inform the application that information is outdated, and force a new cache creation).
How to capture content from the output buffer ? or Give me an example for
Output caching in php?
ob_start(); // start an output buffer
echo ‘This text is from the w3answers buffer*******
’; // output that will be stored in the buffer
$w3buffer = ob_get_contents(); // store buffer content in $w3buffer variable
ob_end_clean(); // stop and clean the output buffer
echo ‘This is not from the w3answers buffer!!!!!!!!
’;
echo $w3buffer;
?>
O/p
*****
This is not from the w3answers buffer!!!!!!!!
This text is from the w3answers buffer*******
What is the difference between $message and $$message?
$message is a simple variable whereas $$message is a variable's variable,which means
value of the variable. Example:
$user = 'bob'
is equivalent to
$message = 'user';
$$message = 'bob';
why should we use Object oriented concepts in php ?
1. Object oriented PHP code is much more reusable because by its' very nature, it is modular.
2. Object oriented PHP is easier to update. Again, because PHP code is organised into objects.
3. Object oriented PHP makes team programming much easier to manage.
4. Object oriented PHP makes larger projects much easier to manage.
5. Object oriented PHP makes creating code libraries much easier.
6. Knowing Object oriented PHP will make working with many opensource PHP libraries much easier. For example: projects like PEAR and the Zend Framework are built using Object oriented PHP.
7. Object oriented PHP programmers typically make more money and will be able to work on more projects.
8. Since object oriented concepts are the same in all Object oriented languages, once you learn Object oriented programing in PHP, you will also have a good understanding of several other languages including:
a. Ruby
b. Java
c. C#
d. Actionscript
…among several other languages.
which is faster mysql_unbuffered_query or mysql_query ?
when we do the select queries that retrieve large data sets from MySQL, mysql_unbuffered_query in PHP is likely to give better performance than mysql_query.
PHP manual says,
it “sends a SQL query query to MySQL, without fetching and buffering the result rows automatically”.
How can we extract string "w3answers.com" from a string
mailto:info@w3answers.com using regular expression of PHP ?
$w3 = "mailto:info@w3answers.com";
preg_match('|.*@([^?]*)|', $w3, $w3output);
echo $w3output[1];
?>
Which function in PHP gives us absolute path of a file on the server?
getcwd()
$p = getcwd();
echo $p;
?>
here I have stored my files under httdocs (using php5,i haven't checked under php4) so I get the output as C:\apache2triad\htdocs
you may get your path information while runnings the above code. :)
what is the output here ?
session_start();
$_SESSION["var"] = NULL;
echo $var = "www.w3answers.com";
?>
The output :
www.w3answers.com and warning as below
Warning: Unknown: Your script possibly relies on a session side-effect which existed until PHP 4.2.3. Please be advised that the session extension does not consider global variables as a source of data, unless register_globals is enabled. You can disable this functionality and this warning by setting session.bug_compat_42 or session.bug_compat_warn to off, respectively. in Unknown on line 0
what is the output ?
echo "www.w3answers.com";
if ((string)'-1') { print 'ouch'; } else { print 'echo'; }
?>
a. ouch
b. echo
c. none
d. Parse error
ANS: a
what output do you get here?
$here = "/home/httpd/html/test ";
list ($j1,$j2,$j3,$j4) = split('/',$here);
print "$j3";
?>
a. home
b. Array
c. test
d. httpd
ANS: httpd
Which of the following functions is most efficient for substituting fixed
patterns in strings?
A. preg_replace()
B. str_replace()
C. str_ireplace()
D. substr_replace()
Answer B is correct.
The PHP efficiency mantra is “do no more work than necessary.”
Both str_ireplace() and preg_replace() have more expensive (and flexible)
matching logic, so you should only use them when your problem requires it.
substr_replace() requires you to know the offsets and lengths of the substrings
you want to replace, and is not sufficient to handle the task at hand.
Which of the following represents the proper way to set a session variable?
A. $_SESSION[‘foo’] = ‘bar’;
B. session_start();
C. session_set_save_handler (‘myopen’, ‘myclose’, ‘myread’,
‘mywrite’, ‘mydelete’, ‘mygarbage’);
D. $foo = $_SESSION[‘foo’];
Answer A is correct.
Answer B is incorrect because session_start() only activates
PHP sessions for the current script. Answer C is incorrect because
session_set_save_handler() allows you to override PHP’s default session
mechanism with your own custom functions. Answer D is incorrect; session data is
being used as the value of a regular variable and is not being manipulated in any
way.
How we can pass data from PHP to ASP,ASP.net?
PHP to ASP
Let's first look at how you can pass data from PHP to ASP using WDDX.
You create a WDDX packet by first serializing data into a WDDX packet and then presenting it.
WDDX can convert most variable types that applications use, such as strings, integers, and arrays. After a variable has been converted to a WDDX variable type, it is ready for another application to pick up.
PHP has WDDX support built in, so you don't need to modify your PHP.ini file to start using WDDX.
A PHP Script to Serialize WDDX
//define PHP data to send
$ValueToSend = "Andrew";
//convert PHP data to WDDX data
$wddxvar = wddx_serialize_value("$ValueToSend");
//output WDDX data
print("$wddxvar");
?>
You first set the data you want to serialize into a WDDX packet:
$ValueToSend = "Andrew";
You then serialize that data:
$wddxvar = wddx_serialize_value("$ValueToSend");
Finally, you present that data as
print("$wddxvar");
********************************
O/P=Andrew
********************************
Internet Explorer just shows the data within the WDDX packet. It doesn't show the surrounding XML structures. However, if you choose the view source option, you can see the WDDX packet's XML structures
#################################-END-
**************************************************
ASP Script to Deserialize WDDX Data
**************************************************
To receive the WDDX packet from the PHP script, you must load the packet into a variable within the receiving ASP script. None of the WDDX implementations (the WDDX COM component or PHP's WDDX functions) provides native ways of doing this. You must add this functionality using separate code. After you receive the WDDX packet, you can convert it into a data type native to the receiving application. This is called deserializing.
Using ASP, you can use a third-party COM component. A free COM component that allows such functionality is ASP Tear from http://www.alphasier-rapapa.com/IisDev/Components/ (also included with the WDDX SDK). However, you can use any COM component that has similar functionality.
<%
set aspget = Server.CreateObject("SOFTWING.AspTear")
set wddxob = Server.CreateObject("WDDX.Deserializer.1")
'get WDDX data
wddxdata = aspget.Retrieve("http://localhost/phpbook/Chapter5_Sessions/WDDX/PHP/
two_wddxserver.php", Request_POST, "", "", "")
'convert WDDX data to ASP data
wddxvar = wddxob.deserialize(wddxdata)
'output ASP data
response.write "Hello " & wddxvar
set wddxob = nothing
set aspget = nothing
%>
First, you must load the WDDX and ASP Tear COM objects into memory for use by ASP. Don't worry too much if you are not familiar with using COM objects
set aspget = Server.CreateObject("SOFTWING.AspTear")
set wddxob = Server.CreateObject("WDDX.Deserializer.1")
Next you use ASP Tear to obtain the WDDX packet produced by the PHP server and load it into a variable:
'get WDDX data
wddxdata = aspget.Retrieve("http://localhost/phpbook/Chapter5_Sessions/WDDX/PHP/
two_wddxserver.php", Request_POST, "", "", "")
You deserialize the WDDX packet into a native data type for ASP:
'convert WDDX data to ASP data
wddxvar = wddxob.deserialize(wddxdata)
You then output the value:
'output ASP data
response.write "Hello " & wddxvar
Finally, you unload the COM objects from memory:
set wddxob = nothing
set aspget = nothing
ASP to PHP
PHP can also receive WDDX packets. Here you will see a PHP script obtaining a WDDX packet from an ASP script.
*************************************************
An ASP Script to Serialize WDDX
*************************************************
<%
'define ASP data to send
ValueToSend = "Andrew"
set wddxob = Server.CreateObject("WDDX.Serializer.1")
'convert ASP data to WDDX data
wddxvar = wddxob.serialize(ValueToSend)
'output WDDX data
response.write wddxvar
set wddxob = nothing
%>
This is very much the same as the serializing PHP script. First, you define the value you want to serialize in WDDX:
'define ASP data to send
ValueToSend = "Andrew"
You then load the WDDX COM object into memory, ready for use by ASP:
set wddxob = Server.CreateObject("WDDX.Serializer.1")
You then serialize the value into a WDDX packet:
'convert ASP data to WDDX data
wddxvar = wddxob.serialize(ValueToSend)
You then display the WDDX packet:
'output WDDX data
response.write wddxvar
Finally, you unload the WDDX COM object from memory:
set wddxob = nothing
*******************************************************
A PHP Script to Deserialize WDDX Data
********************************************************
The deserialize PHP script needs to do the same as the deserialize ASP script: It must convert the WDDX packet back into a native variable type for our script (in this case, a native variable type for PHP):
//get WDDX data
$wddxdata = join ('', file
('http://localhost/phpbook/Chapter5_Sessions/WDDX/ASP/one_wddxserver.asp'));
//convert WDDX data to PHP data
$wddxvar = wddx_deserialize("$wddxdata");
//output PHP data
print("Hello " . $wddxvar);
?>
You can obtain the WDDX packet from the ASP script using the PHP join function. To use the function in this manner, you must make sure that HTTP transparency is enabled in the PHP.ini settings file (the allow_url_fopen setting is enabled). (Note that HTTP transparency is enabled by default.)
$wddxdata = join ('', file
('http://localhost/phpbook/Chapter5_Sessions/WDDX/ASP/one_wddxserver.asp'));
As before, you deserialize the WDDX packet into a native variable type:
$wddxvar = wddx_deserialize("$wddxdata");
You then display the WDDX packet:
print("Hello " . $wddxvar);
How can you block certain IP Addresses from accessing your site?
$banned = array("24.91.102.173", "64.21.162.113");
if (in_array($_SERVER['REMOTE_ADDR'], $banned)) {
echo "You have been banned.";
exit;
}
?>
What Storage Engines do you use in MySQL?
MySQL Engines
*****************************************
MyISAM
HEAP
MEMORY
MERGE
MRG_MYISAM
ISAM
MRG_ISAM
InnoDB
INNOBASE
BDB
BERKELEYDB
NDBCLUSTER
NDB
EXAMPLE
ARCHIVE
CSV
What is Apache?
The most widely available HTTP server on the Internet. It supports the PERL and PHP languages.
The Apache HTTP Server Project is a collaborative software development effort aimed at creating a robust, commercial-grade, featureful, and freely-available source code implementation of an HTTP (Web) server. The project is jointly managed by a group of volunteers located around the world, using the Internet and the Web to communicate, plan, and develop the server and its related documentation. This project is part of the Apache Software Foundation. In addition, hundreds of users have contributed ideas, code, and documentation to the project. This file is intended to briefly describe the history of the Apache HTTP Server and recognize the many contributors.
Installing PHP on your Computer?
You can download apache2triad from
http://sourceforge.net/projects/apache2triad/
Its a single setup file for
---------------------------
Apache2 , MySQL , PostgreSQL , OpenSSL , Xmail , SlimFTPd Software developing triad of : PHP , Perl and Python + Apache2TriadCP , PHPmyadmin , PHPPgAdmin , AWStats , UebiMiau , PHPXMail , PHPSFTPd. All latest stables , all manuals
Use this for your php installation in your pc!!!
What can PHP do?
Anything. PHP is mainly focused on server-side scripting, so you can do anything any other CGI program can do, such as collect form data, generate dynamic page content, or send and receive cookies. But PHP can do much more.
There are three main areas where PHP scripts are used.
Server-side scripting. This is the most traditional and main target field for PHP. You need three things to make this work. The PHP parser (CGI or server module), a webserver and a web browser. You need to run the webserver, with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the server. All these can run on your home machine if you are just experimenting with PHP programming.
Command line scripting. You can make a PHP script to run it without any server or browser. You only need the PHP parser to use it this way. This type of usage is ideal for scripts regularly executed using cron (on *nix or Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text processing tasks.
Writing desktop applications. PHP is probably not the very best language to create a desktop application with a graphical user interface, but if you know PHP very well, and would like to use some advanced PHP features in your client-side applications you can also use PHP-GTK to write such programs. You also have the ability to write cross-platform applications this way. PHP-GTK is an extension to PHP, not available in the main distribution.
PHP can be used on all major operating systems, including Linux, many Unix variants (including HP-UX, Solaris and OpenBSD), Microsoft Windows, Mac OS X, RISC OS, and probably others. PHP has also support for most of the web servers today. This includes Apache, Microsoft Internet Information Server, Personal Web Server, Netscape and iPlanet servers, Oreilly Website Pro server, Caudium, Xitami, OmniHTTPd, and many others. For the majority of the servers PHP has a module, for the others supporting the CGI standard, PHP can work as a CGI processor.
So with PHP, you have the freedom of choosing an operating system and a web server. Furthermore, you also have the choice of using procedural programming or object oriented programming, or a mixture of them. Although not every standard OOP feature is implemented in PHP 4, many code libraries and large applications (including the PEAR library) are written only using OOP code. PHP 5 fixes the OOP related weaknesses of PHP 4, and introduces a complete object model.
With PHP you are not limited to output HTML. PHP's abilities includes outputting images, PDF files and even Flash movies (using libswf and Ming) generated on the fly. You can also output easily any text, such as XHTML and any other XML file. PHP can autogenerate these files, and save them in the file system, instead of printing it out, forming a server-side cache for your dynamic content.
One of the strongest and most significant features in PHP is its support for a wide range of databases. Writing a database-enabled web page is incredibly simple. The following databases are currently supported:
Adabas D InterBase PostgreSQL
dBase FrontBase SQLite
Empress mSQL Solid
FilePro (read-only) Direct MS-SQL Sybase
Hyperwave MySQL Velocis
IBM DB2 ODBC Unix dbm
Informix Oracle (OCI7 and OCI8)
Ingres Ovrimos
We also have a database abstraction extension (named PDO) allowing you to transparently use any database supported by that extension. Additionally PHP supports ODBC, the Open Database Connection standard, so you can connect to any other database supporting this world standard.
PHP also has support for talking to other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (on Windows) and countless others. You can also open raw network sockets and interact using any other protocol. PHP has support for the WDDX complex data exchange between virtually all Web programming languages. Talking about interconnection, PHP has support for instantiation of Java objects and using them transparently as PHP objects. You can also use our CORBA extension to access remote objects.
PHP has extremely useful text processing features, from the POSIX Extended or Perl regular expressions to parsing XML documents. For parsing and accessing XML documents, PHP 4 supports the SAX and DOM standards, and you can also use the XSLT extension to transform XML documents. PHP 5 standardizes all the XML extensions on the solid base of libxml2 and extends the feature set adding SimpleXML and XMLReader support.
At last but not least, we have many other interesting extensions, the mnoGoSearch search engine functions, the IRC Gateway functions, many compression utilities (gzip, bz2, zip), calendar conversion, translation...
What is PHP?
PHP: Hypertext Preprocessor, an open source, server-side, HTML embedded scripting language used to create dynamic Web pages.
In an HTML document, PHP script (similar syntax to that of Perl or C ) is enclosed within special PHP tags. Because PHP is embedded within tags, the author can jump between HTML and PHP (similar to ASP and Cold Fusion) instead of having to rely on heavy amounts of code to output HTML. And, because PHP is executed on the server, the client cannot view the PHP code.
PHP can perform any task that any CGI program can do, but its strength lies in its compatibility with many types of databases. Also, PHP can talk across networks using IMAP, SNMP, NNTP, POP3, or HTTP.
PHP was created sometime in 1994 by Rasmus Lerdorf. During mid 1997, PHP development entered the hands of other contributors. Two of them, Zeev Suraski and Andi Gutmans, rewrote the parser from scratch to create PHP version 3 (PHP3).
PHP OOPS Interview Questions
what is Magic methods in php?
There are seven special methods, and they are as follows:
__construct( )
Called when instantiating an object
__destruct( )
Called when deleting an object
__get( )
Called when reading from a nonexistent property
__set( )
Called when writing to a nonexistent property
__call( )
Called when invoking a nonexistent method
__toString( )
Called when printing an object (for eg: converting an object to strings)
__clone( )
Called when cloning an object (copying object)
Explain Constructors and Destructors in php?
__construct( )
Called when instantiating an object
__destruct( )
Called when deleting an object
Constructors and destructors are functions that are called when a new instance of an object is created (constructors) and/or destroyed (destructors). Their primary purpose is to allow for a means to initialize and clean up after an object during its use.
Constructors can accept parameters, which are assigned to specific object fields at
creation time.
Constructors can call class methods or other functions.
constructors are intuitively useful for initializing class properties,
Class constructors can call on other constructors, including those from the class parent.
One classic example is a class to access a database back end, where a constructor could make the connection to the database while the destructor closes it.
PHP 4 Constructors
In PHP 4, only constructors were available and were created by defining a function whose name was the same as the class itself:
class w3Class {
function w3Class($param) {
echo "Created a new instance of w3Class!";
}
}
$w3instance = new w3Class;
?>
In PHP 5, this concept has been changed PHP 5 or (5>=) now uses a unified constructor function named __construct(). PHP 5 or (5>=) also uses a unified __destruct() method for its destructors.
PHP 5 Constructors and Destructors
class w3Class {
function __construct($p) {
echo "Created a new instance of w3Class!";
}
function __destruct() {
echo "Destroyed this instance of w3Class";
}
}
$w3instance = new w3Class("value");
?>
Define class in php?
A class is a blueprint of an object ,variables and functions (called methods),
PHP 4 Class Style:
Create first file as ‘PHP4Class.php’
class w3answersPHP4Class {
var $my_class;
function my_W3method($param) {
echo "hey, you are in my_W3method ($param)!!\n";
echo "The value of my w3class is: ";
echo "{$this->my_class }\n";
}
}
?>
“$this is a special variable within a class that represents the instance of the object itself. It is used to access both methods and properties internally within the object”.
To create an instance of the w3answersPHP4Class, the new statement is used:
Create Second file as ‘instance.php’
require_once ("PHP4Class.php ");
$w3instance = new w3answersPHP4Class();
$w3anotherinstance = new w3answersPHP4Class();
$w3instance->my_class = 100;
$w3anotherinstance->my_class = 200;
?>
When executed, the $my_class property of the $w3instance object will be set to 100, and the $w3anotherinstance’s $my_class property will be set to 200.
The output will be
Hey, you are in my_W3method(MyParam)!!
The value of my w3class is 100
PHP 5 Class style:
Create first file as ‘PHP5Class.php’
class w3answersPHP5Class {
public $my_class;
/*we can also make private $my_class; but it will lead you to error when you tryimg to acess the varaiable
like Fatal Error: Cannot access private property w3answersPHP5Class::my_class in .... */
public function my_W3method($param) {
echo "hey, you are in my_W3method ($param)!!\n";
echo "The value of my w3class is: ";
echo "{$this->my_class }\n";
}
}
?>
Create Second file as ‘instance.php’
include_once ("PHP5Class.php ");
$w3instance = new w3answersPHP5Class();
$w3anotherinstance = new w3answersPHP5Class();
$w3instance->my_class = 100;
$w3anotherinstance->my_class = 200;
?>
How php Implements Polymorphism ?
PHP supports polymorphism in the sense of allowing instance of subclasses to be used in place of parent instances.
How PHP Supports Encapsulation?
Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from out side interference and miss use .To implement this concept , PHP 5 supports public, private, and protected variables and member functions .
PHP XML Questions
What are the Technology to Use for Parsing the XML?
There are two types of XML parsers the we can use.
1. DOM (Document Object Module).
2. SAX (Simple API for XML).
DOM
The DOM (Document Object Model) extension allows to operate on XML documents through the DOM API with PHP 5. DOM is a standard defined by the W3C for accessing XML documents.
In PHP 4, DOM xml extension is not following the standard method names.
As per the new W3C compatibility, the old domxml-based scripts won't work anymore. The API is quite different in PHP 5. But if we used the "almost W3C compatible" method names available in PHP 4.3, We only need to change the loading and saving methods, and remove the underscore in the method names. Other adjustments here and there may be necessary, but the main logic can stay the same. Though we have not used earlier so these will not be a problem for us.
The easiest way to read a well-formed XML file is to use the DOM library . The DOM library reads the entire XML document into an object and represents it as a tree of nodes,
SAX
SAX stands for Simple API for XML. It's a callback-based interface for parsing XML documents. SAX support has been available since PHP 3 and hasn't changed a lot since then. For PHP 5 the API is unchanged, The only difference is that it's not based on the expat library anymore, but on the libxml2 library.
Rather than treating an XML document as a tree-like structure, SAX treats it as a series of events such as startDocument or endElement. To accomplish this, a SAX appllication consists of a parser that sends these events to "handlers," methods or functions designated to handle them.
What is XML?
XML (eXtensible Markup Language) is a data format for structured document interchange on the Web. It is a standard defined by The World Wide Web consortium (W3C).
XML doesn't define what data is being stored or the structure of that data.
XML simply defines tags and attributes for those tags. A properly formed XML tag looks like this:
An XML book list example
XML (eXtensible Markup Language) is a data format for structured document interchange on the Web. It is a standard defined by The World Wide Web consortium (W3C).
XML doesn't define what data is being stored or the structure of that data.
XML simply defines tags and attributes for those tags. A properly formed XML tag looks like this:
An XML book list example
Ajax Frameworks-php libraries
Sajax
‘Sajax is a tool to make programming websites using the Ajax framework — also known as XMLHTTPRequest or remote scripting — as easy as possible. Sajax makes it easy to call ASP, Cold Fusion, Io, Lua, Perl, PHP, Python or Ruby functions from your webpages via JavaScript without performing a browser refresh. The toolkit does 99% of the work for you so you have no excuse to not use it.’
PHP Class Library - Xajax
‘xajax is an open source PHP class library that allows you to easily create powerful, web-based, Ajax applications using HTML, CSS, JavaScript, and PHP. Applications developed with xajax can asynchronously call server-side PHP functions and update content without reloading the page.’
CPAINT - Ajax Toolkit - what is CPAINT?
‘CPAINT (Cross-Platform Asynchronous INterface Toolkit) is a multi-language toolkit that helps web developers design and implement AJAX web applications with ease and flexibility. It was originally born out of the author’s frustration and disappointment with other open-source AJAX toolkits. It is built on the same principles of AJAX, utilizing JavaScript and the XMLHTTP object on the client-side and the appropriate scripting language on the server-side to complete the full circle of data passing from client to server and back.’
Ajax HTML using PEAR - libraries
This is a PHP and JavaScript package available through the official PEAR website.
Should I use an HTTP GET or POST for my AJAX calls?
AJAX requests should use an HTTP GET request when retrieving data where the data will not change for a given request URL. An HTTP POST should be used when state is updated on the server. This is in line with HTTP idem potency recommendations and is highly recommended for a consistent web application architecture.
What API function provides the connection between the client and server?
XMLHttpRequest
what is ajax? when ajax was born?
"AJAX is an acronym for Asynchronous JavaScript and XML. If you think it doesn't say much, we agree. Simply put, AJAX can be read "empowered JavaScript", because it essentially offers a technique for client-side JavaScript to make background server calls(such as from PHP,ASP.NET,JSP,RUby etc) and retrieve additional data as needed, updating certain portions of the page without causing full page reloads".
The XMLHttpRequest object enables JavaScript to access the server asynchronously, so that the user can continue working, while functionality is performed in the background.
The name AJAX was born in 2005, in Jesse James Garret's article at http://www.adaptivepath.com/publications/essays/archives/ 000385.php,
and gained much popularity when used by Google in many of its applications.
PHP Fresher Job Questions
How can we get second of the current time using date function?
echo $second = date("s");
?>
How can we know the number of elements in an array using php?
Ans:
There are two ways:
1) sizeof($myarray) - This function is an alias of count()
2) count($array) - This function returns the number of elements in an array.
Note
if you just pass a simple variable instead of an array, count() will return 1.
What are the different functions in sorting an array?
Ans:
asort()
arsort()
ksort()
krsort()
uksort()
sort()
natsort()
rsort()
What would the following code print to the browser? Why?
$num = 10;
function multiply(){
$num = $num * 10;
}
multiply();
echo $num;
?>
Ans: 10 because,its a call by value.$num is static here.
change the above code as
$num = 10;
function multiply(){
global $num ;
$num = $num * 10;
}
multiply();
echo $num;
?>
ANS: 100
How can you get round the stateless nature of HTTP using PHP?
ANS: using Sessions in PHP
What function can you use to open a file for reading and writing?
1. fget();
2. file_open();
3. fopen();
4. open_file();
ANS:fopen();
What function would you use to redirect the browser to a new page?
1. redir()
2. header()
3. location()
4. redirect()
ANS:header()
MySQL Interview Questions
3 comments:
Hey,Thanks you have done a great work.
I found very things, which I never seen anywhere.
Keep updating the stuff.
Thanks for the questions. Since there are so many out there I’ve built my own collection and recently uploaded them on a new site that lets you easily organize and publish them online.
http://www.collazz.com/displaypage.php/Web%20development%20interview%20questions
Great to read all stuffs under this...thanks buddy
Post a Comment