Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Saturday, September 7, 2013

W3Schools PHP Quiz

W3Schools PHP Quiz

1. What does PHP stand for?
You answered:PHP: Hypertext Preprocessor
 Correct Answer!

2. PHP server scripts are surrounded by delimiters, which?
You answered:<?php…?>
 Correct Answer!

3. How do you write "Hello World" in PHP
You answered:echo "Hello World";
 Correct Answer!

4. All variables in PHP start with which symbol?
You answered:$
 Correct Answer!

5. What is the correct way to end a PHP statement?
You answered:;
 Correct Answer!

6. The PHP syntax is most similar to:
You answered:Perl and C
 Correct Answer!

7. How do you get information from a form that is submitted using the "get" method?
You answered:$_GET[];
 Correct Answer!

8. When using the POST method, variables are displayed in the URL:
You answered:False
 Correct Answer!

9. In PHP you can use both single quotes ( ' ' ) and double quotes ( " " ) for strings:
You answered:True
 Correct Answer!

10. Include files must have the file extension ".inc"
You answered:False
 Correct Answer!

11. What is the correct way to include the file "time.inc" ?
You answered:<?php include "time.inc"; ?>
 Correct Answer!

12. What is the correct way to create a function in PHP?
You answered:function myFunction()
 Correct Answer!

13. What is the correct way to open the file "time.txt" as readable?
You answered:fopen("time.txt","r");
 Correct Answer!

14. PHP allows you to send emails directly from a script
You answered:True
 Correct Answer!

15. What is the correct way to connect to a MySQL database?
You answered:mysqli_connect(host,username,password,dbname);
 Correct Answer!

16. What is the correct way to add 1 to the $count variable?
You answered:$count++;
 Correct Answer!

17. What is a correct way to add a comment in PHP?
You answered:/*…*/
 Correct Answer!

18. PHP can be run on Microsoft Windows IIS(Internet Information Server):
You answered:True
 Correct Answer!

19. In PHP, the die() and exit() functions do the exact same thing.
You answered:True
 Correct Answer!

20. Which one of these variables has an illegal name?
You answered:$my-Var
 Correct Answer!

Sunday, January 27, 2013

How to Create CAPTCHA Protection using PHP

there are following stpes
1. html code
<img src="/captcha.php/?rand=0.608989860869691" id="captcha_image"/>
<a href="javascript:void(0);" onClick="refreshcaptcha();" >Refresh</a>
<input type="text" name="norobot" id="norobot" value="Enter Image Code" />

2. js
function refreshcaptcha(){
    var capimage = document.getElementById('captcha_image').src;  
    var full_img=capimage.split('rand=');  
    document.getElementById('captcha_image').setAttribute('src', full_img[0]+'rand='+Math.random());
}

3.captcha.php
$randomnr = rand(1000, 9999);
$session["randomnr"] = md5($randomnr));
   
   
    $im = imagecreatetruecolor(100, 38);

    $white = imagecolorallocate($im, 255, 255, 255);
    $grey = imagecolorallocate($im, 150, 150, 150);
    $black = imagecolorallocate($im, 0, 0, 0);

    imagefilledrectangle($im, 0, 0, 200, 35, $black);

    //path to font - this is just an example you can use any font you like:
   
    $font =  '/font/karate/Karate.ttf';

    imagettftext($im, 20, 4, 22, 30, $grey, $font, $randomnr);

    imagettftext($im, 20, 4, 15, 32, $white, $font, $randomnr);
    
    //die(111);
    //prevent caching on client side:
    header("Expires: Wed, 1 Jan 1997 00:00:00 GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: no-store, no-cache, must-revalidate");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");

    header ("Content-type: image/gif");
    imagegif($im);
    imagedestroy($im);
    exit;

4. On post action file
if (md5($data['norobot']) == $session["randomnr"])    {
                // here you  place code to be executed if the captcha test passes
 }    else { 
                // here you  place code to be executed if the captcha test fails
                    echo "Please enter correct code.";
                    return;
}


Tuesday, May 29, 2012

How to get full url of website uing php

$protocol = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
$url = $protocol.'://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; //  More efficient manner
echo $url;

Friday, March 23, 2012

Improving PHP performance

I want to share these tips with my readers.

1. 'echo' is much faster than print. So always try echo something rather than printing it.

/*This is faster*/
echo 'This is echoed text';

/*This is slower*/
print 'This is printed text';

2. Always use the stacked form of echo instead of using concatenation. e.g

/*Faster form of echo*/
echo 'This is stacked form of ', $variable;

