Substr () PHP Function

The Substr () PHP Function is used to return part of a string. It is written as substr (string, start, optional length);.The string is whatever string you want to return a portion of. The start is how many characters in to skip before starting. Setting this to 3 would skip the first three and start returning at the forth character. Setting this to a negative number will start counting backwards from the end of the string.
Length is an optional parameter. If you set this to a positive number, it will return that number of characters. If you set this to a negative number it will count that many numbers from the end of the string and return whatever is left in the middle.
See how this works :

<?php
// this will return bcdefghijk
echo substr(’abcdefghijk’, 1);
echo “<br>”;

// this will return defghijk
echo substr(’abcdefghijk’, 3);
echo “<br>”;

// this will return abc
echo substr(’abcdefghijk’, 0, 3);
echo “<br>”;

// this will return ijk
echo substr(’abcdefghijk’, -3);
echo “<br>”;

// this will return bcdefghij
echo substr(’abcdefghijk’, 1, -1);
echo “<br>”;

// this will return cdefgh
echo substr(’abcdefghijk’, 2, -3);
echo “<br>”;
?>

Fake University in India

Fake Universities

State-wise List of fake Universities as on 18thJanuary, 2009

    Bihar
  • Maithili University/Vishwavidyalaya, Darbhanga, Bihar.
    • Delhi
  • Varanaseya Sanskrit Vishwavidyalaya, Varanasi (UP) Jagatpuri, Delhi.
  • Commercial University Ltd., Daryaganj, Delhi.
  • United Nations University, Delhi.
  • Vocational University, Delhi.
  • ADR-Centric Juridical University, ADR House, 8J, Gopala Tower, 25 Rajendra Place, New Delhi - 110 008.
  • Indian Institute of Science and Engineering, New Delhi.
    • Karnataka
  • Badaganvi Sarkar World Open University Education Society, Gokak, Belgaum, Karnataka.
    • Kerala
  • St. John?s University, Kishanattam, Kerala.
    • Madhya Pradesh
  • Kesarwani Vidyapith, Jabalpur, Madhya Pradesh.
    • Maharashtra
  • Raja Arabic University, Nagpur, Maharashtra.
    • Tamil Nadu
  • D.D.B. Sanskrit University, Putur, Trichi, Tamil Nadu.
    • West Bengal
  • Indian Institute of Alternative Medicine, Kolkatta.
    • Uttar Pradesh
  • Mahila Gram Vidyapith/Vishwavidyalaya, (Women?s University) Prayag, Allahabad,
    Uttar Pradesh.
  • Indian Education Council of U.P., Lucknow, Uttar Pradesh.
  • Gandhi Hindi Vidyapith, Prayag, Allahabad, Uttar Pradesh.
  • National University of Electro Complex Homeopathy, Kanpur, Uttar Pradesh.
  • Netaji Subhash Chandra Bose University (Open University), Achaltal, Aligarh, Uttar Pradesh.
  • Uttar Pradesh Vishwavidyalaya, Kosi Kalan, Mathura, Uttar Pradesh.
  • Maharana Pratap Shiksha Niketan Vishwavidyalaya, Pratapgarh, Uttar Pradesh.
  • Indraprastha Shiksha Parishad, Institutional Area,Khoda,Makanpur,Noida Phase-II, Uttar Pradesh.
  • Gurukul Vishwavidyala, Vridanvan, Uttar Pradesh.
  • To Know more Click Here

    HTML & JavaScript Loader

    In this program just change the source of  iframe and your loading.gif will show upto that time when page will not upload finally.

    For Demo Click Here

    Download Script Click Here

    50+ PHP tips and tricks

    1. echo is faster than print.
    2. Wrap your string in single quotes (’) instead of double quotes (”) is faster because PHP searches for variables inside “…” and not in ‘…’, use this when you’re not using variables you need evaluating in your string.
    3. Use sprintf instead of variables contained in double quotes, it’s about 10x faster.
    4. Use echo’s multiple parameters (or stacked) instead of string concatenation.
    5. Use pre-calculations, set the maximum value for your for-loops before and not in the loop. ie: for ($x=0; $x < count($array); $x), this calls the count() function each time, use $max=count($array) instead before the for-loop starts.
    6. Unset or null your variables to free memory, especially large arrays.
    7. Avoid magic like __get, __set, __autoload.
    8. Use require() instead of require_once() where possible.
    9. Use full paths in includes and requires, less time spent on resolving the OS paths.
    10. require() and include() are identical in every way except require halts if the file is missing. Performance wise there is very little difference.
    11. Since PHP5, the time of when the script started executing can be found in $_SERVER[’REQUEST_TIME’], use this instead of time() or microtime().
    12. PCRE regex is quicker than EREG, but always see if you can use quicker native functions such as strncasecmp, strpbrk and stripos instead.
    13. When parsing with XML in PHP try xml2array, which makes use of the PHP XML functions, for HTML you can try PHP’s DOM document or DOM XML in PHP4.
    14. str_replace is faster than preg_replace, str_replace is best overall, however strtr is sometimes quicker with larger strings. Using array() inside str_replace is usually quicker than multiple str_replace.
    15. “else if” statements are faster than select statements aka case/switch.
    16. Error suppression with @ is very slow.
    17. To reduce bandwidth usage turn on mod_deflate in Apache v2 or for Apache v1 try mod_gzip.
    18. Close your database connections when you’re done with them.
    19. $row[’id’] is 7 times faster than $row[id], because if you don’t supply quotes it has to guess which index you meant, assuming you didn’t mean a constant.
    20. Use <?php … ?> tags when declaring PHP as all other styles are depreciated, including short tags.
    21. Use strict code, avoid suppressing errors, notices and warnings thus resulting in cleaner code and less overheads. Consider having error_reporting(E_ALL) always on.
    22. PHP scripts are be served at 2-10 times slower by Apache httpd than a static page. Try to use static pages instead of server side scripts.
    23. PHP scripts (unless cached) are compiled on the fly every time you call them. Install a PHP caching product (such as memcached or eAccelerator or Turck MMCache) to typically increase performance by 25-100% by removing compile times. You can even setup eAccelerator on cPanel using EasyApache3.
    24. An alternative caching technique when you have pages that don’t change too frequently is to cache the HTML output of your PHP pages. Try Smarty or Cache Lite.
    25. Use isset where possible in replace of strlen. (ie: if (strlen($foo) < 5) { echo “Foo is too short”; } vs. if (!isset($foo{5})) { echo “Foo is too short”; } ).
    26. ++$i is faster than $ i++, so use pre-increment where possible.
    27. Make use of the countless predefined functions of PHP, don’t attempt to build your own as the native ones will be far quicker; if you have very time and resource consuming functions, consider writing them as C extensions or modules.
    28. Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview.
    29. Document your code.
    30. Learn the difference between good and bad code.
    31. Stick to coding standards, it will make it easier for you to understand other people’s code and other people will be able to understand yours.
    32. Separate code, content and presentation: keep your PHP code separate from your HTML.
    33. Don’t bother using complex template systems such as Smarty, use the one that’s included in PHP already, see ob_get_contents and extract, and simply pull the data from your database.
    34. Never trust variables coming from user land (such as from $_POST) use mysql_real_escape_string when using mysql, and htmlspecialchars when outputting as HTML.
    35. For security reasons never have anything that could expose information about paths, extensions and configuration, such as display_errors or phpinfo() in your webroot.
    36. Turn off register_globals (it’s disabled by default for a reason!). No script at production level should need this enabled as it is a security risk. Fix any scripts that require it on, and fix any scripts that require it off using unregister_globals(). Do this now, as it’s set to be removed in PHP6.
    37. Avoid using plain text when storing and evaluating passwords to avoid exposure, instead use a hash, such as an md5 hash.
    38. Use ip2long() and long2ip() to store IP addresses as integers instead of strings.
    39. You can avoid reinventing the wheel by using the PEAR project, giving you existing code of a high standard.
    40. When using header(’Location: ‘.$url); remember to follow it with a die(); as the script continues to run even though the location has changed or avoid using it all together where possible.
    41. In OOP, if a method can be a static method, declare it static. Speed improvement is by a factor of 4..
    42. Incrementing a local variable in an OOP method is the fastest. Nearly the same as calling a local variable in a function and incrementing a global variable is 2 times slow than a local variable.
    43. Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.
    44. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.
    45. Just declaring a global variable without using it in a function slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.
    46. Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance.
    47. Methods in derived classes run faster than ones defined in the base class.
    48. A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations. A similar method call is of course about 15 $localvar++ operations.
    49. Not everything has to be OOP, often it is just overhead, each method and object call consumes a lot of memory.
    50. Never trust user data, escape your strings that you use in SQL queries using mysql_real_escape_string, instead of mysql_escape_string or addslashes. Also note that if magic_quotes_gpc is enabled you should use stripslashes first.
    51. Avoid the PHP mail() function header injection issue.
    52. Unset your database variables (the password at a minimum), you shouldn’t need it after you make the database connection.
    53. RTFM! PHP offers a fantastic manual, possibly one of the best out there, which makes it a very hands on language, providing working examples and talking in plain English. Please USE IT!

    Companies Using PHP

    Often the question is asked by those who wish to convince a CEO or or some company heavy weight when the question is asked “What large sites are using PHP”. Well here is a list of large comapnies and sites known to using PHP.

    Like many enterprises, PHP is not always the sole language in use, and is most often combined for tasks to which is it best suited.

    Difference between isset empty is null

    I have come across code that checks for empty or null values, or if a variable is set. Many of these checks fail as the wrong function is being used to assert the correct value. While it is important to be checking values, it is equally important to understand the difference between the different methods of checking and testing values for empty, null, or if they are set.

    Most common is the incorrect use of isset() and empty(). Many times these are seen to be used interchangeably, where the reality is, that the two are complete opposites. Look at some code.

    <?php

    var_dump( !isset( $var ) );

    var_dump( empty( $var ) );

    ?>

    The above snippet tests for not isset and empty for a variable which has not been set. The results both return true.

    bool(true)
    bool(true)

    The correct method to check if a variable is set or not, is with the isset() function, or, if checking for an empty variable, then use empty(). These functions are provided for good reason, as seen in this code below.

    <?php

    error_reporting(E_ALL);
    if( ! isset(
    $var ) )

    {
    echo ‘Variable is not set<br />’;
    }
    if( empty(
    $var ) )

    {
    echo ‘Variable is empty<br />’;
    }
    if(
    $var )

    {
    echo ‘Variable is set<br />’;
    }
    ?>

    The above snippet produces the following..

    Variable is not set

    Variable is empty

    Notice: Undefined variable: var in /test.php on line 15

    This shows why the use of if($var) type syntax is shunned by many programmers, as PHP throws an E_NOTICE error when it finds an uninitialized variable. The checks for isset and empty declare the variable is not set, and that it is empty? Which is it? The Empty function would have us believe the variable is set, but the value is empty, but this is not the case, the variable is clearly undefined, and the third test which gives and error supports this. Confused?

    To make matters just a little more complex, the empty function will also return true, if the variable has a value of zero. Lets take it for a drive.

    <?php

    /*** turn on error reporting ***/
    error_reporting(E_ALL);

    /*** set variable to zero ***/
    $var = 0;
    if( isset(
    $var ) )
    {
    echo
    ‘Variable is set<br />’;
    }

    if( empty( $var ) )
    {
    echo
    ‘Variable is empty<br />’;
    }

    if( $var )
    {
    echo
    ‘Variable is set<br />’;
    }
    ?>

    Running this test, provides some more clues to the behavior mentioned earlier. The response is:

    Variable is set

    Variable is empty

    At the top of the script, the variable is clearly set to zero, and a check with isset asserts this. However, the next check with the empty function shows the variable to be empty, even though a value for it has been set. Then the final check with if( $var ) does not show the text for the same reason empty shows the variable to be empty.

    To get a better understanding of this seemingly odd behavior lets make a quick test chart can be produced to check for values and the values each returns based on the function that is checking each of the values. The code for producing such a table is provided below, but, here is one we prepared earlier. The error message is produced because the isset() function is trying to check a variable that has not been initialized, as seen earlier in this article.

    Notice: Undefined variable: var in /test.php on line 10

    TEST Not Set NULL Zero FALSE Numeric Value Empty String
    Comparison Table
    isset() bool(false) bool(false) bool(true) bool(true) bool(true) bool(true)
    empty() bool(true) bool(true) bool(true) bool(true) bool(false) bool(true)
    is_null() bool(true) bool(true) bool(false) bool(false) bool(false) bool(false)
    == bool(true) bool(true) bool(true) bool(true) bool(false) bool(true)
    === bool(false) bool(false) bool(false) bool(true) bool(false) bool(false)

    The Comparison Table Code

    <table style=”border: solid 1px black; width:100%;”>

    <tr style=”text-align:left;”><th>TEST</th><th>Not Set</th><th>NULL</th><th>Zero</th><th>FALSE</th><th>Numeric Value</th><th>Empty String</th></tr>
    <tfoot><tr><td colspan=”6″>Comparison Table</td></tr></tfoot>
    <tbody>
    <?php
    /*** turn on error reporting ***/
    error_reporting( E_ALL );

    /*** an array of test values ***/
    $values = array( $var, null, 0, false, 100, );
    echo
    ‘<tr>’;
    echo
    ‘<td>isset()</td>’;
    foreach(
    $values as $val )
    {
    echo
    ‘<td>’;
    var_dump( isset( $val ) );
    echo
    ‘</td>’;
    }
    echo
    ‘</tr>’;

    echo ‘<tr>’;
    echo
    ‘<td>empty()</td>’;
    foreach(
    $values as $val )
    {
    echo
    ‘<td>’;
    var_dump( empty( $val ) );
    echo
    ‘</td>’;
    }
    echo
    ‘</tr>’;

    echo ‘<tr>’;
    echo
    ‘<td>is_null()</td>’;
    foreach(
    $values as $val )
    {
    echo
    ‘<td>’;
    var_dump( is_null( $val ) );
    echo
    ‘</td>’;
    }
    echo
    ‘</tr>’;

    echo ‘<tr>’;
    echo
    ‘<td>==</td>’;
    foreach(
    $values as $val )
    {
    echo
    ‘<td>’;
    var_dump( $val == false );
    echo
    ‘</td>’;
    }
    echo
    ‘</tr>’;

    echo ‘<tr>’;
    echo
    ‘<td>===</td>’;
    foreach(
    $values as $val )
    {
    echo
    ‘<td>’;
    var_dump( $val === false );
    echo
    ‘</td>’;
    }
    echo
    ‘</tr>’;
    ?>
    </tbody>
    </table>

    PHP Type Casting

    Contents

    1. Types
    2. Casting
    3. Check for Type

    The PHP is often referred to as “loosely typed” or “dynaically typed”. What this means is that variable types are detirmined by context. Lets jump straight into some code to see it in action.


    <?php

    /*** create a number as a string ***/
    $var = “6″;

    /*** display the variable type and value ***/
    var_dump($var);

    echo ‘<br />’;

    /*** increment the variable ***/
    $var++;

    /*** display the variable type and value ***/
    var_dump($var);

    ?>


    The above code will produce the following output:

    string(1) “6″

    int(7)

    We began with a string value of 6 and then incremented the variable using the ++ operand. PHP has noted the context of the operation and internally converted the type to INT.

    Types

    PHP supports many different types, these include

    • int
    • string
    • binary
    • unicode
    • array
    • boolean
    • bool (same as boolean)
    • object
    • float
    • double (same as float)
    • real (same as float)

    Casting

    The ability of PHP to be able to dynamically type variables makes for quick and lean code. But for those times where we absolutely need the variable to be of a particular type, the variable must be cast. This is done in much the same way as in C.

    Cast To String


    <?php

    /*** create an int ***/
    $num = 6;

    /*** dump the type ***/
    var_dump($num);

    echo ‘<br />’;

    /*** cast to string ***/
    $num = (string) $num;

    /*** dump again ***/
    var_dump($num);
    ?>


    The above script shows us the variable begins as an integer and then is cast to a string.

    int(6)

    string(1) “6″

    Cast To Int

    Just as PHP allows casting to string, the same applies when casting to an integer


    <?php

    /*** create an string ***/
    $string = “26″;

    /*** dump the type ***/
    var_dump($string);

    echo ‘<br />’;

    /*** cast to int ***/
    $string = (int) $string;

    /*** dump again ***/
    var_dump($string);

    ?>


    The above script tells that the string is created and then converted to an int.

    string(2) “26″

    int(26)

    Try changing the value of the value of the sting to a non-numerical value such as “this is a string”. The result, after casting, would then be int(0).

    Cast To Binary

    Cast To Unicode

    Cast To Boolean


    <?php

    /*** create an int ***/
    $num = 1;

    /*** dump the type ***/
    var_dump($num);

    echo ‘<br />’;

    /*** cast to bool ***/
    $bool = (bool) $num;

    /*** dump again ***/
    var_dump($bool);

    ?>


    The above script will output the following:

    int(1)

    bool(true)

    The script ouputs bool(true) because “1″ is considered to be a true boolean value. Other values that evaluate to boolean true are:

    • -1
    • “string”
    • 1.6e5

    So, basically, any non zero value will evalute to boolean true. Values that evaluate to boolean false are:

    • 0
    • “0″
    • “”
    • FALSE
    • array()
    • NULL

    Cast To Object

    This is quite groovy. Casting an array to an object allows the use of the array as an object, using the corresponding keys and values.

    <?php

    /*** create an array ***/
    $array = array(‘animal’=>‘koala’, ‘name’=>‘bruce’, ‘type’=>‘marsupial’);

    /*** cast to an object ***/
    $object = (object)$array;

    /*** use the array as an object ***/
    echo $object->name;

    ?>


    If any other type, such as a sting or integer is cast to an object, PHP creates an instance of stdClass and the value is contained within the class member scalar as shown here:


    <?php

    /*** create an array ***/
    $string = ‘this is a string’;

    /*** cast to an object ***/
    $object = (object)$string;

    /*** output the value ***/
    echo $object->scalar;

    ?>


    The above string outputs “this is a string” as the string value has been assigned internally by PHP to the special class member “scalar”.

    Cast To Float

    Floats are also known as double or real values and casting is generally considered to be a bad idea with PHP as the precision needed with floats is not readily available as PHP has a finite amount of numbers. Better results can be had with the bc functions.

    Check for Type

    Up to this point we have dealt with converting or casting types. But there will be times when we need to check what type of variable a script is using. PHP comes with several ways to achieve this with the is_* functions and the charater type, or ctype_* functions.

    Check String

    In PHP most variables are strings to begin with, so this is rather straight forward.


    <?php

    /*** a simple string ***/
    $string = ‘This is a string’;

    /*** check if value is a string ***/
    if(is_string($string))
    {
    echo
    $string;
    }

    ?>


    Check INT

    PHP has several ways of checking if the value of a variable is an integer, using the is_int() function is the preferred method. The is_interger() and is_long functions are both an alias of is_int().


    <?php

    /*** a simple int ***/
    $int = 1234;

    /*** check if value is a int ***/
    if(is_int($int))
    {
    echo
    $int;
    }

    ?>


    Of course, we could use the ctype_digit() function to check also.


    <?php

    /*** a simple int ***/
    $int = 1234;

    /*** check if value is a int ***/
    if(ctype_digit($int))
    {
    echo
    $int;
    }

    ?>


    Note:

    While the function is_numeric() also checks the value of a string for numbers, it should not be used as it also returns try for floats and scientific notification.

    Check Array

    To check if a value is or type array, simply use is_array() as we have seen earlier with other types, you should have the swing of this by now..


    <?php

    /*** a simple array ***/
    $array = array(‘animal’=>‘koala’, ‘name’=>‘bruce’, ‘type’=>‘marsupial’);

    /*** check if value is an array ***/
    if(is_array($array))
    {
    /*** cast array to object ***/
    $obj = (object)$array;
    /*** echo the name value ***/
    echo $obj->name;
    }

    ?>


    The above code outputs “bruce”. As we saw in the Cast To Object section we can cast the array to an object. In this instance we have first checked that the value is indeed an array with the is_array() function.

    Check Object

    No surprises here as to what function is used to check if a variable is an object.. is_object().


    <?php

    /*** a simple object ***/
    $obj = new stdClass;

    /*** check if value is an object ***/
    if(is_object($obj))
    {
    echo
    ‘Object found’;
    }

    ?>


    Check Float

    To check if a variable is a float or double or real type, the is_float() function is used. It should be noted that all values from super globals such as $_GET or $_POST are strings and to check the values of these the is_numeric() function should be used. Here we show how to check for a floating point number.


    <?php

    /*** use pi as a floating point number ***/
    $num = pi();

    /*** check if value is an float ***/
    if(is_float($num))
    {
    echo
    $num;
    }

    ?>


    The above script checks the value of pi() and finds it has a value of 3.14159265359 and so, echoes the value.

    Check Double

    To check if a number is a double the is_double() function can be used. This function is an alias of is_float() and so the same procedure applies as seen in the section Check Float.

    Check Real

    To check if a number is a real type the is_real() function can be used. This function is an alias of is_float() and so the
    same procedure applies as seen in the section Check Float.

    Check Boolean

    Checking a boolean value is quite simple, just as we have seen through-out this document the is_bool() function is used.


    <?php

    /*** create a boolean value ***/
    $bool = is_int(0);

    /*** check if value is boolean ***/
    if(is_bool($bool))
    {
    var_dump($bool);
    }

    ?>


    In the above code we have checked if the number zero is an integer with the is_int() function. This returns boolean true on success so when checked with the is_bool() function we see that it is boolean and dumping the resulting variable shows bool(true).

    Check Buffer

    This bad boy checks if a variable is a native unicode or binary string. The is_buffer() function works the same as the other is_* functions


    <?php

    /*** create a unicode string ***/
    $unicode = “û?Ìcöde”;

    /*** check if value is unicode ***/
    if(is_buffer($unicode))
    {
    echo
    ‘Unicode string’;
    }

    ?>


    Check Binary

    To check if variable is a native binary, use the is_binary() function.


    <?php
    /*** no code for this function yet ***/

    ?>


    Check Unicode

    To check if a string is a unicode string, the is_unicode() function is used as below.


    <?php

    /*** create a unicode string ***/
    $unicode = “û?Ìcöde”;

    /*** check if value is unicode ***/
    if(is_unicode($unicode))
    {
    echo
    ‘Unicode string’;
    }

    ?>


    Check NULL

    To find if a variable value is NULL the is_null() function is used.


    <?php

    /*** create a null value ***/
    $var = null;

    /*** check if value is null ***/
    if(is_null($var))
    {
    echo
    ‘Value is null’;
    }
    ?>


    Check Resource

    A resource is a type returned by PHP from opened files and database connections. Using the is_resource() function a variable can be checked reliably.


    <?php

    /*** a database connection resource ***/
    $conn = @mysql_connect(‘localhost’, ‘username’, ‘password’);

    /*** check if connection is a valid resource ***/
    if (is_resource($conn))
    {
    /*** show the resource type ***/
    echo get_resource_type($conn);
    }
    else
    {
    /*** show an error on failure ***/
    echo “Connection Failed: ”.mysql_error();
    }

    ?>


    Check Scalar

    A scalar value is a variable value of type boolean, string, integer or float. All other types are considered non-scalar values. To check for a scalar value use the is_scalar() function.


    <?php

    /*** a string ***/
    $string =“5.2″;

    /*** check if value is scalar ***/
    if (is_scalar($string))
    {
    echo
    $string.‘ is scalar’;
    }

    ?>


    PHP Tutorial - Part VI

    Introduction
    In this part I will continue this and also show you how to use PHP and forms together to make your PHP scripts useful.

    Setting Up Your Form
    Setting up a form for use with a PHP script is exactly the same as normal in HTML. As this is a PHP tutorial I will not go into depth in how to write your form but I will show you three of the main pieces of code you must know:
    <input type=”text” name=”thebox” value=”Your Name”>
    Will display a text input box with Your Name written in it as default. The value section of this code is optional. The information defined by name will be the name of this text box and should be unique.

    <textarea name=”message”>Please write your message here.</textarea>
    Will display a large scrolling text box with the text ‘Please write your message here.’ as default. Again, the name is defined and should be unique.

    <input type=”submit” value=”Submit”>

    This will create a submit button for your form. You can change what it says on the button by changing the button’s value. All the elements for your form must be enclosed in the <form> tags. They are used as follows:

    <form action=”process.php” method=”post”>Form elements and formatting etc.</form>
    The form’s action tells it what script to send its data to (in this case its process.php). This can also be a full URL (e.g. http://www.shashionline.in/scripts/process.php).
    The method tells the form how to submit its data. POST will send the data in a data stream to the script when it is requested. GET is the other option. GET will send the form data in the form of the url so it would appear after a question mark e.g.
    http://www.shashionline.in/process.php?name=shashi

    It really makes no difference which system you use but it is normally better to use POST if you are using passwords or sensitive information as they should not be shown in the browser’s address bar.
    Getting The Form Information

    The next step is to get the data the form has submitted into your script so that you can do something with it. This is. There are basically two different methods of getting the data into
    PHP, which depend on how they were submitted. There are two submission methods, GET and POST, which can both be used by forms. The difference between the two is that using GET, the variables and data will be shown in the page address, but using POST it is invisible. The
    benefit of GET, though is that you can submit information to the script without a form, by simply
    editing the URL.

    This works the same as submitting a form using GET. The advantage of this is that you can create links to your scripts which do different things depending on the link clicked. For example you could create a script which will show different pages depending on the link clicked:

    yourpage.php?user=shashi could show shashi’s page and: yourpage.php?user=raj could show

    raj’s page, using the same script. It is also possible to pass more than one piece of information to the script using this system by separating them with the & symbol:

    yourpage.php?user=shashi&referrer=gowansnet&area=6

    These could all be accessed separately using the GET variables user, referrer and area.

    To get a variable which has been sent to a script using the POST method you use the following code:
    $variablename=$_POST['variable'];

    which basically takes the variable from the POST (the name of a form field) and assigns it to the variable $variablename. Similarly, if you are using the GET method you should use the form:

    $variablename=$_GET['variable'];

    This should be done for each variable you wish to use from your form (or URL).

    Creating The Form To Mail Script

    To finish off this section, I will show you how to use what you have learnt in this part and the last to create a system which will e-mail a user’s comments to you. Firstly, create this form for your HTML page:

    <form action=”mail.php” method=”post”>

    Your Name: <input type=”text” name=”name”><br>

    E-mail: <input type=”text” name =”email”><br><br>

    Comments<br>

    <textarea name=”comments”></textarea><br><br>

    <input type=”submit” value=”Submit”>

    </form>
    This will make a simple form where the user can enter their e-mail address, their name and their comments. You can, of course, add extra parts to this form but remember to update the script too. Now create the PHP script:

    <?

    function
    checkOK($field)

    {

    if (eregi(”\r”,$field) || eregi(”\n”,$field)){

    die(”Invalid Input!”);

    }

    }

    $name=$_POST['name'];

    checkOK($name);

    $email=$_POST['email'];

    checkOK($email);

    $comments=$_POST['comments'];

    checkOK($comments);

    $to=”info@shashionline.in”;

    $message=”$name just filled in your comments form. They said:\n$comments\n\nTheir e-mail address was: $email”;

    if(mail($to,”Comments From Your Site”,$message,”From: $email\n”)) {

    echo “Thanks for your comments.”;

    } else {

    echo “There was a problem sending the mail. Please check that you filled in the form
    correctly.”;

    }

    ?>

    Remember to replace info@shashionline.in with your own e-mail address. This script should be saved as mail.php and both should be uploaded. Now, all you need to do is to fill in your
    comments form. The first part of that script may look a bit strange:

    function checkOK($field)

    {

    if
    (eregi(”\r”,$field) || eregi(”\n”,$field)){

    die(”Invalid Input!”);

    }

    }
    You don’t really need to worry about what this is doing, but basically, it stops spammers from using your form to send thier spam messages by checking special characters are not present
    in the input which can be used to trick the computer into sending messages to other addresses. It is a fuction which checks for these characters, and if they are found, stops running the script.

    The lines:

    checkOK($name);etc. run this check on each input to ensure it is valid.

    PHP Tutorial - Part V

    Introduction
    One of the major uses of a server side scripting language is to provide a way of sending e-mail from the server and, in particular, to take form input and output it to an e-mail address.

    The Mail Command
    Mail is extremely easy to send from PHP, unlike using scripting languages which require special setup (like CGI). There is actually just one command, mail() for sending mail. It is used as follows:
    mail($to,$subject,$body,$headers);

    In this example I have used variables as they have descriptive names but you could also just place text in the mail command. Firstly, $to. This variable (or section of the command) contains the e-mail address to which the mail will be sent. $subject is the section for the subject of the e-mail and $body is the actual text of the e-mail.
    The section $headers is used for any additional e-mail headers you may want to add. The most common use of this is for the From field of an e-mail but you can also include other headers like cc and bcc.

    Sending An E-mail
    Before sending your mail, if you are using variables, you must, of course, set up the variable content beforehand. Here is some simple code for sending a message:
    $to = “info@shashionline.in”;
    $subject = “PHP Is Great”;
    $body = “PHP is one of the best scripting languages around”;
    $headers = “From: webmaster@shashionline.in\n”;
    mail($to,$subject,$body,$headers);
    echo “Mail sent to $to”;


    This code will acutally do two things. Firstly it will send a message to info@shashionline.in with the subject ‘PHP Is Great’ and the text:

    PHP is one of the best scripting languages around and the e-mail will be from webmaster@shashionline.in. It will also output the text: Mail sent to info@shashionline.in to the browser.

    Formatting E-mail
    Something you may have noticed from the example is that the From line ended with \n. This is acutally a very important character when sending e-mail. It is the new line character and
    tells PHP to take a new line in an e-mail. It is very important that this is put in after each header you add so that your e-mail will follow the international standards and will be delivered.

    The \n code can also be used in the body section of the e-mail to put line breaks in but should not be used in the subject or the To field.

    Mail Without Variables
    The e-mail above could have been sent using different variable names (it is the position of the variables in relation to the commas, not the name of them which decides on their use). It could
    also have been done on one line using text like this:

    mail(”info@shashionline.in”,”PHP Is Great”,”PHP is one of the best scripting languages around”,”From:
    webmaster@shashionline.in\n”);

    Error Control
    As anyone who has been scripting for a while will know, it is extremely easy to make mistakes in your code and it is also very easy to input an invalid e-mail address (especially if you are
    using your script for form to mail). Because of this, you can add in a small piece of code which will check if the e-mail is sent:
    if(mail($to,$subject,$body,$headers))
    {
    echo “An e-mail was sent to $to with the subject: $subject”;
    } else {
    echo “There was a problem sending the mail. Check your code and make sure that the e-mail address $to is valid”;
    }


    This code is quite self explanitory. If the mail is sent successfully it will output a message to the browser telling the user, if not, it will display an error message with some suggestions for correcting the problem.

    PHP Tutorial - Part IV

    The WHILE Loop

    The WHILE loop is one of the most useful commands in PHP. It is also quite easy to set up and use. A WHILE loop will, as the name suggests, execute a piece of code until a certain condition is met.
    Repeating A Set Number Of Times

    If you have a piece of code which you want to repeat several times without retyping it, you can use a while loop. For instance if you wanted to print out the words “Hello World” 5 times you could use the following code:
    $times = 5;
    $x = 0;
    while ($x
    < $times) {
    echo “Hello World”;
    ++$x;
    }

    Using $x

    The variable counting the number of repeats ($x in the above example) can be used for much more than just counting. For example if you wanted to create a web page with all the numbers from 1 to 1000 on it, you could either type out every single one or you could use the following code:

    $number = 1000;
    $current
    = 0;
    while ($current < $number)
    {
    ++$current;
    echo
    “$current<br>”;
    }

    There are a few things to notice about this code. Firstly, you will notice that I have placed the ++$current; before the echo statement. This is because, if I didn’t do this it would start printing numbers from 0, which is not what we want. The ++$current; line can be placed anywhere in your WHILE loop, it does not matter. It can, of course, add, subtract, multiply, divide or do anthing else to the number as well.

    The other reason for this is that, if the ++$current; line was after the echo line, the loop would also stop when the number showed 999 because it would check $current which would equal 1000 (set in the last loop) and would stop, even though 1000 had not yet been printed.

    Arrays

    Arrays are common to many programing languages. They are special variables which can hold more than one value, each stored in its own numbered ’space’ in the array. Arrays are extremely useful, especially when using WHILE loops.

    Setting Up An Array

    Setting up an array is slightly different to setting up a normal variable. In this example I will set up an array with 5 names in it:

    $names[0] =
    ‘John’;
    $names[1] = ‘Paul’;
    $names[2] =
    ‘Steven’;
    $names[3] = ‘George’;
    $names[4] =
    ‘David’;

    As you can see, the parts of an array are all numbered, starting from 0. To add a value to an array you must specify the location in the array by putting a number in [ ].

    Reading From An Array

    Reading from an array is just the same as putting information in. All you have to do is to refer to the array and the number of the piece of data in the array. So if I wanted to print out the third name I could use the code:

    style=”font-family: Arial;”>

    echo “The third name is $names[2]“;

    Which would output:

    The third name is Steven

    Using Arrays And Loops

    One of the best uses of a loop is to output the information in an array. For instance if I wanted to print out the following list of names:

    Name 1 is John
    Name 2 is Paul
    Name 3
    is Steven
    Name 4 is George
    Name 5 is
    David

    I could use the following code:

    $number = 5;
    $x =
    0;
    while ($x < $number) {
    $namenumber = $x +
    1;
    echo “Name $namenumber is
    $names[$x]<br>”;
    ++$x;
    }

    As you can see, I can use the variable $x from my loop to print out the names in the array. You may have noticed I am also using the variable $namenumber which is always 1 greater than $x. This is because the array numbering starts from 0, so to number the names correctly in the output I must add one to the actual value.