Blog

  • Hello world!

    Welcome to WordPress. This is your first post. Edit or delete it, then start writing!

  • Atoms and Molecules

    Atoms and Molecules explained in simple terms for students and learners of all ages.

    ]]>

  • States of Matter

    States of Matter explained in simple terms for students and learners of all ages.

    ]]>

  • What is Force?

    What is Force? explained in simple terms for students and learners of all ages.

    ]]>

  • Laws of Motion

    Laws of Motion explained in simple terms for students and learners of all ages.

    ]]>

  • PHP Exercises, Practice, Solution

    What is PHP?

    PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

    The best way we learn anything is by practice and exercise questions. We have started this section for those (beginner to intermediate) who are familiar with PHP.

    Hope, these exercises help you to improve your PHP coding skills. Currently, following sections are available, we are working hard to add more exercises. Happy Coding!

    Note: It’s fine if you are playing around with PHP codes with the help of an online PHP editor, to enjoy a full-fledged PHP environment (since online editors have several caveats, e.g. embedding PHP within HTML) up and running on your own machine is much better of an option to learn PHP. Please read our installing PHP on Windows and Linux if you are unfamiliar to PHP installation.

    List of PHP Exercises :

    • PHP Basic : 102 Exercises with Solution
    • PHP Basic Algorithm: 136 Exercises with Solution
    • PHP Error and Exception Handling [ 10 exercises with solution ]
    • PHP File Handling [ 18 exercises with solution ]
    • PHP Cookies and Sessions Exercises Practice Solution [ 16 exercises with solution ]
    • PHP OOP Exercises Practice Solution [ 19 exercises with solution ]
    • PHP arrays : 59 Exercises with Solution
    • PHP for loop : 38 Exercises with Solution
    • PHP functions : 6 Exercises with Solution
    • PHP classes : 7 Exercises with Solution
    • PHP Regular Expression : 7 Exercises with Solution
    • PHP Date : 28 Exercises with Solution
    • PHP String : 26 Exercises with Solution
    • PHP Math : 12 Exercises with Solution
    • PHP JSON : 4 Exercises with Solution
    • PHP Searching and Sorting Algorithm : 17 Exercises with Solution
    • More to Come !

    PHP Challenges :

    • PHP Challenges: Part -1 [ 1- 25]
    • More to come

    Note : You may accomplish the same task (solution of the exercises) in various ways, therefore the ways described here are not the only ways to do stuff. Rather, it would be great, if this helps you anyway to choose your own methods.

    [ Want to contribute to PHP exercises? Send your code (attached with a .zip file) to us at w3resource[at]yahoo[dot]com. Please avoid copyrighted materials.]

    List of Exercises with Solutions :

    • HTML CSS Exercises, Practice, Solution
    • JavaScript Exercises, Practice, Solution
    • jQuery Exercises, Practice, Solution
    • jQuery-UI Exercises, Practice, Solution
    • CoffeeScript Exercises, Practice, Solution
    • Twitter Bootstrap Exercises, Practice, Solution
    • C Programming Exercises, Practice, Solution
    • C# Sharp Programming Exercises, Practice, Solution
    • PHP Exercises, Practice, Solution
    • Python Exercises, Practice, Solution
    • Java Exercises, Practice, Solution
    • SQL Exercises, Practice, Solution
    • MySQL Exercises, Practice, Solution
    • PostgreSQL Exercises, Practice, Solution
    • SQLite Exercises, Practice, Solution
    • MongoDB Exercises, Practice, Solution
  • PHP error handling

    Description

    PHP has a number of functions for handling as well as reporting errors. Besides, you can define your own way of handling and reporting errors. In this and subsequent pages we are going to discuss installation, runtime configuration, predefined constants and functions relating to PHP error handling and reporting.

    Installation and configuration

    In PHP 5, you don’t need any external library, and you don’t need any installation in addition to error handling and reporting.

    Configuration settings for PHP Error handling and reporting are available in php.ini file, which is located in the php installation folder of your system.

    Following is a list of error handling settings, there descriptions, default value and where they can be changed (Changeable).

    For reference, settings of any PHP configuration can be changed in various ways – using ini_set(), in WINDOWS registry, in php.ini, in .htaccess or in httpd.conf. PHP_INI_ALL refers that the related configuration can be changed in any the aforementioned ways. PHP_INI_SYSTEM refers the entry can be set in php.ini or httpd.conf.

    NameTypeDescriptionDefaultChangeable
    error_reportingintegerSet the error reporting level.NULLPHP_INI_ALL
    display_errorsstringDetermines if errors are displayed or hidden.“1” PHP_INI_ALL
    display_startup_errorsbooleanEven if display_errors is on, hides errors that occur during PHP’s startup sequence. Keep it off when online.“0”PHP_INI_ALL
    log_errorsbooleanSpecifies if script error messages should be logged to the server’s error log.“0”PHP_INI_ALL
    log_errors_max_lenintegerSpecifies the maximum length of log_errors in bytes.“1024”PHP_INI_ALL
    ignore_repeated_errors booleanDo not log repeated messages.“0”PHP_INI_ALL
    ignore_repeated_sourcebooleanIgnore source of message when ignoring repeated messages.“0”PHP_INI_ALL
    report_memleaksbooleanIf set to Off, memory leaks (the program is unable to release memory it has occupied) will not be displayed.“1”PHP_INI_ALL
    track_errorsbooleanIf enabled, variable $php_errormsg will always hold the last error message.“0”PHP_INI_ALL
    html_errorsbooleanTurns HTML tags off in error messages.“1” PHP_INI_ALL
    xmlrpc_errorsbooleanFormats errors as XML-RPC error message, turning normal error reporting off.“0”PHP_INI_SYSTEM
    xmlrpc_error_numberintegerUsed as the value of the XML-RPC fault Code element.“0”PHP_INI_ALL
    docref_rootstringFormat of a new error which contains a reference to a page describing the error or function causing the error.“”PHP_INI_ALL
    docref_extstringSpecifies the file extension of the reference page (as mentioned in docref_root).“”PHP_INI_ALL
    error_prepend_stringstringString to output before an error message.NULLPHP_INI_ALL
    error_append_stringstringString to output after an error message.NULLPHP_INI_ALL
    error_logstringName of the file where script errors should be logged.NULLPHP_INI_ALL

    PHP error handling – predefined constants

    DescriptionList of predefined constants used in PHP 5 for error handling.

    Predefined constants

    Here is a list of the predefined constants used in PHP 5 for error handling : 

    NameTypeDescriptionvalue
    E_ERRORintegerExecution of the script comes to a halt. An example is memory allocation problem.1
    E_WARNINGintegerExecution of the script is not halted, warnings generated. 2
    E_PARSE integerParse errors generated by parsers during compilation.4
    E_NOTICE integerRun-time notices which indicated that may be an error took place but may also be a normal course of action.8
    E_CORE_ERRORintegerFatal errors that occur during the initial startup of PHP.16
    E_CORE_WARNINGintegerWarnings (execution of the script is not halted) that occur during PHP’s initial startup.32
    E_COMPILE_ERROR  integerFatal compile-time errors.64
    E_COMPILE_WARNING  integerCompile-time warnings, execution of the script is not halted.128
    E_USER_ERROR  integerUser-generated error message. 256
    E_USER_WARNINGintegerUser-generated warning message. 512
    E_USER_NOTICEintegerSame as E_NOTICE. The only difference is, trigger_error() function is used here to generate the error message.1024 
    E_STRICTinteger User-generated notice message.2048
    E_RECOVERABLE_ERROR integerCatchable fatal error.4096
    E_DEPRECATED integerRun-time notices. 8192
    E_USER_DEPRECATED integerUser-generated warning message.16384
    E_ALL integerAll errors and warnings, as supported. Exception level E_STRICT.30719

    All these constants are available in  php.ini of your PHP installation folder.

  • Cookies in PHP

    What is a cookie

    Cookies are used to store the information of a web page in a remote browser, so that when the same user comes back to that page, that information can be retrieved from the browser itself.

    In this tutorial, we will discuss how to use Cookies in PHP. We have several examples in this tutorial which will help you to understand the concept and use of a cookie.

    Uses of cookie

    Cookies are often used to perform following tasks:

    • Session management: Cookies are widely used to manage user sessions. For example, when you use an online shopping cart, you keep adding items in the cart and finally when you checkout, all of those items are added to the list of items you have purchased. This can be achieved using cookies.
    •  
    • User identification: Once a user visits a webpage, using cookies, that user can be remembered. And later on, depending upon the search/visit pattern of the user, content which the user likely to be visited are served. A good example of this is ‘Retargetting’. A concept used in online marketing, where depending upon the user’s choice of content, advertisements of the relevant product, which the user may buy, are served.
    •  
    • Tracking / Analytics: Cookies are used to track the user. Which, in turn, is used to analyze and serve various kind of data of great value, like location, technologies (e.g. browser, OS) form where the user visited, how long (s)he stayed on various pages etc.

    How to create a cookie in PHP

    PHP has a setcookie() function to send a cookie. We will discuss this function in detail now.

    Usage:

    setcookie(name, value, expire, path, domain, secure, httponly)
    

    Copy

    Parameters:

    setcookie() has several parameters. Following table discusses those.

    ParameterDescriptionWhich type of data
    nameName of the cookie.String
    valueValue of the cookie, stored in clients computer.String
    expireUnix timestamp, i.e. number of seconds since January 1st, 1970 (called as Unix Epoch).Integer
    pathServer path in which the cookie will be available.String
    domainTo which domain the cookie is available.String
    secureIf set true, the cookie is available over a secure connection only.Boolean
    httponlyIf set true, the cookie is available over HTTP protocol only. Scripting languages like JavaScript won’t be able to access the cookie.Boolean

    setcookie() returns boolean.

    Example:

    Following example shows how to create a cookie in PHP. Code first and then some explanation.

    <?php
    $cookie_value = "w3resource tutorials";
    setcookie("w3resource", $cookie_value, time()+3600, "/home/your_usename/", "example.com", 1, 1);
    if (isset($_COOKIE['cookie']))
    echo $_COOKIE["w3resource"];
    ?>
    

    Copy

    So, what does the code above does? The first parameter sets the name of the cookie as ‘w3resource’, the second parameter sets the value as ‘w3resource tutorials’, the third parameter states that the cookie will be expired after 3600 seconds (note the way it has been declared, we use time() and then add the number of seconds we wish the cookie must be expired after), the fourth parameter sets path on the server ‘/home/your_name’ where your_name may be an username, so it directs the home directory of a user, the fifth and sixth parameter is set to 1, i.e. true, so the cookie is available over secure connections only and it is available on HTTP protocol only.

    echo $_COOKIE["w3resource"]; simply prints the cookie value. This way you can retrieve a cookie value.

    Output:

    w3resource tutorials

    How to create a cookie without urlencoding the cookie value

    The setcookie() sends a cookie by urlencoding the cookie value. If you want to send a cookie without urlencoding the cookie value, you have to use setrawcookie().

    This function has all the parameters which setcookie() has, and the return value is also boolean.

    PHP $_COOKIE autoglobal

    If a cookie is successfully sent to you from the client, it is available in $_COOKIE, which is automatically global in PHP, if the variables_order directive in php.ini is set to C.

    The following code shows how to use $_COOKIE.

    <?php
    $cookie_value = "w3resource tutorials";
    setcookie("w3resource", $cookie_value, time()+3600, "/home/your_usename/", "example.com", 1, 1);
    echo 'Hi ' . htmlspecialchars($_COOKIE["w3resource"]);
    ?>
    

    Copy

    If you wish to retreive all the cookies, you may use the following command

    <?php
    print_r($_COOKIE);
    ?>
    

    Copy

    headers already sent problem because of cookies

    PHP Cookies are part of the HTTP header. Therefore, in a PHP script, if it is not set before any another output is sent to the browser, you will get a warning like “…headers already sent….”.

    To get rid of the problem, you may use “Output buffering functions”. Following code shows how to add an output buffering function.

    <?php
    ob_start(); //at the begining of the php script
    //your code goes here
    //add these two lines at the end of the script
    $stuff = ob_get_clean(); 
    echo $stuff;
    ?>
    

    Copy

    How to delete a cookie

    To delete a cookie value, you may set the expiry time of the cookie in the past. In the following code snippet, cookie expiry time is set one hour before.

    <?php
    $cookie_value = "w3resource tutorials";
    setcookie("w3resource", $cookie_value, time()-3600, "/home/your_usename/", "example.com", 1, 1);
    ?>
    

    Copy

    Javascript cookies vs php cookies

    This may confuse you if you are just starting out with web programming. But in practice, Cookies are defined by RFC 2965. It is a standard which can be used any programming language. It has nothing to do with PHP vs JavaScript. In PHP, as we have seen in the first example of this tutorial, that cookies can be set such a way that it can’t be accessed by client side JavaScript, but that is a programming feature only.

    Cookies vs Sessions

    Both cookies and sessions are used for storing persistent data. But there are differences for sure.

    Sessions are stored on server side. Cookies are on the client side.

    Sessions are closed when the user closes his browser. For cookies, you can set time that when it will be expired.

    Sessions are safe that cookies. Because, since stored on client’s computer, there are ways to modify or manipulate cookies.

    Hopefully, this tutorial about PHP cookies is useful for you. Let us know if you have questions or suggestions.

  • File upload in PHP

    Description

    In this page, we will discuss how file uploading is performed using PHP. For uploading files using PHP, we need to perform following tasks –

    1. Set up an html page with a form using which we will upload the file.
    2. Setup a PHP script to upload the file to the server as well as move the file to it’s destination.
    3. Inform the user whether the upload was successful or not.

    Code :

    <html>
    <body>
    <form action="upload_file.php" method="post" enctype="multipart/form-data">
    <label for="file">Filename:</label>
    <input type="file" name="file" id="file" size="20" /><br />
    <input type="submit" name="submit" value="Submit" />
    </form>
    </body>
    </html>
    <?php
    if (file_exists("upload/" . $_FILES["file"]["name"]))
    {
    echo $_FILES["file"]["name"] . " already exists. ";
    }
    else
    {
    move_uploaded_file($_FILES["file"]["tmp_name"],"upload/" . $_FILES["file"]["name"]);
    echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
    }
    ?>

    Copy

    Explanation

    Code  Explanation: $_FILES[“uploaded_file”][“name”] The original name of the file uploaded from the user’s machine. $_FILES[“uploaded_file”][“type”] The MIME type of the uploaded file. You can use different types for test files, images and video. $_FILES[“uploaded_file”][“size”] The size of the uploaded file in bytes. $_FILES[“uploaded_file”][“tmp_name”] The location in which the file is temporarily stored on the server. $_FILES[“uploaded_file”][“error”] An error code if  the file upload fails.

    This way you can upload files to a web server. We encourage you to copy the codes above and try it on your computer or a web server.

  • PHP mail function

    Description

    The mail() function is used to send a mail.

    Version:

    (PHP 4 and above)

    Syntax:mail(to, subject, message, extra headers, additional parameters)

    Parameter:

    NameDescriptionRequired /
    Optional
    Type
    toMail address to which you want to send mail RequiredString
    subjectSubject of the mail RequiredString
    messageMessage to be sent with the mail. Each line of the message should be separated with a LF (\n). Lines should not be larger than 70 characters.RequiredString
    extra headersAdditional headers like from, CC, BCC. If more than one additional headers are used, they must be separated with CRLF (Carriage return line feed), i.e. new line. Optionalstring
    additional parametersAdditional parameters like –  the envelope sender address when using sendmail with the -f sendmail option, can be used using this parameter. Optionalstring

    Return value:

    Returns true if the mail is successfully sent, otherwise, it returns false. 

    Value Type: boolean

    Example:

    <?php
    $to  = '[email protected]';
    $subject = 'Demo mail ';
    $message = 'This is a demo mail. Please reply to make sure the mail communication is okay.';
    mail($to, $subject, $message);
    ?> 

    Copy

    Send a simple mail using mail() function

    Browse view of the form for sending simple mail in php

    send-simple-mail-php

    Code:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml"><head>
    <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type" /><title>send mail in 
    php</title>
    <style type="text/css">
    li {list-style-type: none;
    font-size: 16pt;
    }
    .mail {
    margin: auto;
    padding-top: 10px;
    padding-bottom: 10px;
    width: 400px;
    background : #D8F1F8;
    border: 1px solid silver;
    }
    .mail h2 {
    margin-left: 38px;
    }
    input {
    font-size: 20pt;
    }
    input:focus, textarea:focus{
    background-color: lightyellow;
    }
    input submit {
    font-size: 12pt;
    }
    </style>
    </head>
    <body>
    <div class="mail">
    <h2>Mail us</h2>
    <ul>
    <li><form name="mail" method="POST" action="send.php"></li>
    <li>To:</li>
    <li><input type="text" name="to" /></li>
    <li>Subject:</li>
    <li><input type="text" name="subject" /></li>
    <li>Message:</li>
    <li><input type="text" name="Message" /></li>
    <li>&nbsp;</li>
    <li><input type="submit" name="submit" value="Send"/></li>
    <li>&nbsp;</li>
    </form>
    </ul>
    </div>
    </body></html>
    

    Copy

    Code of the file for handling form (code above) data :

    <?php
    $to = $_POST['to'] ;    
    $message = $_POST['Message'] ;
    mail( $to, "Mail", $message,  );
    header( "Location: http://localhost/php/simple-mail.php" );
    ?>

    Copy

    Send mail with extra headers using mail() function

    Browser view of the form for sending mail with extra headers in php 

    simple-mail-php-extra-headers

    Code:

    <!DOCTYPE html PUBLIC
    "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html
    xmlns="http://www.w3.org/1999/xhtml"><head>
    <meta content="text/html; charset=ISO-8859-1"
    http-equiv="content-type" /><title>send mail in
    php</title>
    <style type="text/css">
    li {list-style-type: none;
    font-size: 16pt;
    }
    .mail {
    margin: auto;
    padding-top: 10px;
    padding-bottom: 10px;
    width: 400px;
    background : #D8F1F8;
    border: 1px solid silver;
    }
    .mail h2 {
    margin-left: 38px;
    }
    input {
    font-size: 20pt;<
    }
    input:focus, textarea:focus{
    background-color: lightyellow;
    }
    input submit {
    font-size: 12pt;
    }
    </style>
    </head>
    <body>
    <div class="mail">
    <h2>Mail us</h2>
    <ul>
    <li><form name="mail" method="POST"
    action="send-extra.php"></li>
    <li>To:</li>
    <li><input type="text" name="to"
    /></li>
    <li>Message:</li>
    <li><input type="text" name="Message"
    /></li>
    <li>From:</li>
    <li><input type="text" name="from"
    /></li>
    <li>CC:</li>
    <li><input type="text" name="cc"
    /></li>
    <li>&nbsp;</li>
    <li><input type="submit" name="submit"
    value="Send"/></li>
    <li>&nbsp;</li>
    </form>
    </ul>
    </div>
    </body></html>
    

    Copy

    Code of the file for handling form (code above) data:

    <?php
      $to = $_POST['to'] ;    
      $message = $_POST['Message'] ;
      $from = $_POST['from'];
      $cc = $_POST['cc'];
      $headers =  "From: ".$_POST['from']."\r\n" .
    "CC: ".$_POST['cc'];
      mail( $to, "Mail", $message, $headers);
      header( "Location: http://localhost/php/simple-mail.php" );
    ?>
    

    Copy

    We encourage you to replace the value of the parameters used in the above example and test it.

    Send mail in PHP with additional parameters

    You can pass additional parameters as command line options to the program configured to be used while sending mail. Those said configurations are defined by the sendmail_path configuration. One example of using additional parameter is setting the envelope sender address with -f option.

    <?php
    mail('[email protected]', 'Demo mail', 'Testing mail communication', null,
       '-f [email protected]');
    ?> 

    Copy

    We encourage you to replace the value of the parameters used in the above example and with your’s and test it.