/*Slower form of echo*/
echo 'This is regular form of ' . $variable;

3. Use of single quotes rather than double quotes with echo can improve the performance of your code because compiler will not search for the variables inside the single quotes but in double quotes it will perform a search for possible variables.

/*Faster form of echo*/
echo 'This is single quoted string.';

/*Slower form of echo*/
echo "This is double quoted $string.";

4. Use pre-increments where possible instead of post-increments. Pre-incrementing is faster than post-increments.

/*Slower form of iteration*/
for ( $i=0; $i < 1000; $i++ ) {
echo 'Loop ',$i;
}

/*Faster form of iteration*/
for ( $i=0; $i < 1000; ++$i ) {
echo 'Loop ',$i;
}

5. Never use calculations as counters in an iteration.

/*Slower form of iteration*/
for ( $i=0; $i < count($arr); $i++ ) {
echo 'Loop ',$i;
}

/*Faster form of iteration*/
$counter = count($arr);

for ( $i=0; $i < $counter; $i++ ) {
echo 'Loop ',$i;
}

6. Always unset the variable after using those. It may save some of your resources on the server.

$counter = count($arr);

for ( $i=0; $i < $counter; $i++ ) {
$value = $arr[$i];

foo( $value );//call any function

unset($value);//unset the variable after using it.
}

7. Always initialize your variables before using those. It can sometimes prove beneficial in terms of performance.

$counter = count($arr);

$value = '';//initialize the variable before using it

for ( $i=0; $i < $counter; $i++ ) {
$value = $arr[$i];

foo( $value );//call any function

unset($value);//unset the variable after using it.
}

8. Always close the database connections after you are done with the queries.

mysql_connect('localhost', 'root', 'secret123');

mysql_select_db('test_db');

//write database queries here

mysql_close();//close the connection at the end

9. Avoid strlen() to check the length of a string. Checking the desired index in the string can also work.

/*Slower form*/
if ( strlen($str) > 100 ) {
echo 'You have crossed the limits';
}

/*Faster form*/
if ( $str[100] ) {
echo 'You have crossed the limits';
}

10. Use include() and require() instead of include_once() and require_once(). There's a lot of work involved in checking to see if a file has already been included. Sometimes it's necessary, but you should default to include() and require() in most situations.

11. Use full file paths on include/require statements. Normalizing a relative file path can be expensive; giving PHP the absolute path (or even "./file.inc") avoids the extra step.

12. Don't copy variables for no reason. Sometimes PHP novices attempt to make their code "cleaner" by copying predefined variables to variables with shorter names before working with them. What this actually results in is doubled memory consumption (when the variable is altered), and therefore, slow scripts. In the following example, if a user had inserted 512KB worth of characters into a textarea field. This implementation would result in nearly 1MB of memory being used.

/*Slower form*/
$description = strip_tags($_POST['description']);
echo $description;

/*Faster form*/
echo strip_tags($_POST['description']);

13. Avoid doing SQL queries within a loop. A common mistake is placing a SQL query inside of a loop. This results in multiple round trips to the database, and significantly slower scripts. In the example below, you can change the loop to build a single SQL query and insert all of your users at once.

foreach ($userList as $user) {
$query = 'INSERT INTO users (first_name,last_name) VALUES("' . $user['first_name'] . '", "' . $user['last_name'] . '")';
mysql_query($query);
}

Produces:

INSERT INTO users (first_name,last_name) VALUES("John", "Doe")

Instead of using a loop, you can combine the data into a single database query.

$userData = array();
foreach ($userList as $user) {
$userData[] = '("' . $user['first_name'] . '", "' . $user['last_name'] . '")';
}
$query = 'INSERT INTO users (first_name,last_name) VALUES' . implode(',', $userData);
mysql_query($query);

Produces:
INSERT INTO users (first_name,last_name) VALUES("John", "Doe"),("Jane", "Doe")...

14. Avoid OOP whenever you can. You should use OOP concepts only when these are really required. Study the situation you are working in. If you can do the things without OOP concepts, do it without hesitation. Using OOP for smaller tasks will always increase overhead rather than improving the performance. So the core concepts can help in most of the situations.'

15. Always strive for caching. Each time your request is processed by the server, the server has to reproduce the similar content repetitively. This wastes a lot of server resources just for nothing useful. So try to implement templating systems like 'Smarty'. It will always fasten your web application.

16. Using in built functions of PHP is many times faster than using custom build functions. So search the PHP manual thoroughly before writing your own function. Nearly every type of function is available in PHP.