We need PHP masters to show us the best principles to follow for high-grade PHP programming.
Click here :
http://nettuts.com/articles/10-principles-of-the-php-masters/
Showing posts with label php. Show all posts
Showing posts with label php. Show all posts
Thursday, September 18, 2008
Tuesday, September 9, 2008
Introduction to CURL?
What is PHP/CURL?
CURL is the name of the project. The name is a play on 'Client for URLs',
originally with URL spelled in uppercase to make it obvious it deals with
URLs. The module for PHP that makes it possible for PHP programs to access curl-
functions from within PHP.
We can use several web protocols using one uniform interface (CURL), most notably FTP, FTPS, HTTP, HTTPS, GOPHER, TELNET, and LDAP.
In March of 2001, the Curl Corporation launched the Curl Language, their Run
Time Environment (RTE), and their Integrated Development Environment (IDE).
A very powerful feature of the Curl Language is its Just-In-Time compiling.
Curl code is sent over the Web as source code. Curl’s compiler, which ships as part
of the runtime environment, sits on the client computer and compiles the source
code directly to the client’s low-level code. The goal is to minimize the load on the
servers and to capitalize on the end-user’s machine’s processing capability, rather
than their relatively slow communication rate.
TIP: If you are using fopen and fread to read HTTP or FTP or Remote Files, and experiencing some performance
issues such as stalling, slowing down and otherwise, then it's time you learned a thing called cURL.
Performance Comparison:
10 per minute for fopen/fread for 100 HTTP files
2000 per minute for cURL for 2000 HTTP files
cURL should be used for opening HTTP and FTP files, it is EXTREMELY reliable, even when it comes to performance.
Reference sites :
1. What is cURL, libcurl, PHP/CURL?
2. PHP/CURL Examples Collection
CURL is the name of the project. The name is a play on 'Client for URLs',
originally with URL spelled in uppercase to make it obvious it deals with
URLs. The module for PHP that makes it possible for PHP programs to access curl-
functions from within PHP.
We can use several web protocols using one uniform interface (CURL), most notably FTP, FTPS, HTTP, HTTPS, GOPHER, TELNET, and LDAP.
In March of 2001, the Curl Corporation launched the Curl Language, their Run
Time Environment (RTE), and their Integrated Development Environment (IDE).
A very powerful feature of the Curl Language is its Just-In-Time compiling.
Curl code is sent over the Web as source code. Curl’s compiler, which ships as part
of the runtime environment, sits on the client computer and compiles the source
code directly to the client’s low-level code. The goal is to minimize the load on the
servers and to capitalize on the end-user’s machine’s processing capability, rather
than their relatively slow communication rate.
TIP: If you are using fopen and fread to read HTTP or FTP or Remote Files, and experiencing some performance
issues such as stalling, slowing down and otherwise, then it's time you learned a thing called cURL.
Performance Comparison:
10 per minute for fopen/fread for 100 HTTP files
2000 per minute for cURL for 2000 HTTP files
cURL should be used for opening HTTP and FTP files, it is EXTREMELY reliable, even when it comes to performance.
Reference sites :
1. What is cURL, libcurl, PHP/CURL?
2. PHP/CURL Examples Collection
Monday, September 8, 2008
Encrypt vs Decrypt using PHP
md5() - Message Digest Algorithm:
md5 -- Calculate the md5 hash of a string
Calculates the MD5 hash of str using the RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash. The hash is a 32-character hexadecimal number.
$msg = "Evergreenphp123";
$encrypted_text = md5($msg);
echo "
Plain Text : ";
echo $msg;
echo "
Encrypted Text : ";
echo $encrypted_text;
?>
Note :
Once we encrypted the string using MD5() then we can't able to decrypt, we can again use the encrption of
the given string instead of decryption using below example.
Example :
$str = 'apple';
if (md5($str) === '1f3870be274f6c49b3e31a0c6728957f') {
echo "Valid string";
} else {
echo "Invalid string";
}
?>
Something about MD5:
- MD2 is a cryptographic hash function developed by Ronald Rivest in 1989.
- MD4 is a message digest algorithm (the fourth in a series) designed by Professor Ronald Rivest of MIT in 1990.
- MD4 is also used to compute NT-hash password digests on Microsoft Windows NT, XP and Vista.
- MD4 Weaknesses were demonstrated by Den Boer and Bosselaers in a paper published in 1991.
- MD5 was designed by Ron Rivest in 1991 to replace an earlier hash function, MD4.
Applications of MD5:
1. Encrypting the users password at Registration
2. Administrator itself not able to see the users password
3. Encrypting the users Activation code at the time of Registration
URL Encrypt and Decrypt
urlencode() -- URL-encodes string
urldecode() -- Decodes URL-encoded string
String Encrypt & Decrypt
Encryption
base64_encode -- Encodes data with MIME base64
This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies.
Example :
/* Encrypt */
$str = 'This is an encoded string';
echo base64_encode($str);
/*
Output :
VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==
*/
?>
Decryption
base64_decode() -- Decodes data encoded with MIME base64
decodes encoded_data and returns the original data or FALSE on failure. The returned data may be binary.
Example :
/* Decrypt */
$str = 'VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==';
echo base64_decode($str);
/*
Output :
This is an encoded string
*/
?>
md5 -- Calculate the md5 hash of a string
Calculates the MD5 hash of str using the RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash. The hash is a 32-character hexadecimal number.
$msg = "Evergreenphp123";
$encrypted_text = md5($msg);
echo "
Plain Text : ";
echo $msg;
echo "
Encrypted Text : ";
echo $encrypted_text;
?>
Note :
Once we encrypted the string using MD5() then we can't able to decrypt, we can again use the encrption of
the given string instead of decryption using below example.
Example :
$str = 'apple';
if (md5($str) === '1f3870be274f6c49b3e31a0c6728957f') {
echo "Valid string";
} else {
echo "Invalid string";
}
?>
Something about MD5:
- MD2 is a cryptographic hash function developed by Ronald Rivest in 1989.
- MD4 is a message digest algorithm (the fourth in a series) designed by Professor Ronald Rivest of MIT in 1990.
- MD4 is also used to compute NT-hash password digests on Microsoft Windows NT, XP and Vista.
- MD4 Weaknesses were demonstrated by Den Boer and Bosselaers in a paper published in 1991.
- MD5 was designed by Ron Rivest in 1991 to replace an earlier hash function, MD4.
Applications of MD5:
1. Encrypting the users password at Registration
2. Administrator itself not able to see the users password
3. Encrypting the users Activation code at the time of Registration
URL Encrypt and Decrypt
urlencode() -- URL-encodes string
urldecode() -- Decodes URL-encoded string
String Encrypt & Decrypt
Encryption
base64_encode -- Encodes data with MIME base64
This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies.
Example :
/* Encrypt */
$str = 'This is an encoded string';
echo base64_encode($str);
/*
Output :
VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==
*/
?>
Decryption
base64_decode() -- Decodes data encoded with MIME base64
decodes encoded_data and returns the original data or FALSE on failure. The returned data may be binary.
Example :
/* Decrypt */
$str = 'VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==';
echo base64_decode($str);
/*
Output :
This is an encoded string
*/
?>
Labels:
Encrypt vs Decrypt,
php,
Sample php code
Create Dynamic XML file using PHP
/* XML File name */
$filename = "evergreenphp.xml";
/* Path for XML filename */
$path_xmls = "/www/htdocs/phpdocs/missing_man";
/* File mode to Open the file */
$handle = fopen($filename, "w");
/* Sample values for the Array */
$image_array = array("1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg");
/* Writing the Header area */
$top_header = "\n\n";
$player_list = fwrite($handle, $top_header);
/* Writing the Middle area */
for($i=0; $i < count($image_array); $i++){
$image_list = "images/".$image_array[$i]." \n";
$player_list = fwrite($handle, $image_list);
}
/* Writing the Footer area */
$bottom_footer = " \n ";
$player_list = fwrite($handle, $bottom_footer);
fclose($handle);
/*
Output :
-------
< main>
< nodeA>
< bild>images/1.jpg
< bild>images/2.jpg
< bild>images/3.jpg
< bild>images/4.jpg
< bild>images/5.jpg
< /nodeA>
< /main>
*/
?>
$filename = "evergreenphp.xml";
/* Path for XML filename */
$path_xmls = "/www/htdocs/phpdocs/missing_man";
/* File mode to Open the file */
$handle = fopen($filename, "w");
/* Sample values for the Array */
$image_array = array("1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg");
/* Writing the Header area */
$top_header = "
$player_list = fwrite($handle, $top_header);
/* Writing the Middle area */
for($i=0; $i < count($image_array); $i++){
$image_list = "
$player_list = fwrite($handle, $image_list);
}
/* Writing the Footer area */
$bottom_footer = "
$player_list = fwrite($handle, $bottom_footer);
fclose($handle);
/*
Output :
-------
< main>
< nodeA>
< bild>images/1.jpg
< bild>images/2.jpg
< bild>images/3.jpg
< bild>images/4.jpg
< bild>images/5.jpg
< /nodeA>
< /main>
*/
?>
Friday, September 5, 2008
Important Links for you?
Important Links :
- International Dialing Codes
- Listing of all the exising Domain name list
- Complete Info about a Domain
- HTML Special Characters
Sending FREE SMS
- Sending Free SMS in India
- Sending Free SMS to any mobile in India
Javascript
- Javascript Window Objects
- Entire Javascript in finger tip
- DHTML: Draw Line, Ellipse, Oval, Circle, Polyline, Polygon, Triangle with JavaScript
- Download
- JavaScript: DHTML API, Drag & Drop for Images and Layers
- Download
- JavaScript, DHTML Tooltips
- Download
- Highslide JS
- Download Highslide JS
- Calendar script using XHTML
- Download
- jCarousel - Riding carousels with jQuery
- Download Version 0.2.2
- ThickBox 3.1. Lightbox, Highslide, Litebox, SmoothGallery, FrogJS, ClearBox JS 2 or Lightview
- Download
- A PHP- and JavaScript- based File Manager
- Download Version: 2.0.0
- The Coolest DHTML / JavaScript Menu and Toolbar
Linux Commands
- Alphabetical Directory of Linux Commands
Accordion Script
Accordion Script : http://www.webresourcesdepot.com/simple-accordion-script/
Accordion V2.0 : http://www.stickmanlabs.com/accordion/
Accordion Effect : http://net.tutsplus.com/javascript-ajax/create-a-simple-intelligent-accordion-effect-using-prototype-and-scriptaculous/
10 JS Accordion Scripts : http://tutorialblog.org/10-javascript-accordion-scripts/
30+ Animated Tab Based Interface : http://dzineblog.com/2008/10/30-animated-tab-interface-and-accordion-scripts.html
Accordion Menu Scripts : http://www.dynamicdrive.com/dynamicindex17/ddaccordionmenu.htm
DHTML Menus, Javascript / CSS Menus
DHTML Menus : http://www.likno.com/
PHP
Simple Chat (DB Driven) : http://www.ebrueggeman.com/phpsimplechat/
PHP Graph : http://www.ebrueggeman.com/phpgraphlib/examples.php
ToolTips
Skinny Tip : http://www.ebrueggeman.com/skinnytip/
Image Gallery
Slideshow : http://www.phpjabbers.com/slideshow/
Photo Gallery : http://www.ebrueggeman.com/photography.php
Capcha using PHP
Webcheatsheet : http://www.webcheatsheet.com/PHP/create_captcha_protection.php
Captcha image verification : http://www.phpjabbers.com/phpexample.php?eid=19
Creating Captcha : http://www.codewalkers.com/c/a/Miscellaneous/Creating-a-CAPTCHA-with-PHP/
Secure image : http://www.phpcaptcha.org/
AJAX fancy captcha : http://www.webdesignbeach.com/beachbar/ajax-fancy-captcha-jquery-plugin
PHP Event Calender
PHP Event Calender : http://www.phpcalendarscripts.com/
Full collection of Calender Scripts : http://www.phpjabbers.com/
AJAX World
AJAX Daddy : http://www.ajaxdaddy.com/
Free JQuery Content Slider
15 Best Examples : http://visionwidget.com/inspiration/web/295-jquery-content-sliders.html
- International Dialing Codes
- Listing of all the exising Domain name list
- Complete Info about a Domain
- HTML Special Characters
Sending FREE SMS
- Sending Free SMS in India
- Sending Free SMS to any mobile in India
Javascript
- Javascript Window Objects
- Entire Javascript in finger tip
- DHTML: Draw Line, Ellipse, Oval, Circle, Polyline, Polygon, Triangle with JavaScript
- Download
- JavaScript: DHTML API, Drag & Drop for Images and Layers
- Download
- JavaScript, DHTML Tooltips
- Download
- Highslide JS
- Download Highslide JS
- Calendar script using XHTML
- Download
- jCarousel - Riding carousels with jQuery
- Download Version 0.2.2
- ThickBox 3.1. Lightbox, Highslide, Litebox, SmoothGallery, FrogJS, ClearBox JS 2 or Lightview
- Download
- A PHP- and JavaScript- based File Manager
- Download Version: 2.0.0
- The Coolest DHTML / JavaScript Menu and Toolbar
Linux Commands
- Alphabetical Directory of Linux Commands
Accordion Script
Accordion Script : http://www.webresourcesdepot.com/simple-accordion-script/
Accordion V2.0 : http://www.stickmanlabs.com/accordion/
Accordion Effect : http://net.tutsplus.com/javascript-ajax/create-a-simple-intelligent-accordion-effect-using-prototype-and-scriptaculous/
10 JS Accordion Scripts : http://tutorialblog.org/10-javascript-accordion-scripts/
30+ Animated Tab Based Interface : http://dzineblog.com/2008/10/30-animated-tab-interface-and-accordion-scripts.html
Accordion Menu Scripts : http://www.dynamicdrive.com/dynamicindex17/ddaccordionmenu.htm
DHTML Menus, Javascript / CSS Menus
DHTML Menus : http://www.likno.com/
PHP
Simple Chat (DB Driven) : http://www.ebrueggeman.com/phpsimplechat/
PHP Graph : http://www.ebrueggeman.com/phpgraphlib/examples.php
ToolTips
Skinny Tip : http://www.ebrueggeman.com/skinnytip/
Image Gallery
Slideshow : http://www.phpjabbers.com/slideshow/
Photo Gallery : http://www.ebrueggeman.com/photography.php
Capcha using PHP
Webcheatsheet : http://www.webcheatsheet.com/PHP/create_captcha_protection.php
Captcha image verification : http://www.phpjabbers.com/phpexample.php?eid=19
Creating Captcha : http://www.codewalkers.com/c/a/Miscellaneous/Creating-a-CAPTCHA-with-PHP/
Secure image : http://www.phpcaptcha.org/
AJAX fancy captcha : http://www.webdesignbeach.com/beachbar/ajax-fancy-captcha-jquery-plugin
PHP Event Calender
PHP Event Calender : http://www.phpcalendarscripts.com/
Full collection of Calender Scripts : http://www.phpjabbers.com/
AJAX World
AJAX Daddy : http://www.ajaxdaddy.com/
Free JQuery Content Slider
15 Best Examples : http://visionwidget.com/inspiration/web/295-jquery-content-sliders.html
Labels:
AJAX,
CSS,
javascript,
Linux commands,
php
Thursday, September 4, 2008
General info in PHP, MySQL
Do you know this?
- E.F. Codd released his Codd's rule in 1970 at the time of working in IBM's San Jose Research Laboratory
- Structured Query Language (SQL), developed by Donald D. Chamberlin and Raymond F. Boyce, for expressing queries at IBM's San Jose Research Laboratory in early 1970's
- Raymond F. Boyce also worked with Codd to develop the Boyce-Codd Normal Form for efficiently designing relational database tables so information was not needlessly duplicated in different tables.
- SQL was initially called as SEQUEL, was designed to manipulate and retrieve data stored in IBM's San Jose Research Laboratory original relational database product, System R.
- SQL language was standardized by the American National Standards Institute (ANSI) in 1986 and ISO in 1987
- MySQL as maintained by Sun Microsystems and it as first public release in November 1996
- MySQL supported in Windows, Mac OS X, Linux, BSD, UNIX operating systems
- MySQL maximum size of DB is Unlimited, Max table size is 2 GB (Win32 FAT32) to 16 TB (Solaris), Max row size 64 KB,
Max columns per row is 3398, Max Blob/Clob size 4 GB (longtext, longblob), Max CHAR size is 64 KB (text), Max NUMBER size 64 bits.
- MySQL is owned and sponsored by a single for-profit firm, the Swedish company MySQL AB, now a subsidiary of Sun Microsystems
- The world's most popular open source database is MySQL Database
- E.F. Codd released his Codd's rule in 1970 at the time of working in IBM's San Jose Research Laboratory
- Structured Query Language (SQL), developed by Donald D. Chamberlin and Raymond F. Boyce, for expressing queries at IBM's San Jose Research Laboratory in early 1970's
- Raymond F. Boyce also worked with Codd to develop the Boyce-Codd Normal Form for efficiently designing relational database tables so information was not needlessly duplicated in different tables.
- SQL was initially called as SEQUEL, was designed to manipulate and retrieve data stored in IBM's San Jose Research Laboratory original relational database product, System R.
- SQL language was standardized by the American National Standards Institute (ANSI) in 1986 and ISO in 1987
- MySQL as maintained by Sun Microsystems and it as first public release in November 1996
- MySQL supported in Windows, Mac OS X, Linux, BSD, UNIX operating systems
- MySQL maximum size of DB is Unlimited, Max table size is 2 GB (Win32 FAT32) to 16 TB (Solaris), Max row size 64 KB,
Max columns per row is 3398, Max Blob/Clob size 4 GB (longtext, longblob), Max CHAR size is 64 KB (text), Max NUMBER size 64 bits.
- MySQL is owned and sponsored by a single for-profit firm, the Swedish company MySQL AB, now a subsidiary of Sun Microsystems
- The world's most popular open source database is MySQL Database
Tuesday, September 2, 2008
Create PDF file using FPDF in php
- Download Script
- Tutorials
- Forum
Example :
require('fpdf.php');
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
- Demo
- Tutorials
- Forum
Example :
require('fpdf.php');
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
- Demo
Interview Questions in PHP
1. How can we repair a MySQL table?
The syntex for repairing a mysql table is:
- REPAIR TABLE tablename -> This command will repair the table specified.
- REPAIR TABLE tablename QUICK -> If QUICK is given, MySQL will do a repair of only the index tree.
- REPAIR TABLE tablename EXTENDED -> If EXTENDED is given, it will create index row by row.
2. What's diffrence between Get() and Post() Function?
- Get shows information travling on the address bar
- but Post do not shows on the address bar
- the post method is more secure than get method
3. Which is the Best plateform for PHP?
LAMP Linux apache Mysql Php Because In Linux provides basic OS and server Environment In built Mysql no need to download
4. What is meant by urlencode and urldocode?
- urlencode -- URL-encodes string
- urldecode -- Decodes URL-encoded string
5. What is the functionality of the function strstr and stristr?
- strstr -- Find first occurrence of a string
- Example :
$email = 'user@example.com';
$domain = strstr($email, '@');
echo $domain; // prints @example.com
?>
- stristr -- Case-insensitive strstr()
- Example :
$email = 'USER@EXAMPLE.com';
$domain = stristr($email, 'e');
echo $domain;
// outputs ER@EXAMPLE.com
?>
6. What is meant by nl2br()?
- nl2br -- Inserts HTML line breaks before all newlines in a string
- Example :
echo nl2br("foo isn't\n bar");
/*output :
foo isn't
bar
*/
?>
7. How can we submit a form without a submit button?
- we can use the input type as 'image'
- i.e. < input type="image" src="submit.gif">
8. How can we get the properties (size, type, width, height) of an image using PHP
image functions?
- getimagesize -- Get the size of an image
- Returns an array with 4 elements.
- Index 0 contains the width of the image in pixels.
- Index 1 contains the height.
- Index 2 is a flag indicating the type of the image: 1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF, 5 = PSD, 6 = BMP, 7 = TIFF(intel byte order), 8 = TIFF(motorola byte order), 9 = JPC, 10 = JP2, 11 = JPX, 12 = JB2, 13 = SWC, 14 = IFF, 15 = WBMP, 16 = XBM. These values correspond to the IMAGETYPE constants that were added in PHP 4.3.
- Index 3 is a text string with the correct height="yyy" width="xxx" string that can be used directly in an IMG tag.
- Example:
list($width, $height, $type, $attr) = getimagesize("reset.jpg");
echo "
Width : ".$width;
echo "
Height : ".$height;
echo "
Type : ".$type;
echo "
Attribute : ".$attr;
/* Output :
Width : 53
Height : 22
Type : 2
Attribute : width="53" height="22"
*/
?>
9. How I will check that user is logged in or not?
- we can use session for this, at the time of login process we must store the user information into the session, and at the time of
logout we can destroy the session. by this way is the session value is set i.e. not equal to blank then we can easily identify
that user is logged in or not.
- Example:
if (isset($_SESSION['username']) && $_SESSION['username'] != ""){
echo "User already logged in";
} else {
echo "User not logged in";
}
?>
10. How I can get IP address of the usr?
- $_SERVER['REMOTE_ADDR']
11. Explain about the installation of PHP on UNIX systems?
PHP can be installed on UNIX in many different ways there are pre defined packages available which can ease the process. Initially it can be controlled by the command line options. Help can be obtained from./configure help command. After installing PHP modules or executables can be configures and make command should help you in the process.
12. How to enable parsing?
Parsing is an important concept if you want to run your code appropriately and timely. PHP parses all the code present between the opening and closing tags, it ignores everything present out of the closing and opening tags. This tags allow PHP to be embedded between many documents.
13. Explain about null?
Null represents a variable with no value inside. There doesn’t exist any value for type Null. Null is defined to be null if and only if it is assigned a constant null, there is no value set, it is set to be unset(). This is the case insensitive keyword. There are also two functions they are is_null and unset().
14. Explain about PHP looping?
Looping statements are used in PHP to execute the code for a developer defined number of times.
PHP has these following looping statements they are
- while() loop,
- do while() loop,
- for() loop and
- for each() loop .
Foreach is used to loop a block of code in each element in an array.
15. Explain about the advantages of using PHP?
There are many advantages of PHP they are
1) Easy and fast creation of dynamic web pages and a developer can also embed these dynamic functions into HTML.
2) A huge community resource which has a ton of information before you.
3) Connectivity ability lets you to connect to different interfaces and predefined libraries.
4) Execution is very fast because it uses less system resources, etc.
16. How can we destroy the cookie?
- clear all the cookie variables, by using unset() function i.e. unset($_COOKIE).
- destroy the cookie value by it name, if the cookie variable name is 'usename' i.e. $_COOKIE['username'].
17. What is the difference between ereg_replace() and eregi_replace()?
- ereg_replace() -- Replace regular expression
- eregi_replace() -- Replace regular expression case insensitive
The syntex for repairing a mysql table is:
- REPAIR TABLE tablename -> This command will repair the table specified.
- REPAIR TABLE tablename QUICK -> If QUICK is given, MySQL will do a repair of only the index tree.
- REPAIR TABLE tablename EXTENDED -> If EXTENDED is given, it will create index row by row.
2. What's diffrence between Get() and Post() Function?
- Get shows information travling on the address bar
- but Post do not shows on the address bar
- the post method is more secure than get method
3. Which is the Best plateform for PHP?
LAMP Linux apache Mysql Php Because In Linux provides basic OS and server Environment In built Mysql no need to download
4. What is meant by urlencode and urldocode?
- urlencode -- URL-encodes string
- urldecode -- Decodes URL-encoded string
5. What is the functionality of the function strstr and stristr?
- strstr -- Find first occurrence of a string
- Example :
$email = 'user@example.com';
$domain = strstr($email, '@');
echo $domain; // prints @example.com
?>
- stristr -- Case-insensitive strstr()
- Example :
$email = 'USER@EXAMPLE.com';
$domain = stristr($email, 'e');
echo $domain;
// outputs ER@EXAMPLE.com
?>
6. What is meant by nl2br()?
- nl2br -- Inserts HTML line breaks before all newlines in a string
- Example :
echo nl2br("foo isn't\n bar");
/*output :
foo isn't
bar
*/
?>
7. How can we submit a form without a submit button?
- we can use the input type as 'image'
- i.e. < input type="image" src="submit.gif">
8. How can we get the properties (size, type, width, height) of an image using PHP
image functions?
- getimagesize -- Get the size of an image
- Returns an array with 4 elements.
- Index 0 contains the width of the image in pixels.
- Index 1 contains the height.
- Index 2 is a flag indicating the type of the image: 1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF, 5 = PSD, 6 = BMP, 7 = TIFF(intel byte order), 8 = TIFF(motorola byte order), 9 = JPC, 10 = JP2, 11 = JPX, 12 = JB2, 13 = SWC, 14 = IFF, 15 = WBMP, 16 = XBM. These values correspond to the IMAGETYPE constants that were added in PHP 4.3.
- Index 3 is a text string with the correct height="yyy" width="xxx" string that can be used directly in an IMG tag.
- Example:
list($width, $height, $type, $attr) = getimagesize("reset.jpg");
echo "
Width : ".$width;
echo "
Height : ".$height;
echo "
Type : ".$type;
echo "
Attribute : ".$attr;
/* Output :
Width : 53
Height : 22
Type : 2
Attribute : width="53" height="22"
*/
?>
9. How I will check that user is logged in or not?
- we can use session for this, at the time of login process we must store the user information into the session, and at the time of
logout we can destroy the session. by this way is the session value is set i.e. not equal to blank then we can easily identify
that user is logged in or not.
- Example:
if (isset($_SESSION['username']) && $_SESSION['username'] != ""){
echo "User already logged in";
} else {
echo "User not logged in";
}
?>
10. How I can get IP address of the usr?
- $_SERVER['REMOTE_ADDR']
11. Explain about the installation of PHP on UNIX systems?
PHP can be installed on UNIX in many different ways there are pre defined packages available which can ease the process. Initially it can be controlled by the command line options. Help can be obtained from./configure help command. After installing PHP modules or executables can be configures and make command should help you in the process.
12. How to enable parsing?
Parsing is an important concept if you want to run your code appropriately and timely. PHP parses all the code present between the opening and closing tags, it ignores everything present out of the closing and opening tags. This tags allow PHP to be embedded between many documents.
13. Explain about null?
Null represents a variable with no value inside. There doesn’t exist any value for type Null. Null is defined to be null if and only if it is assigned a constant null, there is no value set, it is set to be unset(). This is the case insensitive keyword. There are also two functions they are is_null and unset().
14. Explain about PHP looping?
Looping statements are used in PHP to execute the code for a developer defined number of times.
PHP has these following looping statements they are
- while() loop,
- do while() loop,
- for() loop and
- for each() loop .
Foreach is used to loop a block of code in each element in an array.
15. Explain about the advantages of using PHP?
There are many advantages of PHP they are
1) Easy and fast creation of dynamic web pages and a developer can also embed these dynamic functions into HTML.
2) A huge community resource which has a ton of information before you.
3) Connectivity ability lets you to connect to different interfaces and predefined libraries.
4) Execution is very fast because it uses less system resources, etc.
16. How can we destroy the cookie?
- clear all the cookie variables, by using unset() function i.e. unset($_COOKIE).
- destroy the cookie value by it name, if the cookie variable name is 'usename' i.e. $_COOKIE['username'].
17. What is the difference between ereg_replace() and eregi_replace()?
- ereg_replace() -- Replace regular expression
- eregi_replace() -- Replace regular expression case insensitive
Labels:
Interview questions with answers,
php
Monday, September 1, 2008
Iterative statements (loops concepts) in php
Explain about PHP looping?
Looping statements are used in PHP to execute the code for a developer defined number of times.
PHP has these following looping statements they are
- while() loop,
- do while() loop,
- for() loop and
- foreach() loop
/* Example for while() loop */
echo "Example using while() loop to display 1-4 numbers
";
$i=1;
while($i<5){
echo $i." ";
$i++;
}
echo "
Example using do-while() loop to display 1-4 numbers
";
/* Example for do-while() loop */
$i=1;
do {
echo $i." ";
$i++;
}while($i<5);
echo "
Example using for() loop to display 1-4 numbers
";
/* Example for for() loop */
for($i=1;$i<5;$i++){
echo $i." ";
}
echo "
Example using foreach() loop to display 1-4 numbers
";
/* Example for for() loop */
$a = array(1,2,3,4);
foreach($a as $i){
echo $i." ";
}
?>
Looping statements are used in PHP to execute the code for a developer defined number of times.
PHP has these following looping statements they are
- while() loop,
- do while() loop,
- for() loop and
- foreach() loop
/* Example for while() loop */
echo "Example using while() loop to display 1-4 numbers
";
$i=1;
while($i<5){
echo $i." ";
$i++;
}
echo "
Example using do-while() loop to display 1-4 numbers
";
/* Example for do-while() loop */
$i=1;
do {
echo $i." ";
$i++;
}while($i<5);
echo "
Example using for() loop to display 1-4 numbers
";
/* Example for for() loop */
for($i=1;$i<5;$i++){
echo $i." ";
}
echo "
Example using foreach() loop to display 1-4 numbers
";
/* Example for for() loop */
$a = array(1,2,3,4);
foreach($a as $i){
echo $i." ";
}
?>
Difference between sizeof() and count() in php
- count() -- Count elements in a variable
- syntax for count() [int count ( mixed var [, int mode])]
- If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array. The default value for mode is 0.
- sizeof() function is an alias of count() function
- Example below:
/* Simple Example */
$a = array(1,2,3,4);
echo "
Example #1";
echo "
Count of A array is :".count($a);
echo "
Size of A array is :".sizeof($a);
echo "
Example #2";
$food = array('fruits' => array('orange', 'banana', 'apple'),
'veggie' => array('carrot', 'collard', 'pea'));
/* recursive count */
/* count($food, COUNT_RECURSIVE) equals to count($food, 1) */
echo "
Count of A array is :".count($food, COUNT_RECURSIVE);
echo "
Size of A array is :".sizeof($food, 1);
/* normal count */
/* count($food, COUNT_RECURSIVE) equals to count($food, 1) */
echo "
Example #3";
echo "
Count of A array is :".count($food, 0);
echo "
Size of A array is :".sizeof($food);
echo "
Conclusion :
The sizeof() function is an alias for count().
";
?>
- syntax for count() [int count ( mixed var [, int mode])]
- If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array. The default value for mode is 0.
- sizeof() function is an alias of count() function
- Example below:
/* Simple Example */
$a = array(1,2,3,4);
echo "
Example #1";
echo "
Count of A array is :".count($a);
echo "
Size of A array is :".sizeof($a);
echo "
Example #2";
$food = array('fruits' => array('orange', 'banana', 'apple'),
'veggie' => array('carrot', 'collard', 'pea'));
/* recursive count */
/* count($food, COUNT_RECURSIVE) equals to count($food, 1) */
echo "
Count of A array is :".count($food, COUNT_RECURSIVE);
echo "
Size of A array is :".sizeof($food, 1);
/* normal count */
/* count($food, COUNT_RECURSIVE) equals to count($food, 1) */
echo "
Example #3";
echo "
Count of A array is :".count($food, 0);
echo "
Size of A array is :".sizeof($food);
echo "
Conclusion :
The sizeof() function is an alias for count().
";
?>
Saturday, August 30, 2008
Interview Questions in PHP and General informations
1. How old PHP language is?
- PHP began in 1994, so 14 years old.
2. What are different names of PHP?
- PHP originally stood for Personal Home Page.
- At the formation of PHP 3, name changed into Hypertext Preprocessor by Zeev Suraski and Andi Gutmans, two Israeli developers
3. What is latest name of PHP?
- Hypertext Preprocessor
4. Which databases you can use with PHP?
- * Abstraction Layers
o DBA — Database (dbm-style) Abstraction Layer
o dbx
o ODBC — ODBC (Unified)
o PDO — PHP Data Objects
* Vendor Specific Database Extensions
o dBase
o DB++
o FrontBase
o filePro
o Firebird/InterBase
o Informix
o IBM DB2 — IBM DB2, Cloudscape and Apache Derby
o Ingres II
o MaxDB
o mSQL
o Mssql — Microsoft SQL Server
o MySQL
o Mysqli — MySQL Improved Extension
o OCI8 — Oracle OCI8
o Ovrimos SQL
o Paradox — Paradox File Access
o PostgreSQL
o SQLite
o SQLite3
o Sybase
5. Why PHP is called a scripting language?
A scripting language, script language or extension language, is a programming language that controls a software application. "Scripts" are often treated as distinct from "programs", which execute independently from any other application. At the same time they are distinct from the core code of the application, which is usually written in a different language, and by being accessible to the end user they enable the behavior of the application to be adapted to the user's needs. Scripts are often, but not always, interpreted from the source code or "semi-compiled" to bytecode which is interpreted, unlike the applications they are associated with, which are traditionally compiled to native machine code for the system on which they run. Scripting languages are nearly always embedded in the application with which they are associated.
6. Is PHP object oriented language?
- Yes, PHP 5 and above is an OOPs
7. What is different between PHP & ASP.NET?
- PHP is Open Source Software
- ASP.NET is Payment Software
- PHP is closely with MySQL Database because both are FREE softwares, MySQL is an Open Source SQL database
- ASP.NET is closely with MSSQL (Microsoft Sql Server) but it also payment
- PHP is very easy to learn and implement, style like C language
- ASP.NET using like ASP, also we need basic knowledge about .NET framework
- PHP having no Web services, to access the 3rd party controls
- ASP.NET we can use Web Services easily
- PHP uses both IIS server and Apache Server
- ASP.NET uses IIS Server
- ASP.NET being object oriented is more "organized" and maintainable than scripted PHP. Besides being fully compiled, ASP.NET platform offers loads of pure OO features like inheritance, polymorphism, overloading etc. Newer versions of PHP support OOP but its very limited compared to ASP.NET.
- Example program : #1
< %
' ASP Example
myFormVal = request.form("myInputField")
myQSval = request.querystring("myQSitem")
myVal = request.item("myFormOrQSitem")
%>
// PHP 4.1+ Example
$myFormVal = $_POST['myInputField'];
$myQSval = $_REQUEST['myQSitem'];
// PHP 3+ Example
$myFormVal = $HTTP_POST_VARS['myInputField'];
// If register_globals = on
$myVal = $myFormOrQSitem;
?>
- Example program : #2
< %
' VBScript Example
Option Explicit
myVar = 1
myOtherVar = myVar
myVar = 2
' myResult will be 3
myResult = myVar + myOtherVar
%>
// PHP Example
$myVar = 1;
'Use the ampersand to make a reference
$myOtherVar = &$myVar;
$myVar = 2;
// $myResult will be 4
$myResult = $myVar + $myOtherVar;
?>
8. What is the difference between include & require?
- The require() function is identical to include(), except that it handles errors differently.
- The include() function generates a warning (but the script will continue execution) while the require() function generates a fatal error (and the script execution will stop after the error).
- Example for include() function
/* Example for include */
include("wrongFile.php");
echo "Hello World!";
/* If the file 'wrongFile.php' is not available then Warning error and below will happen */
?>
Warning: include(wrongFile.php) [function.include]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5
Warning: include() [function.include]:
Failed opening 'wrongFile.php' for inclusion
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5
Hello World!
- Example for require() function
/* Example for require */
include("wrongFile.php");
echo "Hello World!";
/* If the file 'wrongFile.php' is not available then Fatal error and below will happen */
?>
Warning: require(wrongFile.php) [function.require]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5
Fatal error: require() [function.require]:
Failed opening required 'wrongFile.php'
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5
9. What is the difference between include_once & require_once?
- both are similar like above but with one major difference
- both the functions checks the given file is already loaded or not, if the file is already loaded then the given file is not
loaded again or else it will load the file.
10. What is error control operator?
- Reporting Errors
To report errors from an internal function, you should call the php3_error() function. This takes at least two parameters -- the first is the level of the error, the second is the format string for the error message (as in a standard printf() call), and any following arguments are the parameters for the format string. The error levels are:
- E_NOTICE
Notices are not printed by default, and indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script. For example, trying to access the value of a variable which has not been set, or calling stat() on a file that doesn't exist.
- E_WARNING
Warnings are printed by default, but do not interrupt script execution. These indicate a problem that should have been trapped by the script before the call was made. For example, calling ereg() with an invalid regular expression.
- E_ERROR
Errors are also printed by default, and execution of the script is halted after the function returns. These indicate errors that can not be recovered from, such as a memory allocation problem.
- E_PARSE
Parse errors should only be generated by the parser. The code is listed here only for the sake of completeness.
- E_CORE_ERROR
This is like an E_ERROR, except it is generated by the core of PHP. Functions should not generate this type of error.
- E_CORE_WARNING
This is like an E_WARNING, except it is generated by the core of PHP. Functions should not generate this type of error.
- E_COMPILE_ERROR
This is like an E_ERROR, except it is generated by the Zend Scripting Engine. Functions should not generate this type of error.
- E_COMPILE_WARNING
This is like an E_WARNING, except it is generated by the Zend Scripting Engine. Functions should not generate this type of error.
- E_USER_ERROR
This is like an E_ERROR, except it is generated in PHP code by using the PHP function trigger_error(). Functions should not generate this type of error.
- E_USER_WARNING
This is like an E_WARNING, except it is generated by using the PHP function trigger_error(). Functions should not generate this type of error.
- E_USER_NOTICE
This is like an E_NOTICE, except it is generated by using the PHP function trigger_error(). Functions should not generate this type of error.
- E_ALL
All of the above. Using this error_reporting level will show all error types.
11. What will these functions do? (explode(), file(), mysql_insert_id(), time() )
- Example for explode()
- explode() -- Split a string by string
/* Example for explode() */
$pizza = "piece1-piece2-piece3-piece4-piece5-piece6";
$pieces = explode("-", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
echo $pieces[4]; // piece5
?>
- Example for file()
- file() -- Reads entire file into an array
// Get a file into an array. In this example we'll go through HTTP to get
// the HTML source of a URL.
$lines = file('http://www.example.com/');
// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) {
echo "Line #{$line_num} : " . htmlspecialchars($line) . "
\n";
}
?>
- Example for mysql_insert_id()
- mysql_insert_id() -- Get the ID generated from the previous INSERT operation
- $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
12. Which function gives us absolute path of a file on the server?
- getcwd() -- gets the current working directory
-
/* current directory *
echo getcwd() . "\n"; /* /home/didou */
?>
13. Can we do automatic FTP using PHP? How?
- Yes, lots of FTP function available in PHP
- Ex: ftp_login(), ftp_mkdir (), ftp_ssl_connect() etc.,
-
// set up basic ssl connection
$conn_id = ftp_ssl_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
echo ftp_pwd($conn_id); // /
// close the ssl connection
ftp_close($conn_id);
?>
14. Can we do Flash programming using PHP? How?
- Yes, lots of Flash programming functions available in PHP
- Ex: swf_actiongeturl(), swf_endbutton() etc.,
15. Can we create dynamic PDF document using PHP? How?
- Yes, lots of functions available in PHP
- The PDF functions in PHP can create PDF files using the PDFlib library created by Thomas Merz.
- Example :
$pdf = pdf_new();
pdf_open_file($pdf, "test.pdf");
pdf_set_info($pdf, "Author", "Uwe Steinmann");
pdf_set_info($pdf, "Title", "Test for PHP wrapper of PDFlib 2.0");
pdf_set_info($pdf, "Creator", "See Author");
pdf_set_info($pdf, "Subject", "Testing");
pdf_begin_page($pdf, 595, 842);
pdf_add_outline($pdf, "Page 1");
$font = pdf_findfont($pdf, "Times New Roman", "winansi", 1);
pdf_setfont($pdf, $font, 10);
pdf_set_value($pdf, "textrendering", 1);
pdf_show_xy($pdf, "Times Roman outlined", 50, 750);
pdf_moveto($pdf, 50, 740);
pdf_lineto($pdf, 330, 740);
pdf_stroke($pdf);
pdf_end_page($pdf);
pdf_close($pdf);
pdf_delete($pdf);
echo "Finished";
?>
16. In which language PHP code is written?
- PHP's Common Gateway Interface binaries written in the C programming language
- PHP began in 1994, so 14 years old.
2. What are different names of PHP?
- PHP originally stood for Personal Home Page.
- At the formation of PHP 3, name changed into Hypertext Preprocessor by Zeev Suraski and Andi Gutmans, two Israeli developers
3. What is latest name of PHP?
- Hypertext Preprocessor
4. Which databases you can use with PHP?
- * Abstraction Layers
o DBA — Database (dbm-style) Abstraction Layer
o dbx
o ODBC — ODBC (Unified)
o PDO — PHP Data Objects
* Vendor Specific Database Extensions
o dBase
o DB++
o FrontBase
o filePro
o Firebird/InterBase
o Informix
o IBM DB2 — IBM DB2, Cloudscape and Apache Derby
o Ingres II
o MaxDB
o mSQL
o Mssql — Microsoft SQL Server
o MySQL
o Mysqli — MySQL Improved Extension
o OCI8 — Oracle OCI8
o Ovrimos SQL
o Paradox — Paradox File Access
o PostgreSQL
o SQLite
o SQLite3
o Sybase
5. Why PHP is called a scripting language?
A scripting language, script language or extension language, is a programming language that controls a software application. "Scripts" are often treated as distinct from "programs", which execute independently from any other application. At the same time they are distinct from the core code of the application, which is usually written in a different language, and by being accessible to the end user they enable the behavior of the application to be adapted to the user's needs. Scripts are often, but not always, interpreted from the source code or "semi-compiled" to bytecode which is interpreted, unlike the applications they are associated with, which are traditionally compiled to native machine code for the system on which they run. Scripting languages are nearly always embedded in the application with which they are associated.
6. Is PHP object oriented language?
- Yes, PHP 5 and above is an OOPs
7. What is different between PHP & ASP.NET?
- PHP is Open Source Software
- ASP.NET is Payment Software
- PHP is closely with MySQL Database because both are FREE softwares, MySQL is an Open Source SQL database
- ASP.NET is closely with MSSQL (Microsoft Sql Server) but it also payment
- PHP is very easy to learn and implement, style like C language
- ASP.NET using like ASP, also we need basic knowledge about .NET framework
- PHP having no Web services, to access the 3rd party controls
- ASP.NET we can use Web Services easily
- PHP uses both IIS server and Apache Server
- ASP.NET uses IIS Server
- ASP.NET being object oriented is more "organized" and maintainable than scripted PHP. Besides being fully compiled, ASP.NET platform offers loads of pure OO features like inheritance, polymorphism, overloading etc. Newer versions of PHP support OOP but its very limited compared to ASP.NET.
- Example program : #1
< %
' ASP Example
myFormVal = request.form("myInputField")
myQSval = request.querystring("myQSitem")
myVal = request.item("myFormOrQSitem")
%>
// PHP 4.1+ Example
$myFormVal = $_POST['myInputField'];
$myQSval = $_REQUEST['myQSitem'];
// PHP 3+ Example
$myFormVal = $HTTP_POST_VARS['myInputField'];
// If register_globals = on
$myVal = $myFormOrQSitem;
?>
- Example program : #2
< %
' VBScript Example
Option Explicit
myVar = 1
myOtherVar = myVar
myVar = 2
' myResult will be 3
myResult = myVar + myOtherVar
%>
// PHP Example
$myVar = 1;
'Use the ampersand to make a reference
$myOtherVar = &$myVar;
$myVar = 2;
// $myResult will be 4
$myResult = $myVar + $myOtherVar;
?>
8. What is the difference between include & require?
- The require() function is identical to include(), except that it handles errors differently.
- The include() function generates a warning (but the script will continue execution) while the require() function generates a fatal error (and the script execution will stop after the error).
- Example for include() function
/* Example for include */
include("wrongFile.php");
echo "Hello World!";
/* If the file 'wrongFile.php' is not available then Warning error and below will happen */
?>
Warning: include(wrongFile.php) [function.include]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5
Warning: include() [function.include]:
Failed opening 'wrongFile.php' for inclusion
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5
Hello World!
- Example for require() function
/* Example for require */
include("wrongFile.php");
echo "Hello World!";
/* If the file 'wrongFile.php' is not available then Fatal error and below will happen */
?>
Warning: require(wrongFile.php) [function.require]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5
Fatal error: require() [function.require]:
Failed opening required 'wrongFile.php'
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5
9. What is the difference between include_once & require_once?
- both are similar like above but with one major difference
- both the functions checks the given file is already loaded or not, if the file is already loaded then the given file is not
loaded again or else it will load the file.
10. What is error control operator?
- Reporting Errors
To report errors from an internal function, you should call the php3_error() function. This takes at least two parameters -- the first is the level of the error, the second is the format string for the error message (as in a standard printf() call), and any following arguments are the parameters for the format string. The error levels are:
- E_NOTICE
Notices are not printed by default, and indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script. For example, trying to access the value of a variable which has not been set, or calling stat() on a file that doesn't exist.
- E_WARNING
Warnings are printed by default, but do not interrupt script execution. These indicate a problem that should have been trapped by the script before the call was made. For example, calling ereg() with an invalid regular expression.
- E_ERROR
Errors are also printed by default, and execution of the script is halted after the function returns. These indicate errors that can not be recovered from, such as a memory allocation problem.
- E_PARSE
Parse errors should only be generated by the parser. The code is listed here only for the sake of completeness.
- E_CORE_ERROR
This is like an E_ERROR, except it is generated by the core of PHP. Functions should not generate this type of error.
- E_CORE_WARNING
This is like an E_WARNING, except it is generated by the core of PHP. Functions should not generate this type of error.
- E_COMPILE_ERROR
This is like an E_ERROR, except it is generated by the Zend Scripting Engine. Functions should not generate this type of error.
- E_COMPILE_WARNING
This is like an E_WARNING, except it is generated by the Zend Scripting Engine. Functions should not generate this type of error.
- E_USER_ERROR
This is like an E_ERROR, except it is generated in PHP code by using the PHP function trigger_error(). Functions should not generate this type of error.
- E_USER_WARNING
This is like an E_WARNING, except it is generated by using the PHP function trigger_error(). Functions should not generate this type of error.
- E_USER_NOTICE
This is like an E_NOTICE, except it is generated by using the PHP function trigger_error(). Functions should not generate this type of error.
- E_ALL
All of the above. Using this error_reporting level will show all error types.
11. What will these functions do? (explode(), file(), mysql_insert_id(), time() )
- Example for explode()
- explode() -- Split a string by string
/* Example for explode() */
$pizza = "piece1-piece2-piece3-piece4-piece5-piece6";
$pieces = explode("-", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
echo $pieces[4]; // piece5
?>
- Example for file()
- file() -- Reads entire file into an array
// Get a file into an array. In this example we'll go through HTTP to get
// the HTML source of a URL.
$lines = file('http://www.example.com/');
// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) {
echo "Line #{$line_num} : " . htmlspecialchars($line) . "
\n";
}
?>
- Example for mysql_insert_id()
- mysql_insert_id() -- Get the ID generated from the previous INSERT operation
- $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
12. Which function gives us absolute path of a file on the server?
- getcwd() -- gets the current working directory
-
/* current directory *
echo getcwd() . "\n"; /* /home/didou */
?>
13. Can we do automatic FTP using PHP? How?
- Yes, lots of FTP function available in PHP
- Ex: ftp_login(), ftp_mkdir (), ftp_ssl_connect() etc.,
-
// set up basic ssl connection
$conn_id = ftp_ssl_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
echo ftp_pwd($conn_id); // /
// close the ssl connection
ftp_close($conn_id);
?>
14. Can we do Flash programming using PHP? How?
- Yes, lots of Flash programming functions available in PHP
- Ex: swf_actiongeturl(), swf_endbutton() etc.,
15. Can we create dynamic PDF document using PHP? How?
- Yes, lots of functions available in PHP
- The PDF functions in PHP can create PDF files using the PDFlib library created by Thomas Merz.
- Example :
$pdf = pdf_new();
pdf_open_file($pdf, "test.pdf");
pdf_set_info($pdf, "Author", "Uwe Steinmann");
pdf_set_info($pdf, "Title", "Test for PHP wrapper of PDFlib 2.0");
pdf_set_info($pdf, "Creator", "See Author");
pdf_set_info($pdf, "Subject", "Testing");
pdf_begin_page($pdf, 595, 842);
pdf_add_outline($pdf, "Page 1");
$font = pdf_findfont($pdf, "Times New Roman", "winansi", 1);
pdf_setfont($pdf, $font, 10);
pdf_set_value($pdf, "textrendering", 1);
pdf_show_xy($pdf, "Times Roman outlined", 50, 750);
pdf_moveto($pdf, 50, 740);
pdf_lineto($pdf, 330, 740);
pdf_stroke($pdf);
pdf_end_page($pdf);
pdf_close($pdf);
pdf_delete($pdf);
echo "Finished";
?>
16. In which language PHP code is written?
- PHP's Common Gateway Interface binaries written in the C programming language
Friday, August 29, 2008
Thursday, August 28, 2008
Details about PHP Cron Job with examples
Introduction to Cron
* There are lots of things to automate in Unix
* Many of them are done routinely
* You (the administrator) have better things to do
* Cron (and some appropriate shell scripts) can do them for you
Cron
This file is an introduction to cron, it covers the basics of what cron does,
and how to use it.
What is Cron?
Cron is the name of program that enables unix users to execute commands or
scripts (groups of commands) automatically at a specified time/date. It is
normally used for sys admin commands, like makewhatis, which builds a
search database for the man -k command, or for running a backup script,
but can be used for anything. A common use for it today is connecting to
the internet and downloading your email.
This file will look at Vixie Cron, a version of cron authored by Paul Vixie.
How to start Cron
Cron is a daemon, which means that it only needs to be started once, and will
lay dormant until it is required. A Web server is a daemon, it stays dormant
until it gets asked for a web page. The cron daemon, or crond, stays dormant
until a time specified in one of the config files, or crontabs.
PHP Cron jobs with Examples
The format of an cron tab entry is:
* * * * * command_to_be_executed
| | | | |
| | | | |_ day of the week (0-6)
| | | |__ month(1-12)
| | |____ day of the month(1-31)
| |______ hour(0-23)
|________ minute(0-59)
Now, take an interest in some special characters (metacharacters) :
- *, if one of the m h dom mon dow fields owns the * character, then it indicates evey minute or evey hour or every day or every day of the month or every month or every day of the week, it depends on which field is placed *.
- / permits to specify a repetition.
- - permits to define a range.
- , permits to specify several values.
Some samples:
*/5 * * * * command to execute a command every 5 minutes.
0 22 * * 1-5 command to execute a command every day, monday to friday, at 10 p.m.
17 19 1,15 * * command means the first and the fifteenth day of the month at 19h17 (7.17 p.m.)
23 0-16/2 * * * command means every 2 hours at the twenty-third minute, between midnight and 16h00 (4.00 p.m.)
Example 1 :
If you want a cron job to run on every day 10 a.m. then the cron command will be like,
0 10 * * * wget -O /dev/null http://manoilayans.com/expired_users.php
here the value 10 is given on the 2nd position, because 2nd position is for hour in the command syntax.
Example 2 :
If you want a cron job to run on every month first day (ex: 01-10-2008) at 5 a.m. then the cron command will be like,
0 5 1 * * wget -O /dev/null http://manoilayans.com/expired_users.php
here the value 5 is given on the 2nd position, because 2nd position is for hour (5 a.m.) and the value
1 is given in the position 3rd position, because 3rd position is for 'day of the month' in the command syntax.
Example 3 :
The following command should run by cron at 1 am on everyday.
0 1 * * * wget -O /dev/null http://manoilayans.com/expired_users.php
Alternative way to run Cron job:
Example 1:
If you want a cron job to run on every day 10 a.m. then the cron command will be like,
[root@mylinux ~]#crontab -e 0 10 * * * /usr/bin/php -q /www/htdocs/phpdocs/expired_users.php
here,
'/usr/local/bin/php' - where php is installed in our server
'-q' - run the file
'/www/htdocs/phpdocs/expired_users.php' - path for the executable file
Example 2:
If you want a cron job to run on every month first day (ex: 01-10-2008) at 5 a.m. then the cron command will be like,
[root@mylinux ~]#crontab -e 0 5 1 * * /usr/bin/php -q /www/htdocs/phpdocs/expired_users.php
Example 3:
The following command should run by cron at 1 am on everyday.
[root@mylinux ~]#crontab -e 0 1 * * * /usr/bin/php -q /www/htdocs/phpdocs/expired_users.php
Example 4:
The following command should run by cron at every 5 minutes.
[root@mylinux ~]#crontab -e */5 * * * * /usr/bin/php -q /www/htdocs/phpdocs/expired_users.php
Conclusion:
* There are lots of things to automate in Unix
* Many of them are done routinely
* You (the administrator) have better things to do
* Cron (and some appropriate shell scripts) can do them for you
* There are lots of things to automate in Unix
* Many of them are done routinely
* You (the administrator) have better things to do
* Cron (and some appropriate shell scripts) can do them for you
Cron
This file is an introduction to cron, it covers the basics of what cron does,
and how to use it.
What is Cron?
Cron is the name of program that enables unix users to execute commands or
scripts (groups of commands) automatically at a specified time/date. It is
normally used for sys admin commands, like makewhatis, which builds a
search database for the man -k command, or for running a backup script,
but can be used for anything. A common use for it today is connecting to
the internet and downloading your email.
This file will look at Vixie Cron, a version of cron authored by Paul Vixie.
How to start Cron
Cron is a daemon, which means that it only needs to be started once, and will
lay dormant until it is required. A Web server is a daemon, it stays dormant
until it gets asked for a web page. The cron daemon, or crond, stays dormant
until a time specified in one of the config files, or crontabs.
PHP Cron jobs with Examples
The format of an cron tab entry is:
* * * * * command_to_be_executed
| | | | |
| | | | |_ day of the week (0-6)
| | | |__ month(1-12)
| | |____ day of the month(1-31)
| |______ hour(0-23)
|________ minute(0-59)
Now, take an interest in some special characters (metacharacters) :
- *, if one of the m h dom mon dow fields owns the * character, then it indicates evey minute or evey hour or every day or every day of the month or every month or every day of the week, it depends on which field is placed *.
- / permits to specify a repetition.
- - permits to define a range.
- , permits to specify several values.
Some samples:
*/5 * * * * command to execute a command every 5 minutes.
0 22 * * 1-5 command to execute a command every day, monday to friday, at 10 p.m.
17 19 1,15 * * command means the first and the fifteenth day of the month at 19h17 (7.17 p.m.)
23 0-16/2 * * * command means every 2 hours at the twenty-third minute, between midnight and 16h00 (4.00 p.m.)
Example 1 :
If you want a cron job to run on every day 10 a.m. then the cron command will be like,
0 10 * * * wget -O /dev/null http://manoilayans.com/expired_users.php
here the value 10 is given on the 2nd position, because 2nd position is for hour in the command syntax.
Example 2 :
If you want a cron job to run on every month first day (ex: 01-10-2008) at 5 a.m. then the cron command will be like,
0 5 1 * * wget -O /dev/null http://manoilayans.com/expired_users.php
here the value 5 is given on the 2nd position, because 2nd position is for hour (5 a.m.) and the value
1 is given in the position 3rd position, because 3rd position is for 'day of the month' in the command syntax.
Example 3 :
The following command should run by cron at 1 am on everyday.
0 1 * * * wget -O /dev/null http://manoilayans.com/expired_users.php
Alternative way to run Cron job:
Example 1:
If you want a cron job to run on every day 10 a.m. then the cron command will be like,
[root@mylinux ~]#crontab -e 0 10 * * * /usr/bin/php -q /www/htdocs/phpdocs/expired_users.php
here,
'/usr/local/bin/php' - where php is installed in our server
'-q' - run the file
'/www/htdocs/phpdocs/expired_users.php' - path for the executable file
Example 2:
If you want a cron job to run on every month first day (ex: 01-10-2008) at 5 a.m. then the cron command will be like,
[root@mylinux ~]#crontab -e 0 5 1 * * /usr/bin/php -q /www/htdocs/phpdocs/expired_users.php
Example 3:
The following command should run by cron at 1 am on everyday.
[root@mylinux ~]#crontab -e 0 1 * * * /usr/bin/php -q /www/htdocs/phpdocs/expired_users.php
Example 4:
The following command should run by cron at every 5 minutes.
[root@mylinux ~]#crontab -e */5 * * * * /usr/bin/php -q /www/htdocs/phpdocs/expired_users.php
Conclusion:
* There are lots of things to automate in Unix
* Many of them are done routinely
* You (the administrator) have better things to do
* Cron (and some appropriate shell scripts) can do them for you
Monday, August 25, 2008
Extracting text from Word Documents via PHP and COM
$word = new COM("word.application") or die ("Could not initialise MS Word object.");
$word->Documents->Open(realpath("Sample.doc"));
// Extract content.
$content = (string) $word->ActiveDocument->Content;
echo $content;
$word->ActiveDocument->Close(false);
$word->Quit();
$word = null;
unset($word);
$word->Documents->Open(realpath("Sample.doc"));
// Extract content.
$content = (string) $word->ActiveDocument->Content;
echo $content;
$word->ActiveDocument->Close(false);
$word->Quit();
$word = null;
unset($word);
Thursday, August 14, 2008
Various Script Optimization techniques! New
what are the various PHP Script Optimization techniques?
1. If a method can be static, declare it static. Speed
improvement is by a factor of 4.
2. Avoid magic like __get, __set, __autoload
3. require_once() is expensive
4. Use full paths in includes and requires, less time spent
on resolving the OS paths.
5. If you need to find out the time when the script started
executing, $_SERVER[’REQUEST_TIME’] is preferred to time()
6. See if you can use strncasecmp, strpbrk and stripos
instead of regex
7. str_replace is faster than preg_replace, but strtr is
faster than str_replace by a factor of 4
8. If the function, such as string replacement function,
accepts both arrays and single characters as arguments, and
if your argument list is not too long, consider writing a
few redundant replacement statements, passing one character
at a time, instead of one line of code that accepts arrays
as search and replace arguments.
9. Error suppression with @ is very slow.
10. $row[’id’] is 7 times faster than $row[id]
11. Error messages are expensive
12. Do not use functions inside of for loop, such as for
($x=0; $x < count($array); $x) The count() function gets
called each time.
1. If a method can be static, declare it static. Speed
improvement is by a factor of 4.
2. Avoid magic like __get, __set, __autoload
3. require_once() is expensive
4. Use full paths in includes and requires, less time spent
on resolving the OS paths.
5. If you need to find out the time when the script started
executing, $_SERVER[’REQUEST_TIME’] is preferred to time()
6. See if you can use strncasecmp, strpbrk and stripos
instead of regex
7. str_replace is faster than preg_replace, but strtr is
faster than str_replace by a factor of 4
8. If the function, such as string replacement function,
accepts both arrays and single characters as arguments, and
if your argument list is not too long, consider writing a
few redundant replacement statements, passing one character
at a time, instead of one line of code that accepts arrays
as search and replace arguments.
9. Error suppression with @ is very slow.
10. $row[’id’] is 7 times faster than $row[id]
11. Error messages are expensive
12. Do not use functions inside of for loop, such as for
($x=0; $x < count($array); $x) The count() function gets
called each time.
Wednesday, August 13, 2008
PHP Interview Questions in Astute Tecknowledgies
hai all,
Anybody know the PHP interview questions asked in Astute Tecknowledgies?
Anybody know the PHP interview questions asked in Astute Tecknowledgies?
PHP Interview Questions in Innuendo Technologies Solution (ITS)
hai all,
Anybody know the PHP interview questions asked in Innuendo Technologies Solution (ITS)?
Anybody know the PHP interview questions asked in Innuendo Technologies Solution (ITS)?
PHP Interview Questions in Bharath matrimonial
hai all,
Anybody know the PHP interview questions asked in Bharath matrimonial?
Anybody know the PHP interview questions asked in Bharath matrimonial?
PHP Interview Questions in Adan prathan
hai all,
Anybody know the PHP interview questions asked in Adan Prathan?
Anybody know the PHP interview questions asked in Adan Prathan?
Subscribe to:
Posts (Atom)
Popular Posts
-
1. How old PHP language is? - PHP began in 1994, so 14 years old. 2. What are different names of PHP? - PHP originally stood for Persona...
-
HTML: a. HTML is a markup language that is used to build static (non interactive and nonanimated) webpages. b. HTML is Case-Insensitive. So...
-
A payment gateway is an e-commerce application service provider service that authorizes payments for e-businesses, online retailers, bricks...
-
Note : This is not a perfect sort order, we have just displaying the list of PHP companies. 1. Photon Infotech No. 2/102, Arvind IT Park (N...
-
Hai all, Simple show hide sample using Show/Hide? Simple Show/Hide code
-
- count() -- Count elements in a variable - syntax for count() [int count ( mixed var [, int mode])] - If the optional mode parameter is set...
-
Sharing PHP, MySQL, Javascript, CSS Knowledge, We can share our PHP knowledge on the basis of PHP versioning, Javascript, AJAX, Stylesheet, ...
-
Use the below code and you can get the exact value in php as us saw in browser. Code: $encode_data = iconv('UTF-8', 'windows-125...
-
Download and Enjoy!
-
1. Rasmus Lerdorf Rasmus Lerdorf (born November 22, 1968 in Qeqertarsuaq, Greenland) is a Danish-Greenlandic programmer and is most notable ...