Category: PHP

  • PHP Constants

    What is Constant in PHP

    A constant is a name or an identifier for a fixed value. Constant are like variables, except that once they are defined, they cannot be undefined or changed (except magic constants).

    Constants are very useful for storing data that doesn’t change while the script is running. Common examples of such data include configuration settings such as database username and password, website’s base URL, company name, etc.

    Constants are defined using PHP’s define() function, which accepts two arguments: the name of the constant, and its value. Once defined the constant value can be accessed at any time just by referring to its name. Here is a simple example:

    Example

    <?php
    // Defining constant
    define("SITE_URL", "https://www.tutorialrepublic.com/");
     
    // Using constant
    echo 'Thank you for visiting - ' . SITE_URL;
    ?>

    The output of the above code will be:

    The PHP echo statement is often used to display or output data to the web browser. We will learn more about this statement in the next chapter.

    Tip: By storing the value in a constant instead of a variable, you can make sure that the value won’t get changed accidentally when your application runs.


    Naming Conventions for PHP Constants

    Name of constants must follow the same rules as variable names, which means a valid constant name must starts with a letter or underscore, followed by any number of letters, numbers or underscores with one exception: the $ prefix is not required for constant names.

  • PHP Variables

    What is Variable in PHP

    Variables are used to store data, like string of text, numbers, etc. Variable values can change over the course of a script. Here’re some important things to know about variables:

    • In PHP, a variable does not need to be declared before adding a value to it. PHP automatically converts the variable to the correct data type, depending on its value.
    • After declaring a variable it can be reused throughout the code.
    • The assignment operator (=) used to assign value to a variable.

    In PHP variable can be declared as: $var_name = value;

    Example

    <?php
    // Declaring variables
    $txt = "Hello World!";
    $number = 10;
     
    // Displaying variables value
    echo $txt;  // Output: Hello World!
    echo $number; // Output: 10
    ?>

    In the above example we have created two variables where first one has assigned with a string value and the second has assigned with a number. Later we’ve displayed the variables values in the browser using the echo statement. The PHP echo statement is often used to output data to the browser. We will learn more about this in upcoming chapter.

    Naming Conventions for PHP Variables

    These are the following rules for naming a PHP variable:

    • All variables in PHP start with a $ sign, followed by the name of the variable.
    • A variable name must start with a letter or the underscore character _.
    • A variable name cannot start with a number.
    • A variable name in PHP can only contain alpha-numeric characters and    underscores (A-z0-9, and _).
    • A variable name cannot contain spaces.
  • PHP Syntax

    Standard PHP Syntax

    A PHP script starts with the <?php and ends with the ?> tag.

    The PHP delimiter <?php and ?> in the following example simply tells the PHP engine to treat the enclosed code block as PHP code, rather than simple HTML.

    Example

    <?php
    // Some code to be executed
    echo "Hello, world!";
    ?>

    Every PHP statement end with a semicolon (;) — this tells the PHP engine that the end of the current statement has been reached.


    Embedding PHP within HTML

    PHP files are plain text files with .php extension. Inside a PHP file you can write HTML like you do in regular HTML pages as well as embed PHP codes for server side execution.

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>A Simple PHP File</title>
    </head>
    <body>
        <h1><?php echo "Hello, world!"; ?></h1>
    </body>
    </html>

    The above example shows how you can embed PHP codes within HTML to create well-formed dynamic web pages. If you view the source code of the resulting web page in your browser, the only difference you will see is the PHP code <?php echo "Hello, world!"; ?> has been replaced with the output “Hello, world!”.

    What happend here is? when you run this code the PHP engine exacuted the instructions between the <?php … ?> tags and leave rest of the thing as it is. At the end the web server send the final output back to your browser which is completely in HTML.


    PHP Comments

    A comment is simply text that is ignored by the PHP engine. The purpose of comments is to make the code more readable. It may help other developer (or you in the future when you edit the source code) to understand what you were trying to do with the PHP.

    PHP support single-line as well as multi-line comments. To write a single-line comment either start the line with either two slashes (//) or a hash symbol (#). For example:

    Example

    <?php
    // This is a single line comment
    # This is also a single line comment
    echo "Hello, world!";
    ?>

    However to write multi-line comments, start the comment with a slash followed by an asterisk (/*) and end the comment with an asterisk followed by a slash (*/), like this:

    Example

    <?php
    /*
    This is a multiple line comment block
    that spans across more than
    one line
    */
    echo "Hello, world!";
    ?>

    Case Sensitivity in PHP

    Variable names in PHP are case-sensitive. As a result the variables $color$Color and $COLOR are treated as three different variables.

    Example

    <?php
    // Assign value to variable
    $color = "blue";
     
    // Try to print variable value
    echo "The color of the sky is " . $color . "<br>";
    echo "The color of the sky is " . $Color . "<br>";
    echo "The color of the sky is " . $COLOR . "<br>";
    ?>

    If you try to run the above example code it will only display the value of the variable $color and produce the “Undefined variable” warning for the variable $Color and $COLOR.

    However the keywords, function and classes names are case-insensitive. As a result calling the gettype() or GETTYPE() produce the same result.

    Example

    <?php
    // Assign value to variable
    $color = "blue";
     
    // Get the type of a variable
    echo gettype($color) . "<br>";
    echo GETTYPE($color) . "<br>";
    ?>

    If you try to run the above example code both the functions gettype() and GETTYPE() gives the same output, which is: string.

  • PHP Getting Started

    Getting Started with PHP

    Here, you will learn how easy it is to create dynamic web pages using PHP. Before begin, be sure to have a code editor and some working knowledge of HTML and CSS.

    If you’re just starting out in web development, start learning from here »

    Well, let’s get straight into it.

    Setting Up a Local Web Server

    PHP script execute on a web server running PHP. So before you start writing any PHP program you need the following program installed on your computer.

    • The Apache Web server
    • The PHP engine
    • The MySQL database server

    You can either install them individually or choose a pre-configured package for your operating system like Linux and Windows. Popular pre-configured package are XAMPP and WampServer.

    WampServer is a Windows web development environment. It allows you to create web applications with Apache2, PHP and a MySQL database. It will also provide the MySQL administrative tool PhpMyAdmin to easily manage your databases using a web browser.

    The official website for downloading and installation instructions for the WampServer: http://www.wampserver.com/en/


    Creating Your First PHP Script

    Now that you have successfully installed WampServer on your computer. In this section we will create a very simple PHP script that displays the text “Hello, world!” in the browser window.

    Ok, click on the WampServer icon somewhere on your Windows task bar and select the “www directory”. Alternatively, you can access the “www” directory through navigating the C:\wamp\www. Create a subdirectory in “www” directory let’s say “project”.

    Now open up your favorite code editor and create a new PHP file then type the following code:

    Example

    <?php
    // Display greeting message
    echo "Hello, world!";
    ?>

    Now save this file as “hello.php” in your project folder (located at C:\wamp\www\project), and view the result in your browser through visiting this URL: http://localhost/project/hello.php.

    Alternatively, you can access the “hello.php” file through selecting the localhost option and then select the project folder from the WampSever menu on the taskbar.

    PHP can be embedded within a normal HTML web page. That means inside your HTML document you can write the PHP statements, as demonstrated in the follwoing example:

    Example

    <!DOCTYPE HTML>
    <html>
    <head>
        <title>PHP Application</title>
    </head>
    <body>
    <?php
    // Display greeting message
    echo 'Hello World!';
    ?>
    </body>
    </html>

    You will learn what each of these statements means in upcoming chapters.

  • PHP Tutorial

    PHP stands for Hypertext Preprocessor. PHP is a very popular and widely-used open source server-side scripting language to write dynamically generated web pages. PHP was originally created by Rasmus Lerdorf in 1994. It was initially known as Personal Home Page.

    PHP scripts are executed on the server and the result is sent to the web browser as plain HTML. PHP can be integrated with the number of popular databases, including MySQL, PostgreSQL, Oracle, Microsoft SQL Server, Sybase, and so on. The current major version of PHP is 7. All of the code in this tutorial has been tested and validated against the most recent release of PHP 7.

    PHP is very powerful language yet easy to learn and use. So bookmark this website and continued on.

    Tip: Our PHP tutorial will help you to learn the fundamentals of the PHP scripting language, from the basic to advanced topics step-by-step. If you’re a beginner, start with the basics and gradually move forward by learning a little bit every day.


    What You Can Do with PHP

    There are lot more things you can do with PHP.

    • You can generate pages and files dynamically.
    • You can create, open, read, write and close files on the server.
    • You can collect data from a web form such as user information, email, phone no, etc.
    • You can send emails to the users of your website.
    • You can send and receive cookies to track the visitor of your website.
    • You can store, delete, and modify information in your database.
    • You can restrict unauthorized access to your website.
    • You can encrypt data for safe transmission over internet.

    The list does not end here, there are many other interesting things that you can do with PHP. You will learn about all of them in detail in upcoming chapters.


    Advantages of PHP over Other Languages

    If you’re familiar with other server-side languages like ASP.NET or Java, you might be wondering what makes PHP so special. There are several advantages why one should choose PHP.

    • Easy to learn: PHP is easy to learn and use. For beginner programmers who just started out in web development, PHP is often considered as the preferable choice of language to learn.
    • Open source: PHP is an open-source project. It is developed and maintained by a worldwide community of developers who make its source code freely available to download and use.
    • Portability: PHP runs on various platforms such as Microsoft Windows, Linux, Mac OS, etc. and it is compatible with almost all servers used today such Apache, IIS, etc.
    • Fast Performance: Scripts written in PHP usually execute or runs faster than those written in other scripting languages like ASP, Ruby, Python, Java, etc.
    • Vast Community: Since PHP is supported by the worldwide community, finding help or documentation related to PHP online is extremely easy.

    Tip: Do you know some huge websites like Facebook, Yahoo, Flickr, and Wikipedia are built using PHP. Most of the major content management systems (CMS), such as WordPress, Drupal, Joomla and Magento are also built in PHP.


    What This Tutorial Covers

    This PHP tutorial series covers all the fundamental programming concepts, including data types, operators, creating and using variables, generating outputs, structuring your code to make decisions in your programs or to loop over the same block of code multiple times, creating and manipulating strings and arrays, defining and calling functions, and so on.

    Once you’re comfortable with the basics, you’ll move on to next level that explains the concept file system, sessions and cookies, dates and times, as well as how to send email from your script, handling and validating forms, perform data filtration and handling errors in PHP.

    Finally, you’ll explore some advanced concepts like classes and objects, parsing JSON data, pattern matching with regular expressions, exception handling as well as how to use PHP to manipulate data in MySQL database and create useful features like user login system, Ajax search, etc.

    Tip: Every chapter in this tutorial contains lots of real-world examples that you can try and test using an online editor. These examples will help you to better understand the concept or topic. It also contains smart workarounds as well as useful tips and important notes.