Author: Saim Khalid

  • Python Tutorial | Python Programming Language

    Python tutorial provides basic and advanced concepts of Python. Our Python tutorial is designed for beginners and professionals.

    Python is a simple, general purpose, high level, and object-oriented programming language.

    Python is an interpreted scripting language also. Guido Van Rossum is known as the founder of Python programming.

    Our Python tutorial includes all topics of Python Programming such as installation, control statements, Strings, Lists, Tuples, Dictionary, Modules, Exceptions, Date and Time, File I/O, Programs, etc. There are also given Python interview questions to help you better understand Python Programming.

    What is Python

    Python is a general-purpose, dynamic, high-level, and interpreted programming language. It supports Object Oriented programming approach to develop applications. It is simple and easy to learn and provides lots of high-level data structures.

    Python is an easy-to-learn yet powerful and versatile scripting language, which makes it attractive for Application Development.

    With its interpreted nature, Python’s syntax and dynamic typing make it an ideal language for scripting and rapid application development.

    Python supports multiple programming patterns, including object-oriented, imperative, and functional or procedural programming styles.

    Python is not intended to work in a particular area, such as web programming. It is a multipurpose programming language because it can be used with web, enterprise, 3D CAD, etc.

    We don’t need to use data types to declare variable because it is dynamically typed, so we can write a=10 to assign an integer value in an integer variable.

    Python makes development and debugging fast because no compilation step is included in Python development, and the edit-test-debug cycle is very fast.

    Python has many web-based assets, open-source projects, and a vibrant community. Learning the language, working together on projects, and contributing to the Python ecosystem are all made very easy for developers.

    Because of its straightforward language framework, Python is easier to understand and write code in. This makes it a fantastic programming language for novices. Additionally, it assists seasoned programmers in writing clearer, error-free code.

    Python is an open-source, cost-free programming language. It is utilized in several sectors and disciplines as a result.

    In Python, code readability and maintainability are important. As a result, even if the code was developed by someone else, it is easy to understand and adapt by some other developer.

    Python has many third-party libraries that can be used to make its functionality easier. These libraries cover many domains, for example, web development, scientific computing, data analysis, and more.

    Python Basic Syntax

    There is no use of curly braces or semicolon in Python programming language. It is English-like language. But Python uses the indentation to define a block of code. Indentation is nothing but adding whitespace before the statement when it is needed. For example –

    def func():  
    
           statement 1  
    
           statement 2  
    
           …………………  
    
           …………………  
    
             statement N

    In the above example, the statements that are the same level to the right belong to the function. Generally, we can use four whitespaces to define indentation.

    Instead of Semicolon as used in other languages, Python ends its statements with a NewLine character.

    Python is a case-sensitive language, which means that uppercase and lowercase letters are treated differently. For example, ‘name’ and ‘Name’ are two different variables in Python.

    In Python, comments can be added using the ‘#’ symbol. Any text written after the ‘#’ symbol is considered a comment and is ignored by the interpreter. This trick is useful for adding notes to the code or temporarily disabling a code block. It also helps in understanding the code better by some other developers.

    ‘If’, ‘otherwise’, ‘for’, ‘while’, ‘try’, ‘except’, and ‘finally’ are a few reserved keywords in Python that cannot be used as variable names. These terms are used in the language for particular reasons and have fixed meanings. If you use these keywords, your code may include errors, or the interpreter may reject them as potential new Variables.

    Why learn Python?

    Python provides many useful features to the programmer. These features make it the most popular and widely used language. We have listed below few-essential features of Python.

    • Easy to use and Learn: Python has a simple and easy-to-understand syntax, unlike traditional languages like C, C++, Java, etc., making it easy for beginners to learn.
    • Expressive Language: It allows programmers to express complex concepts in just a few lines of code or reduces Developer’s Time.
    • Interpreted Language: Python does not require compilation, allowing rapid development and testing. It uses Interpreter instead of Compiler.
    • Object-Oriented Language: It supports object-oriented programming, making writing reusable and modular code easy.
    • Open Source Language: Python is open source and free to use, distribute and modify.
    • Extensible: Python can be extended with modules written in C, C++, or other languages.
    • Learn Standard Library: Python’s standard library contains many modules and functions that can be used for various tasks, such as string manipulation, web programming, and more.
    • GUI Programming Support: Python provides several GUI frameworks, such as Tkinter and PyQt, allowing developers to create desktop applications easily.
    • Integrated: Python can easily integrate with other languages and technologies, such as C/C++, Java, and . NET.
    • Embeddable: Python code can be embedded into other applications as a scripting language.
    • Dynamic Memory Allocation: Python automatically manages memory allocation, making it easier for developers to write complex programs without worrying about memory management.
    • Wide Range of Libraries and Frameworks: Python has a vast collection of libraries and frameworks, such as NumPy, Pandas, Django, and Flask, that can be used to solve a wide range of problems.
    • Versatility: Python is a universal language in various domains such as web development, machine learning, data analysis, scientific computing, and more.
    • Large Community: Python has a vast and active community of developers contributing to its development and offering support. This makes it easy for beginners to get help and learn from experienced developers.
    • Career Opportunities: Python is a highly popular language in the job market. Learning Python can open up several career opportunities in data science, artificial intelligence, web development, and more.
    • High Demand: With the growing demand for automation and digital transformation, the need for Python developers is rising. Many industries seek skilled Python developers to help build their digital infrastructure.
    • Increased Productivity: Python has a simple syntax and powerful libraries that can help developers write code faster and more efficiently. This can increase productivity and save time for developers and organizations.
    • Big Data and Machine Learning: Python has become the go-to language for big data and machine learning. Python has become popular among data scientists and machine learning engineers with libraries like NumPy, Pandas, Scikit-learn, TensorFlow, and more.

    Where is Python used?

    Python is a general-purpose, popular programming language, and it is used in almost every technical field. The various areas of Python use are given below.

    • Data Science: Data Science is a vast field, and Python is an important language for this field because of its simplicity, ease of use, and availability of powerful data analysis and visualization libraries like NumPy, Pandas, and Matplotlib.
    • Desktop Applications: PyQt and Tkinter are useful libraries that can be used in GUI – Graphical User Interface-based Desktop Applications. There are better languages for this field, but it can be used with other languages for making Applications.
    • Console-based Applications: Python is also commonly used to create command-line or console-based applications because of its ease of use and support for advanced features such as input/output redirection and piping.
    • Mobile Applications: While Python is not commonly used for creating mobile applications, it can still be combined with frameworks like Kivy or BeeWare to create cross-platform mobile applications.
    • Software Development: Python is considered one of the best software-making languages. Python is easily compatible with both from Small Scale to Large Scale software.
    • Artificial Intelligence: AI is an emerging Technology, and Python is a perfect language for artificial intelligence and machine learning because of the availability of powerful libraries such as TensorFlow, Keras, and PyTorch.
    • Web Applications: Python is commonly used in web development on the backend with frameworks like Django and Flask and on the front end with tools like JavaScript and HTML.
    • Enterprise Applications: Python can be used to develop large-scale enterprise applications with features such as distributed computing, networking, and parallel processing.
    • 3D CAD Applications: Python can be used for 3D computer-aided design (CAD) applications through libraries such as Blender.
    • Machine Learning: Python is widely used for machine learning due to its simplicity, ease of use, and availability of powerful machine learning libraries.
    • Computer Vision or Image Processing Applications: Python can be used for computer vision and image processing applications through powerful libraries such as OpenCV and Scikit-image.
    • Speech Recognition: Python can be used for speech recognition applications through libraries such as SpeechRecognition and PyAudio.
    • Scientific computing: Libraries like NumPy, SciPy, and Pandas provide advanced numerical computing capabilities for tasks like data analysis, machine learning, and more.
    • Education: Python’s easy-to-learn syntax and availability of many resources make it an ideal language for teaching programming to beginners.
    • Testing: Python is used for writing automated tests, providing frameworks like unit tests and pytest that help write test cases and generate reports.
    • Gaming: Python has libraries like Pygame, which provide a platform for developing games using Python.
    • IoT: Python is used in IoT for developing scripts and applications for devices like Raspberry Pi, Arduino, and others.
    • Networking: Python is used in networking for developing scripts and applications for network automation, monitoring, and management.
    • DevOps: Python is widely used in DevOps for automation and scripting of infrastructure management, configuration management, and deployment processes.
    • Finance: Python has libraries like Pandas, Scikit-learn, and Statsmodels for financial modeling and analysis.
    • Audio and Music: Python has libraries like Pyaudio, which is used for audio processing, synthesis, and analysis, and Music21, which is used for music analysis and generation.
    • Writing scripts: Python is used for writing utility scripts to automate tasks like file operations, web scraping, and data processing.

    Python Popular Frameworks and Libraries

    Python has wide range of libraries and frameworks widely used in various fields such as machine learning, artificial intelligence, web applications, etc. We define some popular frameworks and libraries of Python as follows.

    • Web development (Server-side) – Django Flask, Pyramid, CherryPy
    • GUIs based applications – Tk, PyGTK, PyQt, PyJs, etc.
    • Machine Learning – TensorFlow, PyTorch, Scikit-learn, Matplotlib, Scipy, etc.
    • Mathematics – Numpy, Pandas, etc.
    • BeautifulSoup: a library for web scraping and parsing HTML and XML
    • Requests: a library for making HTTP requests
    • SQLAlchemy: a library for working with SQL databases
    • Kivy: a framework for building multi-touch applications
    • Pygame: a library for game development
    • Pytest: a testing framework for Python
    • Django REST framework: a toolkit for building RESTful APIs
    • FastAPI: a modern, fast web framework for building APIs
    • Streamlit: a library for building interactive web apps for machine learning and data science
    • NLTK: a library for natural language processing

    Python Conditional Statements

    Conditional statements help us to execute a particular block for a particular condition. In this tutorial, we will learn how to use conditional expression to execute a different block of statements. Python provides if and else keywords to set up logical conditions. The elif keyword is also used as a conditional statement.

    Example code for if..else statement

    x = 10  
    
    y = 5  
    
      
    
    if x > y:  
    
        print("x is greater than y")  
    
    else:  
    
        print("y is greater than or equal to x")

    In the above code, we have two variables, x, and y, with 10 and 5, respectively. Then we used an if..else statement to check if x is greater than y or vice versa. If the first condition is true, the statement “x is greater than y” is printed. If the first condition is false, the statement “y is greater than or equal to x” is printed instead.

    The if keyword checks the condition is true and executes the code block inside it. The code inside the else block is executed if the condition is false. This way, the if..else statement helps us to execute different blocks of code based on a condition.

    We will learn about this in more detail in the further article for the Python tutorial.

    Python Loops

    Sometimes we may need to alter the flow of the program. The execution of a specific code may need to be repeated several times. For this purpose, the programming languages provide various loops capable of repeating some specific code several times. Consider the following tutorial to understand the statements in detail.

    Python For Loop

    fruits = ["apple", "banana", "cherry"]  
    
    for x in fruits:  
    
    print(x)

    Python While Loop

    i = 1   
    
    while i < 6:   
    
    print(i)   
    
    i += 1

    In the above example code, we have demonstrated using two types of loops in Python – For loop and While loop.

    The For loop is used to iterate over a sequence of items, such as a list, tuple, or string. In the example, we defined a list of fruits and used a for loop to print each fruit, but it can also be used to print a range of numbers.

    The While loop repeats a code block if the specified condition is true. In the example, we have initialized a variable i to 1 and used a while loop to print the value of i until it becomes greater than or equal to 6. The i += 1 statement is used to increment the value of i in each iteration.

    We will learn about them in the tutorial in detail.

    Python Functional Programming

    This section of the Python tutorial defines some important tools related to functional programming, such as lambda and recursive functions. These functions are very efficient in accomplishing complex tasks. We define a few important functions, such as reduce, map, and filter. Python provides the functools module that includes various functional programming tools. Visit the following tutorial to learn more about functional programming.

    Recent versions of Python have introduced features that make functional programming more concise and expressive. For example, the “walrus operator”:= allows for inline variable assignment in expressions, which can be useful when working with nested function calls or list comprehensions.

    Python Function

    1. Lambda Function – A lambda function is a small, anonymous function that can take any number of arguments but can only have one expression. Lambda functions are often used in functional programming to create functions “on the fly” without defining a named function.
    2. Recursive Function – A recursive function is a function that calls itself to solve a problem. Recursive functions are often used in functional programming to perform complex computations or to traverse complex data structures.
    3. Map Function – The map() function applies a given function to each item of an iterable and returns a new iterable with the results. The input iterable can be a list, tuple, or other.
    4. Filter Function – The filter() function returns an iterator from an iterable for which the function passed as the first argument returns True. It filters out the items from an iterable that do not meet the given condition.
    5. Reduce Function – The reduce() function applies a function of two arguments cumulatively to the items of an iterable from left to right to reduce it to a single value.
    6. functools Module – The functools module in Python provides higher-order functions that operate on other functions, such as partial() and reduce().
    7. Currying Function – A currying function is a function that takes multiple arguments and returns a sequence of functions that each take a single argument.
    8. Memoization Function – Memoization is a technique used in functional programming to cache the results of expensive function calls and return the cached Result when the same inputs occur again.
    9. Threading Function – Threading is a technique used in functional programming to run multiple tasks simultaneously to make the code more efficient and faster.

    Python Modules

    Python modules are the program files that contain Python code or functions. Python has two types of modules – User-defined modules and built-in modules. A module the user defines, or our Python code saved with .py extension, is treated as a user-define module.

    Built-in modules are predefined modules of Python. To use the functionality of the modules, we need to import them into our current working program.

    Python modules are essential to the language’s ecosystem since they offer reusable code and functionality that can be imported into any Python program. Here are a few examples of several Python modules, along with a brief description of each:

    Math: Gives users access to mathematical constants and pi and trigonometric functions.

    Datetime: Provides classes for a simpler way of manipulating dates, times, and periods.

    Os – Enables interaction with the base operating system, including administration of processes and file system activities.

    Random – The random function offers tools for generating random integers and picking random items from a list.

    JSON – JSON is a data structure that can be encoded and decoded and is frequently used in online APIs and data exchange. This module allows dealing with JSON.

    Re – Supports regular expressions, a potent text-search and text-manipulation tool.

    Collections – Provides alternative data structures such as sorted dictionaries, default dictionaries, and named tuples.

    Numpy is a core toolkit for scientific computing that supports numerical operations on arrays and matrices.

    Pandas: It provides high-level data structures and operations for dealing with time series and other structured data types.

    Requests: Offers a simple user interface for web APIs and performs HTTP requests.

    Python File I/O

    Files are used to store data in a computer disk. In this tutorial, we explain the built-in file object of Python. We can open a file using Python script and perform various operations such as writing, reading, and appending. There are various ways of opening a file. We are explained with the relevant example. We will also learn to perform read/write operations on binary files.

    Python’s file input/output (I/O) system offers programs to communicate with files stored on a disc. Python’s built-in methods for the file object let us carry out actions like reading, writing, and adding data to files.

    The open() method in Python makes a file object when working with files. The name of the file to be opened and the mode in which the file is to be opened are the two parameters required by this function. The mode can be used according to work that needs to be done with the file, such as “r” for reading, “w” for writing, or “a” for attaching.

    After successfully creating an object, different methods can be used according to our work. If we want to write in the file, we can use the write() functions, and if you want to read and write both, then we can use the append() function and, in cases where we only want to read the content of the file we can use read() function.

    Binary files containing data in a binary rather than a text format may also be worked with using Python. Binary files are written in a manner that humans cannot directly understand. The rb and wb modes can read and write binary data in binary files.

    Python Exceptions

    An exception can be defined as an unusual condition in a program resulting in an interruption in the flow of the program.

    Whenever an exception occurs, the program stops the execution, and thus the other code is not executed. Therefore, an exception is the run-time errors that are unable to handle to Python script. An exception is a Python object that represents an error.

    Python exceptions are an important aspect of error handling in Python programming. When a program encounters an unexpected situation or error, it may raise an exception, which can interrupt the normal flow of the program.

    In Python, exceptions are represented as objects containing information about the error, including its type and message. The most common type of Exception in Python is the Exception class, a base class for all other built-in exceptions.

    To handle exceptions in Python, we use the try and except statements. The try statement is used to enclose the code that may raise an exception, while the except statement is used to define a block of code that should be executed when an exception occurs.

    For example, consider the following code:

    try:  
    
        x = int ( input ("Enter a number: "))  
    
        y = 10 / x  
    
        print ("Result:", y)  
    
    except ZeroDivisionError:  
    
        print ("Error: Division by zero")  
    
    except ValueError:  
    
        print ("Error: Invalid input")

    In this code, we use the try statement to attempt to perform a division operation. If either of these operations raises an exception, the matching except block is executed.

    Python also provides many built-in exceptions that can be raised in similar situations. Some common built-in exceptions include IndexErrorTypeError, and NameError. Also, we can define our custom exceptions by creating a new class that inherits from the Exception class.

    Python CSV

    A CSV stands for “comma separated values”, which is defined as a simple file format that uses specific structuring to arrange tabular data. It stores tabular data such as spreadsheets or databases in plain text and has a common format for data interchange. A CSV file opens into the Excel sheet, and the rows and columns data define the standard format.

    We can use the CSV.reader function to read a CSV file. This function returns a reader object that we can use to repeat over the rows in the CSV file. Each row is returned as a list of values, where each value corresponds to a column in the CSV file.

    For example, consider the following code:

    import csv  
    
      
    
    with open('data.csv', 'r') as file:  
    
        reader = csv.reader(file)  
    
        for row in reader:  
    
            print(row)

    Here, we open the file data.csv in read mode and create a csv.reader object using the csv.reader() function. We then iterate over the rows in the CSV file using a for loop and print each row to the console.

    We can use the CSV.writer() function to write data to a CSV file. It returns a writer object we can use to write rows to the CSV file. We can write rows by calling the writer () method on the writer object.

    For example, consider the following code:

    import csv  
    
      
    
    data = [    ['Name', 'Age', 'Country'],  
    
        ['Alice', '25', 'USA'],  
    
        ['Bob', '30', 'Canada'],  
    
        ['Charlie', '35', 'Australia']  
    
    ]  
    
      
    
    with open('data.csv', 'w') as file:  
    
        writer = csv.writer(file)  
    
        for row in data:  
    
            writer.writerow(row)

    In this program, we create a list of lists called data, where each inner list represents a row of data. We then open the file data.csv in write mode and create a CSV.writer object using the CSV.writer function. We then iterate over the rows in data using a for loop and write each row to the CSV file using the writer method.

    Python Sending Mail

    We can send or read a mail using the Python script. Python’s standard library modules are useful for handling various protocols such as PoP3 and IMAP. Python provides the smtplib module for sending emails using SMTP (Simple Mail Transfer Protocol). We will learn how to send mail with the popular email service SMTP from a Python script.

    Python Sending Emails

    Python Magic Methods

    The Python magic method is the special method that adds “magic” to a class. It starts and ends with double underscores, for example, _init_ or _str_.

    The built-in classes define many magic methods. The dir() function can be used to see the number of magic methods inherited by a class. It has two prefixes and suffix underscores in the method name.

    • Python magic methods are also known as dunder methods, short for “double underscore” methods because their names start and end with a double underscore.
    • Magic methods are automatically invoked by the Python interpreter in certain situations, such as when an object is created, compared to another object, or printed.
    • Magic methods can be used to customize the behavior of classes, such as defining how objects are compared, converted to strings, or accessed as containers.
    • Some commonly used magic methods include init for initializing an object, str for converting an object to a string, eq for comparing two objects for equality, and getitem and setitem for accessing items in a container object.

    For example, the str magic method can define how an object should be represented as a string. Here’s an example:

    class Person:  
    
        def __init__(self, name, age):  
    
            self.name = name  
    
            self.age = age  
    
          
    
        def __str__(self):  
    
            return f"{self.name} ({self.age})"

    In this example, the str method is defined to return a formatted string representation of the Person object with the person’s name and age.

    Another commonly used magic method is eq, which defines how objects should be compared for equality. Here’s an example:

    
    
    1. def __init__(self, x, y):  
    2.     self.x = x  
    3.     self.y = y  
    4.   
    5. def __eq__(self, other):  
    6.     return self.x == other.x and self.y == other.y  

    In this example, the eq method is defined to return True if two Point objects have the same x and y coordinates and False otherwise.

    Python Oops Concepts

    Everything in Python is treated as an object, including integer values, floats, functions, classes, and none. Apart from that, Python supports all oriented concepts. Below is a brief introduction to the Oops concepts of Python.

    • Classes and Objects – Python classes are the blueprints of the Object. An object is a collection of data and methods that act on the data.
    • Inheritance – An inheritance is a technique where one class inherits the properties of other classes.
    • Constructor – Python provides a special method __init__() which is known as a constructor. This method is automatically called when an object is instantiated.
    • Data Member – A variable that holds data associated with a class and its objects.
    • Polymorphism – Polymorphism is a concept where an object can take many forms. In Python, polymorphism can be achieved through method overloading and method overriding.
    • Method Overloading – In Python, method overloading is achieved through default arguments, where a method can be defined with multiple parameters. The default values are used if some parameters are not passed while calling the method.
    • Method Overriding – Method overriding is a concept where a subclass implements a method already defined in its superclass.
    • Encapsulation – Encapsulation is wrapping data and methods into a single unit. In Python, encapsulation is achieved through access modifiers, such as public, private, and protected. However, Python does not strictly enforce access modifiers, and the naming convention indicates the access level.
    • Data Abstraction: A technique to hide the complexity of data and show only essential features to the user. It provides an interface to interact with the data. Data abstraction reduces complexity and makes code more modular, allowing developers to focus on the program’s essential features.

    To read the Oops concept in detail, visit the following resources.

    • Python Oops Concepts
    • Python Objects and classes
    • Python Constructor
    • Python Inheritance
    • Python Polymorphism

    Python Advance Topics

    Python includes many advances and useful concepts that help the programmer solve complex tasks. These concepts are given below.

    Python Iterator

    An iterator is simply an object that can be iterated upon. It returns one Object at a time. It can be implemented using the two special methods, __iter__() and __next__().

    Iterators in Python are objects that allow iteration over a collection of data. They process each collection element individually without loading the entire collection into memory.

    For example, let’s create an iterator that returns the squares of numbers up to a given limit:

    class Squares:

    def __init__(self, limit):  
    
            self.limit = limit  
    
            self.n = 0  
    
      
    
        def __iter__(self):  
    
            return self  
    
      
    
        def __next__(self):  
    
            if self.n <= self.limit:  
    
                square = self.n ** 2  
    
                self.n += 1  
    
                return square  
    
            else:  
    
                raise StopIteration  
    
      
    
    numbers = Squares(5)  
    
    for n in numbers:  
    
        print(n)

    Output:0 1 4 9 16 25

    In this example, we have created a class Squares that acts as an iterator by implementing the __iter__() and __next__() methods. The __iter__() method returns the Object itself, and the __next__() method returns the next square of the number until the limit is reached.

    To learn more about the iterators, visit our Python Iterators tutorial.

    Python Generators

    Python generators produce a sequence of values using a yield statement rather than a return since they are functions that return iterators. Generators terminate the function’s execution while keeping the local state. It picks up right where it left off when it is restarted. Because we don’t have to implement the iterator protocol thanks to this feature, writing iterators is made simpler. Here is an illustration of a straightforward generator function that produces squares of numbers:

    def square_numbers(n):  
    
        for i in range(n):  
    
            yield i**2  
    
      
    
    # create a generator object  
    
    generator = square_numbers(5)  
    
      
    
    # print the values generated by the generator  
    
    for num in generator:  
    
        print(num)

    Output:0 1 4 9 16

    Python Modifiers

    Python Decorators are functions used to modify the behavior of another function. They allow adding functionality to an existing function without modifying its code directly. Decorators are defined using the @ symbol followed by the name of the decorator function. They can be used for logging, timing, caching, etc. Here’s an example of a decorator function that adds timing functionality to another function:

    import time  
    
    def time_it(func):  
    
        def wrapper(*args, **kwargs):  
    
            start = time.time()  
    
            result = func(*args, **kwargs)  
    
            end = time.time()  
    
            print(f"{func.__name__} took {end-start:.2f} seconds to run.")  
    
            return result  
    
        return wrapper  
    
      
    
    def my_function():  
    
        time.sleep(2)  
    
        print("Function executed.")  
    
      
    
    my_function()

    In the above example, the time_it decorator function takes another function as an argument and returns a wrapper function. The wrapper function calculates the time to execute the original function and prints it to the console. The @time_it decorator is used to apply the time_it function to the my_function function. When my_function is called, the decorator is executed, and the timing functionality is added.

    Python MySQL

    Python MySQL is a powerful relational database management system. We must set up the environment and establish a connection to use MySQL with Python. We can create a new database and tables using SQL commands in Python.

    • Environment Setup: Installing and configuring MySQL Connector/Python to use Python with MySQL.
    • Database Connection: Establishing a connection between Python and MySQL database using MySQL Connector/Python.
    • Creating New Database: Creating a new database in MySQL using Python.
    • Creating Tables: Creating tables in the MySQL database with Python using SQL commands.
    • Insert Operation: Insert data into MySQL tables using Python and SQL commands.
    • Read Operation: Reading data from MySQL tables using Python and SQL commands.
    • Update Operation: Updating data in MySQL tables using Python and SQL commands.
    • Join Operation: Joining two or more tables in MySQL using Python and SQL commands.
    • Performing Transactions: Performing a group of SQL queries as a single unit of work in MySQL using Python.

    Other relative points include handling errors, creating indexes, and using stored procedures and functions in MySQL with Python.

    Python MongoDB

    MongoDB is a popular NoSQL database that stores data in JSON-like documents. It is schemaless and provides high scalability and flexibility for data storage. We can use MongoDB with Python using the PyMongo library, which provides a simple and intuitive interface for interacting with MongoDB.

    Here are some common tasks when working with MongoDB in Python:

    1. Environment Setup:Install and configure MongoDB and PyMongo library on your system.
    2. Database Connection:Connect to a MongoDB server using the MongoClient class from PyMongo.
    3. Creating a new database:Use the MongoClient Object to create a new database.
    4. Creating collections:Create collections within a database to store documents.
    5. Inserting documents: Insert new documents into a collection using the insert_one() or insert_many() methods.
    6. Querying documents: Retrieve documents from a collection using various query methods like find_one(), find(), etc.
    7. Updating documents: Modify existing documents in a collection using update_one() or update_many() methods.
    8. Deleting documents: Remove documents from a collection using the delete_one() or delete_many() methods.
    9. Aggregation: Perform aggregation operations like grouping, counting, etc., using the aggregation pipeline framework.
    10. Indexing: Improve query performance by creating indexes on fields in collections.

    There are many more advanced topics in MongoDB, such as data sharding, replication, and more, but these tasks cover the basics of working with MongoDB in Python.

    Python SQLite

    Relational databases are built and maintained using Python SQLite, a compact, serverless, self-contained database engine. Its mobility and simplicity make it a popular option for local or small-scale applications. Python has a built-in module for connecting to SQLite databases called SQLite3, enabling developers to work with SQLite databases without difficulties.

    Various API methods are available through the SQLite3 library that may be used to run SQL queries, insert, update, and remove data, as well as get data from tables. Additionally, it allows transactions, allowing programmers to undo changes in case of a problem. Python SQLite is a fantastic option for creating programs that need an embedded database system, including desktop, mobile, and modest-sized web programs. SQLite has become popular among developers for lightweight apps with database functionality thanks to its ease of use, portability, and smooth connection with Python.

    Python CGI

    Python CGI is a technology for running scripts through web servers to produce dynamic online content. It offers a communication channel and a dynamic content generation interface for external CGI scripts and the web server. Python CGI scripts may create HTML web pages, handle form input, and communicate with databases. Python CGI enables the server to carry out Python scripts and provide the results to the client, offering a quick and effective approach to creating dynamic online applications.

    Python CGI scripts may be used for many things, including creating dynamic web pages, processing forms, and interacting with databases. Since Python, a potent and popular programming language, can be utilized to create scripts, it enables a more customized and flexible approach to web creation. Scalable, safe, and maintainable online applications may be created with Python CGI. Python CGI is a handy tool for web developers building dynamic and interactive online applications.

    Asynchronous Programming in Python

    Asynchronous programming is a paradigm for computer programming that enables independent and concurrent operation of activities. It is frequently used in applications like web servers, database software, and network programming, where several tasks or requests must be handled concurrently.

    Python has asyncio, Twisted, and Tornado among its libraries and frameworks for asynchronous programming. Asyncio, one of these, offers a simple interface for asynchronous programming and is the official asynchronous programming library in Python.

    Coroutines are functions that may be halted and restarted at specific locations in the code and are utilized by asyncio. This enables numerous coroutines to operate simultaneously without interfering with one another. For constructing and maintaining coroutines, the library offers several classes and methods, including asyncio.gather(), asyncio.wait(), and asyncio.create_task().

    Event loops, which are in charge of planning and operating coroutines, are another feature of asyncio. By cycling between coroutines in a non-blocking way, the event loop controls the execution of coroutines and ensures that no coroutine blocks another. Additionally, it supports timers and scheduling callbacks, which may be helpful when activities must be completed at specified times or intervals.

    Python Concurrency

    The term “concurrency” describes a program’s capacity to carry out several tasks at once, enhancing the program’s efficiency. Python offers several modules and concurrency-related methods, including asynchronous programming, multiprocessing, and multithreading. While multiprocessing involves running many processes simultaneously on a system, multithreading involves running numerous threads concurrently inside a single process.

    The threading module in Python enables programmers to build multithreading. It offers classes and operations for establishing and controlling threads. Conversely, the multiprocessing module allows developers to design and control processes. Python’s asyncio module provides asynchronous programming support, allowing developers to write non-blocking code that can handle multiple tasks concurrently. Using these techniques, developers can write high-performance, scalable programs that can handle multiple tasks concurrently.

    Python’s threading module enables the concurrent execution of several threads within a single process, which is helpful for I/O-bound activities.

    For CPU-intensive operations like image processing or data analysis, multiprocessing modules make it possible to execute numerous processes concurrently across multiple CPU cores.

    The asyncio module supports asynchronous I/O and permits the creation of single-threaded concurrent code using coroutines for high-concurrency network applications.

    With libraries like Dask, PySpark, and MPI, Python may also be used for parallel computing. These libraries allow workloads to be distributed across numerous nodes or clusters for better performance.

    Web Scrapping using Python

    The process of web scraping is used to retrieve data from websites automatically. Various tools and libraries extract data from HTML and other online formats. Python is among the most widely used programming languages for web scraping because of its ease of use, adaptability, and variety of libraries.

    We must take a few steps to accomplish web scraping using Python. We must first decide which website to scrape and what information to gather. Then, we can submit a request to the website and receive the HTML content using Python’s requests package. Once we have the HTML text, we can extract the needed data using a variety of parsing packages, like Beautiful Soup and lxml.

    We can employ several strategies, like slowing requests, employing user agents, and using proxies, to prevent overburdening the website’s server. It is also crucial to abide by the terms of service for the website and respect its robots.txt file.

    Data mining, lead creation, pricing tracking, and many more uses are possible for web scraping. However, as unauthorized web scraping may be against the law and unethical, it is essential to utilize it professionally and ethically.

    Natural Language Processing (NLP) using Python

    A branch of artificial intelligence (AI) called “natural language processing” (NLP) studies how computers and human language interact. Thanks to NLP, computers can now understand, interpret, and produce human language. Due to its simplicity, versatility, and strong libraries like NLTK (Natural Language Toolkit) and spaCy, Python is a well-known programming language for NLP.

    For NLP tasks, including tokenization, stemming, lemmatization, part-of-speech tagging, named entity identification, sentiment analysis, and others, NLTK provides a complete library. It has a variety of corpora (big, organized text collections) for developing and evaluating NLP models. Another well-liked library for NLP tasks is spaCy, which offers quick and effective processing of enormous amounts of text. It enables simple modification and expansion and comes with pre-trained models for various NLP workloads.

    NLP may be used in Python for various practical purposes, including chatbots, sentiment analysis, text categorization, machine translation, and more. NLP is used, for instance, by chatbots to comprehend and reply to user inquiries in a natural language style. Sentiment analysis, which may be helpful for brand monitoring, customer feedback analysis, and other purposes, employs NLP to categorize text sentiment (positive, negative, or neutral). Text documents are categorized using natural language processing (NLP) into pre-established categories for spam detection, news categorization, and other purposes.

    Python is a strong and useful tool when analyzing and processing human language. Developers may carry out various NLP activities and create useful apps that can communicate with consumers in natural language with libraries like NLTK and spaCy.

    Conclusion:

    In this tutorial, we’ve looked at some of Python’s most important features and ideas, including variables, data types, loops, functions, modules, and more. More complex subjects, including web scraping, natural language processing, parallelism, and database connection, have also been discussed. You will have a strong basis to continue learning about Python and its applications using the information you have learned from this lesson.

    Remember that practicing and developing code is the best method to learn Python. You may find many resources at javaTpoint to support your further learning, including documentation, tutorials, online groups, and more. You can master Python and use it to create wonderful things if you work hard and persist.

    Prerequisite

    Before learning Python, you must have the basic knowledge of programming concepts.

    Audience

    Our Python tutorial is designed to help beginners and professionals.

    Problem

    We assure that you will not find any problem in this Python tutorial. But if there is any mistake, please post the problem in contact form.

  • PHP Exception Handling

    What is an Exception

    An exception is a signal that indicates some sort of exceptional event or error has occurred. Exceptions can be caused due to various reasons, for example, database connection or query fails, file that you’re trying to access doesn’t exist, and so on.

    PHP provides a powerful exception handling mechanism that allows you to handle exceptions in a graceful way. As opposed to PHP’s traditional error-handling system, exception handling is the object-oriented method for handling errors, which provides more controlled and flexible form of error reporting. Exception model was first introduced in PHP 5.

    Using Throw and Try…Catch Statements

    In exception-based approach, program code is written in a try block, an exception can be thrown using the throw statement when an exceptional event occurs during the execution of code in a try block. It is then caught and resolved by one or more catch blocks.

    The following example demonstrates how exception handling works:

    Example

    <?php
    function division($dividend, $divisor){
        // Throw exception if divisor is zero
        if($divisor == 0){
            throw new Exception('Division by zero.');
        } else{
            $quotient = $dividend / $divisor;
            echo "<p>$dividend / $divisor = $quotient</p>";
        }
    }
     
    try{
        division(10, 2);
        division(30, -4);
        division(15, 0);
        
        // If exception is thrown following line won't execute
        echo '<p>All divisions performed successfully.</p>';
    } catch(Exception $e){
        // Handle the exception
        echo "<p>Caught exception: " . $e->getMessage() . "</p>";
    }
     
    // Continue execution
    echo "<p>Hello World!</p>";
    ?>

    You might be wondering what this code was all about. Well, let’s go through each part of this code one by one for a better understanding.

    Explanation of Code

    The PHP’s exception handling system has basically four parts: trythrowcatch, and the Exception class. The following list describes how each part exactly works.

    • The division() function in the example above checks if a divisor is equal to zero. If it is, an exception is thrown via PHP’s throw statement. Otherwise this function perform the division using given numbers and display the result.
    • Later, the division() function is called within a try block with different arguments. If an exception is generated while executing the code within the try block, PHP stops execution at that point and attempt to find the corresponding catch block. If it is found, the code within that catch block is executed, if not, a fatal error is generated.
    • The catch block typically catch the exception thrown within the try block and creates an object ($e) containing the exception information. The error message from this object can be retrieved using the Exception’s getMessage() method.

    The PHP’s Exception class also provides getCode()getFile()getLine() and getTraceAsString() methods that can be used to generate detailed debugging information.

    Example

    <?php
    // Turn off default error reporting
    error_reporting(0);
     
    try{
        $file = "somefile.txt";
        
        // Attempt to open the file
        $handle = fopen($file, "r");
        if(!$handle){
            throw new Exception("Cannot open the file!", 5);
        }
        
        // Attempt to read the file contents
        $content = fread($handle, filesize($file));
        if(!$content){
            throw new Exception("Could not read file!", 10);
        }
        
        // Closing the file handle
        fclose($handle);
        
        // Display file contents
        echo $content;
    } catch(Exception $e){
        echo "<h3>Caught Exception!</h3>";
        echo "<p>Error message: " . $e->getMessage() . "</p>";    
        echo "<p>File: " . $e->getFile() . "</p>";
        echo "<p>Line: " . $e->getLine() . "</p>";
        echo "<p>Error code: " . $e->getCode() . "</p>";
        echo "<p>Trace: " . $e->getTraceAsString() . "</p>";
    }
    ?>

    The Exception’s constructor optionally takes an exception message and an exception code. While the exception message is typically used to display generic information on what went wrong, the exception code can be used to categorize the errors. The exception code provided can be retrieved later via Exception’s getCode() method.

    Tip: Exception should only be used to denote exceptional conditions; they should not be used to control normal application flow e.g., jump to another place in the script at a particular point. Doing that would adversely affect your application’s performance.


    Defining Custom Exceptions

    You can even define your own custom exception handlers to treat different types of exceptions in a different way. It allows you to use a separate catch block for each exception type.

    You can define a custom exception by extending the Exception class, because Exception is the base class for all exceptions. The custom exception class inherits all the properties and methods from PHP’s Exception class. You can also add your custom methods to the custom exception class. Let’s check out the following example:

    Example

    <?php
    // Extending the Exception class
    class EmptyEmailException extends Exception {}
    class InvalidEmailException extends Exception {}
     
    $email = "[email protected]";
     
    try{
        // Throw exception if email is empty
        if($email == ""){
            throw new EmptyEmailException("<p>Please enter your E-mail address!</p>");
        }
        
        // Throw exception if email is not valid
        if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {           
            throw new InvalidEmailException("<p><b>$email</b> is not a valid E-mail address!</p>");
        }
        
        // Display success message if email is valid
        echo "<p>SUCCESS: Email validation successful.</p>";
    } catch(EmptyEmailException $e){
        echo $e->getMessage();
    } catch(InvalidEmailException $e){
        echo $e->getMessage();
    }
    ?>

    In the above example we’ve derived two new exception classes: EmptyEmailException, and InvalidEmailException from the Exception base class. Multiple catch blocks are used to display different error messages, depending on the type of exception generated.

    Since these custom exception classes inherits the properties and methods from the Exception class, so we can use the Exception’s class methods like getMessage()getLine()getFile(), etc. to retrieve error information from the exception object.


    Setting a Global Exception Handler

    As we’ve discussed earlier in this chapter if an exception is not caught, PHP generates a Fatal Error with an “Uncaught Exception …” message. This error message may contain sensitive information like file name and line number where the problem occurs. If you don’t want to expose such information to the user, you can create a custom function and register it with the set_exception_handler() function to handle all uncaught exceptions.

    Example

    <?php
    function handleUncaughtException($e){
        // Display generic error message to the user
        echo "Opps! Something went wrong. Please try again, or contact us if the problem persists.";
        
        // Construct the error string
        $error = "Uncaught Exception: " . $message = date("Y-m-d H:i:s - ");
        $error .= $e->getMessage() . " in file " . $e->getFile() . " on line " . $e->getLine() . "\n";
        
        // Log details of error in a file
        error_log($error, 3, "var/log/exceptionLog.log");
    }
     
    // Register custom exception handler
    set_exception_handler("handleUncaughtException");
     
    // Throw an exception
    throw new Exception("Testing Exception!");
    ?>
  • PHP Regular Expressions

    What is Regular Expression

    Regular Expressions, commonly known as “regex” or “RegExp“, are a specially formatted text strings used to find patterns in text. Regular expressions are one of the most powerful tools available today for effective and efficient text processing and manipulations. For example, it can be used to verify whether the format of data i.e. name, email, phone number, etc. entered by the user was correct or not, find or replace matching string within text content, and so on.

    PHP (version 5.3 and above) supports Perl style regular expressions via its preg_ family of functions. Why Perl style regular expressions? Because Perl (Practical Extraction and Report Language) was the first mainstream programming language that provided integrated support for regular expressions and it is well known for its strong support of regular expressions and its extraordinary text processing and manipulation capabilities.

    Let’s begin with a brief overview of the commonly used PHP’s built-in pattern-matching functions before delving deep into the world of regular expressions.

    FunctionWhat it Does
    preg_match()Perform a regular expression match.
    preg_match_all()Perform a global regular expression match.
    preg_replace()Perform a regular expression search and replace.
    preg_grep()Returns the elements of the input array that matched the pattern.
    preg_split()Splits up a string into substrings using a regular expression.
    preg_quote()Quote regular expression characters found within a string.

    Note: The PHP preg_match() function stops searching after it finds the first match, whereas the preg_match_all() function continues searching until the end of the string and find all possible matches instead of stopping at the first match.


    Regular Expression Syntax

    Regular expression syntax includes the use of special characters (do not confuse with the HTML special characters). The characters that are given special meaning within a regular expression, are: . * ? + [ ] ( ) { } ^ $ | \. You will need to backslash these characters whenever you want to use them literally. For example, if you want to match “.”, you’d have to write \.. All other characters automatically assume their literal meanings.

    The following sections describe the various options available for formulating patterns:

    Character Classes

    Square brackets surrounding a pattern of characters are called a character class e.g. [abc]. A character class always matches a single character out of a list of specified characters that means the expression [abc] matches only a, b or c character.

    Negated character classes can also be defined that match any character except those contained within the brackets. A negated character class is defined by placing a caret (^) symbol immediately after the opening bracket, like this [^abc].

    You can also define a range of characters by using the hyphen (-) character inside a character class, like [0-9]. Let’s look at some examples of character classes:

    RegExpWhat it Does
    [abc]Matches any one of the characters a, b, or c.
    [^abc]Matches any one character other than a, b, or c.
    [a-z]Matches any one character from lowercase a to lowercase z.
    [A-Z]Matches any one character from uppercase a to uppercase z.
    [a-Z]Matches any one character from lowercase a to uppercase Z.
    [0-9]Matches a single digit between 0 and 9.
    [a-z0-9]Matches a single character between a and z or between 0 and 9.

    The following example will show you how to find whether a pattern exists in a string or not using the regular expression and PHP preg_match() function:

    Example

    <?php
    $pattern = "/ca[kf]e/";
    $text = "He was eating cake in the cafe.";
    if(preg_match($pattern, $text)){
        echo "Match found!";
    } else{
        echo "Match not found.";
    }
    ?>

    Similarly, you can use the preg_match_all() function to find all matches within a string:

    Example

    <?php
    $pattern = "/ca[kf]e/";
    $text = "He was eating cake in the cafe.";
    $matches = preg_match_all($pattern, $text, $array);
    echo $matches . " matches were found.";
    ?>

    Tip: Regular expressions aren’t exclusive to PHP. Languages such as Java, Perl, Python, etc. use the same notation for finding patterns in text.


    Predefined Character Classes

    Some character classes such as digits, letters, and whitespaces are used so frequently that there are shortcut names for them. The following table lists those predefined character classes:

    ShortcutWhat it Does
    .Matches any single character except newline \n.
    \dmatches any digit character. Same as [0-9]
    \DMatches any non-digit character. Same as [^0-9]
    \sMatches any whitespace character (space, tab, newline or carriage return character). Same as [ \t\n\r]
    \SMatches any non-whitespace character. Same as [^ \t\n\r]
    \wMatches any word character (definned as a to z, A to Z,0 to 9, and the underscore). Same as [a-zA-Z_0-9]
    \WMatches any non-word character. Same as [^a-zA-Z_0-9]

    The following example will show you how to find and replace space with a hyphen character in a string using regular expression and PHP preg_replace() function:

    Example

    <?php
    $pattern = "/\s/";
    $replacement = "-";
    $text = "Earth revolves around\nthe\tSun";
    // Replace spaces, newlines and tabs
    echo preg_replace($pattern, $replacement, $text);
    echo "<br>";
    // Replace only spaces
    echo str_replace(" ", "-", $text);
    ?>

    Repetition Quantifiers

    In the previous section we’ve learnt how to match a single character in a variety of fashions. But what if you want to match on more than one character? For example, let’s say you want to find out words containing one or more instances of the letter p, or words containing at least two p’s, and so on. This is where quantifiers come into play. With quantifiers you can specify how many times a character in a regular expression should match.

    The following table lists the various ways to quantify a particular pattern:

    RegExpWhat it Does
    p+Matches one or more occurrences of the letter p.
    p*Matches zero or more occurrences of the letter p.
    p?Matches zero or one occurrences of the letter p.
    p{2}Matches exactly two occurrences of the letter p.
    p{2,3}Matches at least two occurrences of the letter p, but not more than three occurrences of the letter p.
    p{2,}Matches two or more occurrences of the letter p.
    p{,3}Matches at most three occurrences of the letter p

    The regular expression in the following example will splits the string at comma, sequence of commas, whitespace, or combination thereof using the PHP preg_split() function:

    Example

    <?php
    $pattern = "/[\s,]+/";
    $text = "My favourite colors are red, green and blue";
    $parts = preg_split($pattern, $text);
     
    // Loop through parts array and display substrings
    foreach($parts as $part){
        echo $part . "<br>";
    }
    ?>

    Position Anchors

    There are certain situations where you want to match at the beginning or end of a line, word, or string. To do this you can use anchors. Two common anchors are caret (^) which represent the start of the string, and the dollar ($) sign which represent the end of the string.

    RegExpWhat it Does
    ^pMatches the letter p at the beginning of a line.
    p$Matches the letter p at the end of a line.

    The regular expression in the following example will display only those names from the names array which start with the letter “J” using the PHP preg_grep() function:

    Example

    <?php
    $pattern = "/^J/";
    $names = array("Jhon Carter", "Clark Kent", "John Rambo");
    $matches = preg_grep($pattern, $names);
     
    // Loop through matches array and display matched names
    foreach($matches as $match){
        echo $match . "<br>";
    }
    ?>

    Pattern Modifiers

    A pattern modifier allows you to control the way a pattern match is handled. Pattern modifiers are placed directly after the regular expression, for example, if you want to search for a pattern in a case-insensitive manner, you can use the i modifier, like this: /pattern/i. The following table lists some of the most commonly used pattern modifiers.

    ModifierWhat it Does
    iMakes the match case-insensitive manner.
    mChanges the behavior of ^ and $ to match against a newline boundary (i.e. start or end of each line within a multiline string), instead of a string boundary.
    gPerform a global match i.e. finds all occurrences.
    oEvaluates the expression only once.
    sChanges the behavior of . (dot) to match all characters, including newlines.
    xAllows you to use whitespace and comments within a regular expression for clarity.

    The following example will show you how to perform a global case-insensitive search using the i modifier and the PHP preg_match_all() function.

    Example

    <?php
    $pattern = "/color/i";
    $text = "Color red is more visible than color blue in daylight.";
    $matches = preg_match_all($pattern, $text, $array);
    echo $matches . " matches were found.";
    ?>

    Similarly, the following example shows how to match at the beginning of every line in a multi-line string using ^ anchor and m modifier with PHP preg_match_all() function.

    Example

    <?php
    $pattern = "/^color/im";
    $text = "Color red is more visible than \ncolor blue in daylight.";
    $matches = preg_match_all($pattern, $text, $array);
    echo $matches . " matches were found.";
    ?>

    Word Boundaries

    A word boundary character ( \b) helps you search for the words that begins and/or ends with a pattern. For example, the regexp /\bcar/ matches the words beginning with the pattern car, and would match cart, carrot, or cartoon, but would not match oscar.

    Similarly, the regexp /car\b/ matches the words ending with the pattern car, and would match scar, oscar, or supercar, but would not match cart. Likewise, the /\bcar\b/ matches the words beginning and ending with the pattern car, and would match only the word car.

    The following example will highlight the words beginning with car in bold:

    Example

    <?php
    $pattern = '/\bcar\w*/';
    $replacement = '<b>$0</b>';
    $text = 'Words begining with car: cart, carrot, cartoon. Words ending with car: scar, oscar, supercar.';
    echo preg_replace($pattern, $replacement, $text);
    ?>

    We hope you have understood the basics of regular expression. To learn how to validate form data using regular expression, please check out the tutorial on PHP Form Validation.

  • PHP JSON Parsing

    What is JSON

    JSON stands for JavaScript Object Notation. JSON is a standard lightweight data-interchange format which is quick and easy to parse and generate.

    JSON, like XML, is a text-based format that’s easy to write and easy to understand for both humans and computers, but unlike XML, JSON data structures occupy less bandwidth than their XML versions. JSON is based on two basic structures:

    • Object: This is defined as a collection of key/value pairs (i.e. key:value). Each object begins with a left curly bracket { and ends with a right curly bracket }. Multiple key/value pairs are separated by a comma ,.
    • Array: This is defined as an ordered list of values. An array begins with a left bracket [ and ends with a right bracket ]. Values are separated by a comma ,.

    In JSON, keys are always strings, while the value can be a stringnumbertrue or falsenull or even an object or an array. Strings must be enclosed in double quotes " and can contain escape characters such as \n\t and \. A JSON object may look like this:

    Example

    Run this code »

    {
        "book": {
            "name": "Harry Potter and the Goblet of Fire",
            "author": "J. K. Rowling",
            "year": 2000,
            "genre": "Fantasy Fiction",
            "bestseller": true
        }
    }

    Whereas an example of JSON array would look something like this:

    Example

    Run this code »

    {
        "fruits": [
            "Apple",
            "Banana",
            "Strawberry",
            "Mango"
        ]
    }

    Tip: A data-interchange format is a text format which is used to interchange or exchange data between different platforms and operating systems. JSON is the most popular and lightweight data-interchange format for web applications.


    Parsing JSON with PHP

    JSON data structures are very similar to PHP arrays. PHP has built-in functions to encode and decode JSON data. These functions are json_encode() and json_decode(), respectively. Both functions only works with UTF-8 encoded string data.

    Encoding JSON Data in PHP

    In PHP the json_encode() function is used to encode a value to JSON format. The value being encoded can be any PHP data type except a resource, like a database or file handle. The below example demonstrates how to encode a PHP associative array into a JSON object:

    Example

    <?php
    // An associative array
    $marks = array("Peter"=>65, "Harry"=>80, "John"=>78, "Clark"=>90);
     
    echo json_encode($marks);
    ?>

    The output of the above example will look like this:

    {“Peter”:65,”Harry”:80,”John”:78,”Clark”:90}

    Similarly, you can encode the PHP indexed array into a JSON array, like this:

    Example

    <?php
    // An indexed array
    $colors = array("Red", "Green", "Blue", "Orange", "Yellow");
     
    echo json_encode($colors);
    ?>

    The output of the above example will look like this:

    [“Red”,”Green”,”Blue”,”Orange”,”Yellow”]

    You can also force json_encode() function to return an PHP indexed array as JSON object by using the JSON_FORCE_OBJECT option, as shown in the example below:

    Example

    <?php
    // An indexed array
    $colors = array("Red", "Green", "Blue", "Orange");
     
    echo json_encode($colors, JSON_FORCE_OBJECT);
    ?>

    The output of the above example will look like this:

    {“0″:”Red”,”1″:”Green”,”2″:”Blue”,”3″:”Orange”}

    As you can see in the above examples a non-associative array can be encoded as array or object. However, an associative array always encoded as object.


    Decoding JSON Data in PHP

    Decoding JSON data is as simple as encoding it. You can use the PHP json_decode() function to convert the JSON encoded string into appropriate PHP data type. The following example demonstrates how to decode or convert a JSON object to PHP object.

    Example

    <?php
    // Store JSON data in a PHP variable
    $json = '{"Peter":65,"Harry":80,"John":78,"Clark":90}';
     
    var_dump(json_decode($json));
    ?>

    The output of the above example will look something like this:

    object(stdClass)#1 (4) { [“Peter”]=> int(65) [“Harry”]=> int(80) [“John”]=> int(78) [“Clark”]=> int(90) }

    By default the json_decode() function returns an object. However, you can optionally specify a second parameter $assoc which accepts a boolean value that when set as true JSON objects are decoded into associative arrays. It is false by default. Here’s an example:

    Example

    <?php
    // Store JSON data in a PHP variable
    $json = '{"Peter":65,"Harry":80,"John":78,"Clark":90}';
     
    var_dump(json_decode($json, true));
    ?>

    The output of the above example will look something like this:

    array(4) { [“Peter”]=> int(65) [“Harry”]=> int(80) [“John”]=> int(78) [“Clark”]=> int(90) }

    Now let’s check out an example that will show you how to decode the JSON data and access individual elements of the JSON object or array in PHP.

    Example

    <?php
    // Assign JSON encoded string to a PHP variable
    $json = '{"Peter":65,"Harry":80,"John":78,"Clark":90}';
     
    // Decode JSON data to PHP associative array
    $arr = json_decode($json, true);
    // Access values from the associative array
    echo $arr["Peter"];  // Output: 65
    echo $arr["Harry"];  // Output: 80
    echo $arr["John"];   // Output: 78
    echo $arr["Clark"];  // Output: 90
     
    // Decode JSON data to PHP object
    $obj = json_decode($json);
    // Access values from the returned object
    echo $obj->Peter;   // Output: 65
    echo $obj->Harry;   // Output: 80
    echo $obj->John;    // Output: 78
    echo $obj->Clark;   // Output: 90
    ?>

    You can also loop through the decoded data using foreach() loop, like this:

    Example

    <?php
    // Assign JSON encoded string to a PHP variable
    $json = '{"Peter":65,"Harry":80,"John":78,"Clark":90}';
     
    // Decode JSON data to PHP associative array
    $arr = json_decode($json, true);
     
    // Loop through the associative array
    foreach($arr as $key=>$value){
        echo $key . "=>" . $value . "<br>";
    }
    echo "<hr>";
    // Decode JSON data to PHP object
    $obj = json_decode($json);
     
    // Loop through the object
    foreach($obj as $key=>$value){
        echo $key . "=>" . $value . "<br>";
    }
    ?>

    Extracting Values from Nested JSON Data in PHP

    JSON objects and arrays can also be nested. A JSON object can arbitrarily contains other JSON objects, arrays, nested arrays, arrays of JSON objects, and so on. The following example will show you how to decode a nested JSON object and print all its values in PHP.

    Example

    <?php
    // Define recursive function to extract nested values
    function printValues($arr) {
        global $count;
        global $values;
        
        // Check input is an array
        if(!is_array($arr)){
            die("ERROR: Input is not an array");
        }
        
        /*
        Loop through array, if value is itself an array recursively call the
        function else add the value found to the output items array,
    
  • PHP Magic Constants

    What is Magic Constants

    In the PHP constants chapter we’ve learned how to define and use constants in PHP script.

    PHP moreover also provide a set of special predefined constants that change depending on where they are used. These constants are called magic constants. For example, the value of __LINE__ depends on the line that it’s used on in your script.

    Magic constants begin with two underscores and end with two underscores. The following section describes some of the most useful magical PHP constants.

    __LINE__

    The __LINE__ constant returns the current line number of the file, like this:

    Example

    <?php
    echo "Line number " . __LINE__ . "<br>"; // Displays: Line number 2
    echo "Line number " . __LINE__ . "<br>"; // Displays: Line number 3
    echo "Line number " . __LINE__ . "<br>"; // Displays: Line number 4
    ?>

    __FILE__

    The __FILE__ constant returns full path and name of the PHP file that’s being executed. If used inside an include, the name of the included file is returned.

    Example

    <?php
    // Displays the absolute path of this file
    echo "The full path of this file is: " . __FILE__;
    ?>

    __DIR__

    The __DIR__ constant returns the directory of the file. If used inside an include, the directory of the included file is returned. Here’s an example:

    Example

    <?php
    // Displays the directory of this file
    echo "The directory of this file is: " . __DIR__;
    ?>

    __FUNCTION__

    The __FUNCTION__ constant returns the name of the current function.

    Example

    <?php
    function myFunction(){
        echo  "The function name is - " . __FUNCTION__;
    }
    myFunction(); // Displays: The function name is - myFunction
    ?>

    __CLASS__

    The __CLASS__ constant returns the name of the current class. Here’s an example:

    Example

    <?php
    class MyClass
    {
        public function getClassName(){
            return __CLASS__;
        }
    }
    $obj = new MyClass();
    echo $obj->getClassName(); // Displays: MyClass
    ?>

    __METHOD__

    The __METHOD__ constant returns the name of the current class method.

    Example

    <?php
    class Sample
    {
        public function myMethod(){
            echo __METHOD__;
        }
    }
    $obj = new Sample();
    $obj->myMethod(); // Displays: Sample::myMethod
    ?>

    __NAMESPACE__

    The __NAMESPACE__ constant returns the name of the current namespace.

    Example

    <?php
    namespace MyNamespace;
    class MyClass
    {
        public function getNamespace(){
            return __NAMESPACE__;
        }
    }
    $obj = new MyClass();
    echo $obj->getNamespace(); // Displays: MyNamespace
    ?>
  • PHP Classes and Objects

    What is Object Oriented Programming

    Object-Oriented Programming (OOP) is a programming model that is based on the concept of classes and objects. As opposed to procedural programming where the focus is on writing procedures or functions that perform operations on the data, in object-oriented programming the focus is on the creations of objects which contain both data and functions together.

    Object-oriented programming has several advantages over conventional or procedural style of programming. The most important ones are listed below:

    • It provides a clear modular structure for the programs.
    • It helps you adhere to the “don’t repeat yourself” (DRY) principle, and thus make your code much easier to maintain, modify and debug.
    • It makes it possible to create more complicated behavior with less code and shorter development time and high degree of reusability.

    The following sections will describe how classes and objects work in PHP.

    Tip: The idea behind Don’t Repeat Yourself (DRY) principle is reducing the repetition of code by abstracting out the code that are common for the application and placing them at a single place and reuse them instead of repeating it.


    Understanding Classes and Objects

    Classes and objects are the two main aspects of object-oriented programming. A class is a self-contained, independent collection of variables and functions which work together to perform one or more specific tasks, while objects are individual instances of a class.

    A class acts as a template or blueprint from which lots of individual objects can be created. When individual objects are created, they inherit the same generic properties and behaviors, although each object may have different values for certain properties.

    For example, think of a class as a blueprint for a house. The blueprint itself is not a house, but is a detailed plan of the house. While, an object is like an actual house built according to that blueprint. We can build several identical houses from the same blueprint, but each house may have different paints, interiors and families inside, as shown in the illustration below.

    Class Object Relationship Illustration

    A class can be declared using the class keyword, followed by the name of the class and a pair of curly braces ({}), as shown in the following example.

    Let’s create a PHP file named Rectangle.php and put the following example code inside it so that our class code should be separated from rest of the program. We can then use it wherever it’s needed by simply including the Rectangle.php file.

    Example

    <?php
    class Rectangle
    {
        // Declare  properties
        public $length = 0;
        public $width = 0;
        
        // Method to get the perimeter
        public function getPerimeter(){
            return (2 * ($this->length + $this->width));
        }
        
        // Method to get the area
        public function getArea(){
            return ($this->length * $this->width);
        }
    }
    ?>

    The public keyword before the properties and methods in the example above, is an access modifier, which indicates that this property or method is accessible from anywhere. We will learn more about this a little later in this chapter.

    Note: Syntactically, variables within a class are called properties, whereas functions are called methods. Also class names conventionally are written in PascalCase i.e. each concatenated word starts with an uppercase letter (e.g. MyClass).

    Once a class has been defined, objects can be created from the class with the new keyword. Class methods and properties can directly be accessed through this object instance.

    Create another PHP file name test.php and put the following code inside it.

    Example

    <?php
    // Include class definition
    require "Rectangle.php";
     
    // Create a new object from Rectangle class
    $obj = new Rectangle;
     
    // Get the object properties values
    echo $obj->length; // 0utput: 0
    echo $obj->width; // 0utput: 0
     
    // Set object properties values
    $obj->length = 30;
    $obj->width = 20;
     
    // Read the object properties values again to show the change
    echo $obj->length; // 0utput: 30
    echo $obj->width; // 0utput: 20
     
     
    // Call the object methods
    echo $obj->getPerimeter(); // 0utput: 100
    echo $obj->getArea(); // Output: 600
    ?>

    The arrow symbol (->) is an OOP construct that is used to access contained properties and methods of a given object. Whereas, the pseudo-variable $this provides a reference to the calling object i.e. the object to which the method belongs.

    The real power of object oriented programming becomes evident when using multiple instances of the same class, as shown in the following example:

    Example

    <?php
    // Include class definition
    require "Rectangle.php";
     
    // Create multiple objects from the Rectangle class
    $obj1 = new Rectangle;
    $obj2 = new Rectangle;
     
    // Call the methods of both the objects
    echo $obj1->getArea(); // Output: 0
    echo $obj2->getArea(); // Output: 0
     
    // Set $obj1 properties values
    $obj1->length = 30;
    $obj1->width = 20;
     
    // Set $obj2 properties values
    $obj2->length = 35;
    $obj2->width = 50;
     
    // Call the methods of both the objects again
    echo $obj1->getArea(); // Output: 600
    echo $obj2->getArea(); // Output: 1750
    ?>

    As you can see in the above example, calling the getArea() method on different objects causes that method to operate on a different set of data. Each object instance is completely independent, with its own properties and methods, and thus can be manipulated independently, even if they’re of the same class.


    Using Constructors and Destructors

    To make the object-oriented programming easier, PHP provides some magic methods that are executed automatically when certain actions occur within an object.

    For example, the magic method __construct() (known as constructor) is executed automatically whenever a new object is created. Similarly, the magic method __destruct() (known as destructor) is executed automatically when the object is destroyed. A destructor function cleans up any resources allocated to an object once the object is destroyed.

    Example

    <?php
    class MyClass
    {
        // Constructor
        public function __construct(){
            echo 'The class "' . __CLASS__ . '" was initiated!<br>';
        }
        
        // Destructor
        public function __destruct(){
            echo 'The class "' . __CLASS__ . '" was destroyed.<br>';
        }
    }
     
    // Create a new object
    $obj = new MyClass;
     
    // Output a message at the end of the file
    echo "The end of the file is reached.";
    ?>

    The PHP code in the above example will produce the following output:

    The class “MyClass” was initiated!
    The end of the file is reached.
    The class “MyClass” was destroyed.

    A destructor is called automatically when a scripts ends. However, to explicitly trigger the destructor, you can destroy the object using the PHP unset() function, as follow:

    Example

    <?php
    class MyClass
    {
        // Constructor
        public function __construct(){
            echo 'The class "' . __CLASS__ . '" was initiated!<br>';
        }
        
        // Destructor
        public function __destruct(){
        echo 'The class "' . __CLASS__ . '" was destroyed.<br>';
        }
    }
     
    // Create a new object
    $obj = new MyClass;
     
    // Destroy the object
    unset($obj);
     
    // Output a message at the end of the file
    echo "The end of the file is reached.";
    ?>

    Now, the PHP code in the above example will produce the following output:

    The class “MyClass” was initiated!
    The class “MyClass” was destroyed.
    The end of the file is reached.

    Tip: PHP automatically clean up all resources allocated during execution when the script is finished, e.g. closing database connections, destroying objects, etc.

    Note: The __CLASS__ is a magic constant which contains the name of the class in which it is occur. It is empty, if it occurs outside of the class.


    Extending Classes through Inheritance

    Classes can inherit the properties and methods of another class using the extends keyword. This process of extensibility is called inheritance. It is probably the most powerful reason behind using the object-oriented programming model.

    Example

    <?php
    // Include class definition
    require "Rectangle.php";
     
    // Define a new class based on an existing class
    class Square extends Rectangle
    {   
        // Method to test if the rectangle is also a square
        public function isSquare(){
            if($this->length == $this->width){
                return true; // Square
            } else{
                return false; // Not a square
            }
        }
    }
     
    // Create a new object from Square class
    $obj = new Square;
     
    // Set object properties values
    $obj->length = 20;
    $obj->width = 20;
     
    // Call the object methods
    if($obj->isSquare()){
        echo "The area of the square is ";
    } else{
        echo "The area of the rectangle is ";
    };
    echo $obj->getArea();
    ?>

    The PHP code in the above example will produce the following output:

    The area of the square is 400

    As you can see in the above example, even though the class definition of Square doesn’t explicitly contain getArea() method nor the $length and $width property, instances of the Square class can use them, as they inherited from the parent Rectangle class.

    Tip: Since a child class is derived from a parent class, it is also referred to as a derived class, and its parent is called the base class.


    Controlling the Visibility of Properties and Methods

    When working with classes, you can even restrict access to its properties and methods using the visibility keywords for greater control. There are three visibility keywords (from most visible to least visible): publicprotectedprivate, which determines how and from where properties and methods can be accessed and modified.

    • public — A public property or method can be accessed anywhere, from within the class and outside. This is the default visibility for all class members in PHP.
    • protected — A protected property or method can only be accessed from within the class itself or in child or inherited classes i.e. classes that extends that class.
    • private — A private property or method is accessible only from within the class that defines it. Even child or inherited classes cannot access private properties or methods.

    The following example will show you how this visibility actually works:

    Example

    <?php
    // Class definition
    class Automobile
    {
        // Declare  properties
        public $fuel;
        protected $engine;
        private $transmission;
    }
    class Car extends Automobile
    {
        // Constructor
        public function __construct(){
            echo 'The class "' . __CLASS__ . '" was initiated!<br>';
        }
    }
     
    // Create an object from Automobile class
    $automobile = new Automobile;
     
    // Attempt to set $automobile object properties
    $automobile->fuel = 'Petrol'; // ok
    $automobile->engine = '1500 cc'; // fatal error
    $automobile->transmission = 'Manual'; // fatal error
     
    // Create an object from Car class
    $car = new Car;
     
    // Attempt to set $car object properties
    $car->fuel = 'Diesel'; // ok
    $car->engine = '2200 cc'; // fatal error
    $car->transmission = 'Automatic'; // undefined
    ?>

    Static Properties and Methods

    In addition to the visibility, properties and methods can also be declared as static, which makes them accessible without needing an instantiation of the class. Static properties and methods can be accessed using the scope resolution operator (::), like this: ClassName::$property and ClassName::method().

    A property declared as static cannot be accessed via the object of that class though a static method can be, as demonstrated in the following example:

    Example

    <?php
    // Class definition
    class HelloClass
    {
        // Declare a static property
        public static $greeting = "Hello World!";
        
        // Declare a static method
        public static function sayHello(){
            echo self::$greeting;
        }
    }
    // Attempt to access static property and method directly
    echo HelloClass::$greeting; // Output: Hello World!
    HelloClass::sayHello(); // Output: Hello World!
     
    // Attempt to access static property and method via object
    $hello = new HelloClass;
    echo $hello->greeting; // Strict Warning
    $hello->sayHello(); // Output: Hello World!
    ?>

    The keyword self in the above example means “the current class”. It is never preceded by a dollar sign ($) and always followed by the :: operator (e.g. self::$name).

    The self keyword is different from the this keyword which means “the current object” or  “the current instance of a class”. The this keyword is always preceded by a dollar sign ($) and followed by the -> operator (e.g. $this->name).

    Note: Since static methods can be called without an instance of a class (i.e. object), the pseudo-variable $this is not available inside the method declared as static.

    We hope you’ve understood the basic concepts of object-oriented programming by now. You’ll find more examples on OOP in PHP and MySQL database section.

  • PHP Error Handling

    Handling Errors

    Sometimes your application will not run as it supposed to do, resulting in an error. There are a number of reasons that may cause errors, for example:

    • The Web server might run out of disk space
    • A user might have entered an invalid value in a form field
    • The file or database record that you were trying to access may not exist
    • The application might not have permission to write to a file on the disk
    • A service that the application needs to access might be temporarily unavailable

    These types of errors are known as runtime errors, because they occur at the time the script runs. They are distinct from syntax errors that need to be fixed before the script will run.

    A professional application must have the capabilities to handle such runtime error gracefully. Usually this means informing the user about the problem more clearly and precisely.

    Understanding Error Levels

    Usually, when there’s a problem that prevents a script from running properly, the PHP engine triggers an error. Each error is represented by an integer value and an associated constant. The following table list some of the common error levels:

    Error LevelValueDescription
    E_ERROR1A fatal run-time error, that can’t be recovered from. The execution of the script is stopped immediately.
    E_WARNING2A run-time warning. It is non-fatal and most errors tend to fall into this category. The execution of the script is not stopped.
    E_NOTICE8A run-time notice. Indicate that the script encountered something that could possibly an error, although the situation could also occur when running a script normally.
    E_USER_ERROR256A fatal user-generated error message. This is like an E_ERROR, except it is generated by the PHP script using the function trigger_error() rather than the PHP engine.
    E_USER_WARNING512A non-fatal user-generated warning message. This is like an E_WARNING, except it is generated by the PHP script using the function trigger_error() rather than the PHP. engine
    E_USER_NOTICE1024A user-generated notice message. This is like an E_NOTICE, except it is generated by the PHP script using the function trigger_error() rather than the PHP engine.
    E_STRICT2048Not strictly an error, but triggered whenever PHP encounters code that could lead to problems or forward incompatibilities
    E_ALL8191All errors and warnings, except of E_STRICT prior to PHP 5.4.0.

    For more error levels, please check out the reference on PHP Error Levels.

    The PHP engine triggers an error whenever it encounters a problem with your script, but you can also trigger errors yourself to generate more user friendly error messages. This way you can make your application more sofisticated. The following section describes some of common methods used for handling errors in PHP:

    Basic Error Handling Using the die() Function

    Consider the following example that simply tries to open a text file for reading only.

    Example

    Download

    <?php
    // Try to open a non-existent file
    $file = fopen("sample.txt", "r");
    ?>

    If the file does not exist you might get an error like this:

    Warning: fopen(sample.txt) [function.fopen]: failed to open stream: No such file or directory in C:\wamp\www\project\test.php on line 2

    If we follow some simple steps we can prevent the users from getting such error message.

    Example

    Download

    <?php
    if(file_exists("sample.txt")){
        $file = fopen("sample.txt", "r");
    } else{
        die("Error: The file you are trying to access doesn't exist.");
    }
    ?>

    Now if you run the above script you will get the error message like this:

    Error: The file you are trying to access doesn’t exist.

    As you can see by implementing a simple check whether the file exist or not before trying to access it, we can generate an error message that is more meaningful to the user.

    The die() function used above simply display the custom error message and terminate the current script if ‘sample.txt’ file is not found.


    Creating a Custom Error Handler

    You can create your own error handler function to deal with the run-time error generated by PHP engine. The custom error handler provides you greater flexibility and better control over the errors, it can inspect the error and decide what to do with the error, it might display a message to the user, log the error in a file or database or send by e-mail, attempt to fix the problem and carry on, exit the execution of the script or ignore the error altogether.

    The custom error handler function must be able to handle at least two parameters (errno and errstr), however it can optionally accept an additional three parameters (errfile, errline, and errcontext), as described below:

    ParameterDescription
    Required — The following parameters are required
    errnoSpecifies the level of the error, as an integer. This corresponds to the appropriate error level constant ( E_ERRORE_WARNING, and so on)
    errstrSpecifies the error message as a string
    Optional — The following parameters are optional
    errfileSpecifies the filename of the script file in which the error occurred, as a string
    errlineSpecifies the line number on which the error occurred, as a string
    errcontextSpecifies an array containing all the variables and their values that existed at the time the error occurred. Useful for debugging

    Here’s an example of a simple custom error handling function. This handler, customError() is triggered whenever an error occurred, no matter how trivial. It then outputs the details of the error to the browser and stops the execution of the script.

    Example

    <?php
    // Error handler function
    function customError($errno, $errstr){
        echo "<b>Error:</b> [$errno] $errstr";
    }
    ?>

    You need to tell the PHP to use your custom error handler function — just call the built-in set_error_handler() function, passing in the name of the function.

    Example

    <?php
    // Error handler function
    function customError($errno, $errstr){
        echo "<b>Error:</b> [$errno] $errstr";
    }
     
    // Set error handler
    set_error_handler("customError");
     
    // Trigger error
    echo($test);
    ?>

    Error Logging

    Log Error Messages in a Text File

    You can also logs details of the error to the log file, like this:

    Example

    <?php
    function calcDivision($dividend, $divisor){
        if($divisor == 0){
            trigger_error("calcDivision(): The divisor cannot be zero", E_USER_WARNING);
            return false;
        } else{
            return($dividend / $divisor);
        }
    }
    function customError($errno, $errstr, $errfile, $errline, $errcontext){
        $message = date("Y-m-d H:i:s - ");
        $message .= "Error: [" . $errno ."], " . "$errstr in $errfile on line $errline, ";
        $message .= "Variables:" . print_r($errcontext, true) . "\r\n";
        
        error_log($message, 3, "logs/app_errors.log");
        die("There was a problem, please try again.");
    }
    set_error_handler("customError");
    echo calcDivision(10, 0);
    echo "This will never be printed.";
    ?>

    Send Error Messages by E-Mail

    You can also send e-mail with the error details using the same error_log() function.

    Example

    <?php
    function calcDivision($dividend, $divisor){
        if ($divisor == 0){
            trigger_error("calcDivision(): The divisor cannot be zero", E_USER_WARNING);
            return false;
        } else{
            return($dividend / $divisor);
        }
    }
    function customError($errno, $errstr, $errfile, $errline, $errcontext){
        $message = date("Y-m-d H:i:s - ");
        $message .= "Error: [" . $errno ."], " . "$errstr in $errfile on line $errline, ";
        $message .= "Variables:" . print_r($errcontext, true) . "\r\n";
        
        error_log($message, 1, "[email protected]");
        die("There was a problem, please try again. Error report submitted to webmaster.");
    }
    set_error_handler("customError");
    echo calcDivision(10, 0);
    echo "This will never be printed.";
    ?>

    Trigger an Error

    Although the PHP engine triggers an error whenever it encounters a problem with your script, however you can also trigger errors yourself. This can help to make your application more robust, because it can flag potential problems before they turn into serious errors.

    To trigger an error from within your script, call the trigger_error() function, passing in the error message that you want to generate:

    trigger_error(“There was a problem.”);

    Consider the following function that calculates division of the two numbers.

    Example

    <?php
    function calcDivision($dividend, $divisor){
        return($dividend / $divisor);
    }
     
    // Calling the function
    echo calcDivision(10, 0);
    ?>

    If a value of zero (0) is passed as the $divisor parameter, the error generated by the PHP engine will look something like this:

    Warning: Division by zero in C:\wamp\www\project\test.php on line 3

    This message doesn’t look very informative. Consider the following example that uses the trigger_error() function to generate the error.

    Example

    <?php
    function calcDivision($dividend, $divisor){
        if($divisor == 0){
            trigger_error("The divisor cannot be zero", E_USER_WARNING);
            return false;
        } else{
            return($dividend / $divisor);
        }
    }
     
    // Calling the function
    echo calcDivision(10, 0);
    ?>

    Now the script generates this error message:

    Warning: The divisor cannot be zero in C:\wamp\www\project\error.php on line 4

    As you can see the error message generated by the second example explains the problem more clearly as compared to the previous one.

  • PHP Filters

    Validating and Sanitizing Data with Filters

    Sanitizing and validating user input is one of the most common tasks in a web application. To make this task easier PHP provides native filter extension that you can use to sanitize or validate data such as e-mail addresses, URLs, IP addresses, etc.

    To validate data using filter extension you need to use the PHP’s filter_var() function. The basic syntax of this function can be given with:

    filter_var(variablefilteroptions)

    This function takes three parameters out of which the last two are optional. The first parameter is the value to be filtered, the second parameter is the ID of the filter to apply, and the third parameter is the array of options related to filter. Let’s see how it works.

    Sanitize a String

    The following example will sanitize a string by removing all HTML tags from it:

    Example

    <?php
    // Sample user comment
    $comment = "<h1>Hey there! How are you doing today?</h1>";
     
    // Sanitize and print comment string
    $sanitizedComment = filter_var($comment, FILTER_SANITIZE_STRING);
    echo $sanitizedComment;
    ?>

    The output of the above example will look something like this:

    Hey there! How are you doing today?


    Validate Integer Values

    The following example will validate whether the value is a valid integer or not.

    Example

    <?php
    // Sample integer value
    $int = 20;
     
    // Validate sample integer value
    if(filter_var($int, FILTER_VALIDATE_INT)){
        echo "The <b>$int</b> is a valid integer";
    } else{
        echo "The <b>$int</b> is not a valid integer";
    }
    ?>

    In the above example, if variable $int is set to 0, the example code will display invalid integer message. To fix this problem, you need to explicitly test for the value 0, as follow:

    Example

    <?php
    // Sample integer value
    $int = 0;
     
    // Validate sample integer value
    if(filter_var($int, FILTER_VALIDATE_INT) === 0 || filter_var($int, FILTER_VALIDATE_INT)){
        echo "The <b>$int</b> is a valid integer";
    } else{
        echo "The <b>$int</b> is not a valid integer";
    }
    ?>

    Validate IP Addresses

    The following example will validate whether the value is a valid IP address or not.

    Example

    <?php
    // Sample IP address
    $ip = "172.16.254.1";
     
    // Validate sample IP address
    if(filter_var($ip, FILTER_VALIDATE_IP)){
        echo "The <b>$ip</b> is a valid IP address";
    } else {
        echo "The <b>$ip</b> is not a valid IP address";
    }
    ?>

    You can further apply validation for IPV4 or IPV6 IP addresses by using the FILTER_FLAG_IPV4 or FILTER_FLAG_IPV6 flags, respectively. Here’s an example:

    Example

    <?php
    // Sample IP address
    $ip = "172.16.254.1";
     
    // Validate sample IP address
    if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)){
        echo "The <b>$ip</b> is a valid IPV6 address";
    } else {
        echo "The <b>$ip</b> is not a valid IPV6 address";
    }
    ?>

    Sanitize and Validate Email Addresses

    The following example will show you how to sanitize and validate an e-mail address.

    Example

    <?php
    // Sample email address
    $email = "someone@@example.com";
     
    // Remove all illegal characters from email
    $sanitizedEmail = filter_var($email, FILTER_SANITIZE_EMAIL);
     
    // Validate email address
    if($email == $sanitizedEmail && filter_var($email, FILTER_VALIDATE_EMAIL)){
        echo "The $email is a valid email address";
    } else{
        echo "The $email is not a valid email address";
    }
    ?>

    Note: The FILTER_SANITIZE_EMAIL filter removes all invalid characters from the provided email address string except letters, digits and !#$%&'*+-=?^_`{|}~@.[].


    Sanitize and Validate URLs

    The following example will show you how to sanitize and validate a url.

    Example

    <?php
    // Sample website url
    $url = "http:://www.example.com";
     
    // Remove all illegal characters from url
    $sanitizedUrl = filter_var($url, FILTER_SANITIZE_URL);
     
    // Validate website url
    if($url == $sanitizedUrl && filter_var($url, FILTER_VALIDATE_URL)){
        echo "The $url is a valid website url";
    } else{
        echo "The $url is not a valid website url";
    }
    ?>

    Note: The FILTER_SANITIZE_URL filter removes all invalid characters from the provided URL string except letters, digits and $-_.+!*'(),{}|\\^~[]`<>#%";/?:@&=.

    You can also check whether a URL contains query string or not by using the flag FILTER_FLAG_QUERY_REQUIRED, as shown in the following example:

    Example

    <?php
    // Sample website url
    $url = "http://www.example.com?topic=filters";
     
    // Validate website url for query string
    if(filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED)){
        echo "The <b>$url</b> contains query string";
    } else{
        echo "The <b>$url</b> does not contain query string";
    }
    ?>

    See the tutorial on HTML URL to learn about the different components of a URL.


    Validate Integers Within a Range

    The following example will validate whether the supplied value is an integer or not, as well as whether it lies within the range of 0 to 100 or not.

    Example

    <?php
    // Sample integer value
    $int = 75;
     
    // Validate sample integer value
    if(filter_var($int, FILTER_VALIDATE_INT, array("options" => array("min_range" => 0,"max_range" => 100)))){
        echo "The <b>$int</b> is within the range of 0 to 100";
    } else{
        echo "The <b>$int</b> is not within the range of 0 to 100";
    }
    ?>
  • PHP Form Validation

    Sanitizing and Validating Form Data

    As you have seen in the previous tutorial, the process of capturing and displaying the submitted form data is quite simple. In this tutorial you will learn how to implement a simple contact form on your website that allows the user to send their comment and feedback through email. We will use the same PHP mail() function to send the emails.

    We are also going to implement some basic security feature like sanitization and validation of the user’s input so that user can not insert potentially harmful data that compromise the website security or might break the application.

    The following is our all-in-one PHP script which does the following things:

    • It will ask the users to enter his comments about the website.
    • The same script displays the contact form and process the submitted form data.
    • The script sanitizes and validates the user inputs. If any required field (marked with *) is missing or validation failed due to incorrect inputs the script redisplays the form with an error message for corresponding form field.
    • The script remembers which fields the user has already filled in, and prefills those fields when the form redisplayed due to validation error.
    • If the data submitted by the user are acceptable and everything goes well it will send an email to the website administrator and display a success message to the user.

    Type the following code in “contact.php” file and save in your project root directory:

    Example

    <?php
    // Functions to filter user inputs
    function filterName($field){
        // Sanitize user name
        $field = filter_var(trim($field), FILTER_SANITIZE_STRING);
        
        // Validate user name
        if(filter_var($field, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){
            return $field;
        } else{
            return FALSE;
        }
    }    
    function filterEmail($field){
        // Sanitize e-mail address
        $field = filter_var(trim($field), FILTER_SANITIZE_EMAIL);
        
        // Validate e-mail address
        if(filter_var($field, FILTER_VALIDATE_EMAIL)){
            return $field;
        } else{
            return FALSE;
        }
    }
    function filterString($field){
        // Sanitize string
        $field = filter_var(trim($field), FILTER_SANITIZE_STRING);
        if(!empty($field)){
            return $field;
        } else{
            return FALSE;
        }
    }
     
    // Define variables and initialize with empty values
    $nameErr = $emailErr = $messageErr = "";
    $name = $email = $subject = $message = "";
     
    // Processing form data when form is submitted
    if($_SERVER["REQUEST_METHOD"] == "POST"){
     
        // Validate user name
        if(empty($_POST["name"])){
            $nameErr = "Please enter your name.";
        } else{
            $name = filterName($_POST["name"]);
            if($name == FALSE){
                $nameErr = "Please enter a valid name.";
            }
        }
        
        // Validate email address
        if(empty($_POST["email"])){
            $emailErr = "Please enter your email address.";     
        } else{
            $email = filterEmail($_POST["email"]);
            if($email == FALSE){
                $emailErr = "Please enter a valid email address.";
            }
        }
        
        // Validate message subject
        if(empty($_POST["subject"])){
            $subject = "";
        } else{
            $subject = filterString($_POST["subject"]);
        }
        
        // Validate user comment
        if(empty($_POST["message"])){
            $messageErr = "Please enter your comment.";     
        } else{
            $message = filterString($_POST["message"]);
            if($message == FALSE){
                $messageErr = "Please enter a valid comment.";
            }
        }
        
        // Check input errors before sending email
        if(empty($nameErr) && empty($emailErr) && empty($messageErr)){
            // Recipient email address
            $to = '[email protected]';
            
            // Create email headers
            $headers = 'From: '. $email . "\r\n" .
            'Reply-To: '. $email . "\r\n" .
            'X-Mailer: PHP/' . phpversion();
            
            // Sending email
            if(mail($to, $subject, $message, $headers)){
                echo '<p class="success">Your message has been sent successfully!</p>';
            } else{
                echo '<p class="error">Unable to send email. Please try again!</p>';
            }
        }
    }
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Contact Form</title>
        <style type="text/css">
            .error{ color: red; }
            .success{ color: green; }
        </style>
    </head>
    <body>
        <h2>Contact Us</h2>
        <p>Please fill in this form and send us.</p>
        <form action="contact.php" method="post">
            <p>
                <label for="inputName">Name:<sup>*</sup></label>
                <input type="text" name="name" id="inputName" value="<?php echo $name; ?>">
                <span class="error"><?php echo $nameErr; ?></span>
            </p>
            <p>
                <label for="inputEmail">Email:<sup>*</sup></label>
                <input type="text" name="email" id="inputEmail" value="<?php echo $email; ?>">
                <span class="error"><?php echo $emailErr; ?></span>
            </p>
            <p>
                <label for="inputSubject">Subject:</label>
                <input type="text" name="subject" id="inputSubject" value="<?php echo $subject; ?>">
            </p>
            <p>
                <label for="inputComment">Message:<sup>*</sup></label>
                <textarea name="message" id="inputComment" rows="5" cols="30"><?php echo $message; ?></textarea>
                <span class="error"><?php echo $messageErr; ?></span>
            </p>
            <input type="submit" value="Send">
            <input type="reset" value="Reset">
        </form>
    </body>
    </html>

    Explanation of code

    You might think what that code was all about. OK, let’s get straight into it.

    • The filterName() function (line no-03) validate input value as person’s name. A valid name can only contain alphabetical characters (a-z, A-Z).
    • The filterEmail() function (line no-14) validate input value as email address.
    • The filterString() function (line no-25) only sanitize the input value by stripping HTML tags and special characters. It doesn’t validate the input value against anything.
    • The attribute action="contact.php" (line no-111) inside the <form> tag specifies that the same contact.php file display the form as well as process the form data.
    • The PHP code inside the value attribute of <input> and <textarea> e.g. <?php echo $name; ?> display prefilled value when form is redisplayed upon validation error.
    • The PHP code inside the .error class e.g. <span class="error"><?php echo $nameErr; ?></span> display error for corresponding field.

    Rest the thing we have already covered in previous chapters. To learn more about sanitize and validate filters, please check out the PHP Filter reference.

  • PHP Form Handling

    Creating a Simple Contact Form

    In this tutorial we are going to create a simple HMTL contact form that allows users to enter their comment and feedback then displays it to the browser using PHP.

    Open up your favorite code editor and create a new PHP file. Now type the following code and save this file as “contact-form.php” in the root directory of your project.

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Contact Form</title>
    </head>
    <body>
        <h2>Contact Us</h2>
        <p>Please fill in this form and send us.</p>
        <form action="process-form.php" method="post">
            <p>
                <label for="inputName">Name:<sup>*</sup></label>
                <input type="text" name="name" id="inputName">
            </p>
            <p>
                <label for="inputEmail">Email:<sup>*</sup></label>
                <input type="text" name="email" id="inputEmail">
            </p>
            <p>
                <label for="inputSubject">Subject:</label>
                <input type="text" name="subject" id="inputSubject">
            </p>
            <p>
                <label for="inputComment">Message:<sup>*</sup></label>
                <textarea name="message" id="inputComment" rows="5" cols="30"></textarea>
            </p>
            <input type="submit" value="Submit">
            <input type="reset" value="Reset">
        </form>
    </body>
    </html>

    Explanation of code

    Notice that there are two attributes within the opening <form> tag:

    • The action attribute references a PHP file “process-form.php” that receives the data entered into the form when user submit it by pressing the submit button.
    • The method attribute tells the browser to send the form data through POST method.

    Rest of the elements inside the form are basic form controls to receive user inputs. To learn more about HTML form elements please check out the HTML Forms tutorial.


    Capturing Form Data with PHP

    To access the value of a particular form field, you can use the following superglobal variables. These variables are available in all scopes throughout a script.

    SuperglobalDescription
    $_GETContains a list of all the field names and values sent by a form using the get method (i.e. via the URL parameters).
    $_POSTContains a list of all the field names and values sent by a form using the post method (data will not visible in the URL).
    $_REQUESTContains the values of both the $_GET and $_POST variables as well as the values of the $_COOKIE superglobal variable.

    When a user submit the above contact form through clicking the submit button, the form data is sent to the “process-form.php” file on the server for processing. It simply captures the information submitted by the user and displays it to browser.

    The PHP code of “process-form.php” file will look something like this:

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Contact Form</title>
    </head>
    <body>
        <h1>Thank You</h1>
        <p>Here is the information you have submitted:</p>
        <ol>
            <li><em>Name:</em> <?php echo $_POST["name"]?></li>
            <li><em>Email:</em> <?php echo $_POST["email"]?></li>
            <li><em>Subject:</em> <?php echo $_POST["subject"]?></li>
            <li><em>Message:</em> <?php echo $_POST["message"]?></li>
        </ol>
    </body>
    </html>

    The PHP code above is quite simple. Since the form data is sent through the post method, you can retrieve the value of a particular form field by passing its name to the $_POST superglobal array, and displays each field value using echo() statement.

    In real world you cannot trust the user inputs; you must implement some sort of validation to filter the user inputs before using them. In the next chapter you will learn how sanitize and validate this contact form data and send it through the email using PHP.