Server Side Scripting Basic PDF

Document Details

HighQualityTimpani5591

Uploaded by HighQualityTimpani5591

Mekelle University

Tags

PHP programming server-side scripting web development dynamic web pages

Summary

This document provides an introduction to server-side scripting, focusing on PHP. It details the core concepts and functionalities behind generating dynamic web content using PHP. The document also explores various aspects of website development practices.

Full Transcript

Chapter 3 Server Side Scripting Basic 1.1.Introduction to server-side scripting Server-side scripting is the process of executing scripts on a web server to generate dynamic content that is then sent to the client's web browser. It allows for the creation of interac...

Chapter 3 Server Side Scripting Basic 1.1.Introduction to server-side scripting Server-side scripting is the process of executing scripts on a web server to generate dynamic content that is then sent to the client's web browser. It allows for the creation of interactive and personalized web applications by processing data, performing calculations, accessing databases, and generating dynamic HTML or other content. Server-side scripting is typically used for tasks such as form processing, user authentication, database interactions, and generating dynamic web pages. When a client sends a request to a web server, the server-side script is executed to process the request and generate a response. The server-side script can interact with databases, perform complex calculations, and generate dynamic content based on the request parameters or user data. 1.2. Server-side scripting languages Server-side scripting languages provide the necessary tools and syntax to write scripts that can be executed on the server. These languages are specifically designed for server-side processing and have features to handle web-related tasks efficiently. Common server-side scripting languages include PHP, Python, Ruby, Java, and ASP.NET. 1. Dynamic Content Generation: Server-side scripting allows for the creation of dynamic web pages that can display personalized content based on user input or data from databases. 2. Data Processing and Validation: Server-side scripts can process and validate data submitted by users through forms, ensuring data integrity and security. 3. Database Interaction: Server-side scripting languages can interact with databases to perform operations such as retrieving data, updating records, and executing complex queries. 4. Application Logic: Server-side scripts can implement business logic, perform calculations, and handle complex operations required by web applications. PHP Fundamentals It is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's ASP 1 What is PHP?  PHP is an acronym for "PHP: Hypertext Preprocessor"  PHP is a widely-used, open source scripting language  PHP scripts are executed on the server  PHP is free to download and use What is a PHP File?  PHP files can contain text, HTML, CSS, JavaScript, and PHP code  PHP code are executed on the server, and the result is returned to the browser as plain HTML  PHP files have extension ".php" What Can PHP Do?  Generate dynamic page content  Create, open, read, write, delete, and close files on the server  Collect form data  Sending and receiving cookies  Add, delete, modify data in your database  Can be used to control user-access  It can encrypt data With PHP you are not limited to output HTML. You can output images, PDF files, and even Flash movies. You can also output any text, such as XHTML and XML Why PHP?  PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)  PHP is compatible with almost all servers used today (Apache, IIS, etc.)  PHP supports a wide range of databases  PHP is free. Download it from the official PHP resource: www.php.net 2  PHP is easy to learn and runs efficiently on the server side What Do I Need? To start using PHP, you can: Install Apache and PHP on a Windows system, you can follow these general steps: 1. Download Apache: Go to the Apache Haus website (https://www.apachehaus.com/) and download the latest version of Apache HTTP Server for Windows. Choose the appropriate version based on your system architecture (32-bit or 64-bit). 2. Run Apache Installer: Once the download is complete, run the Apache installer. Follow the installation wizard, and during the process, you can customize the installation path if desired. By default, Apache will be installed in "C:\Apache24". 3. Start Apache: After the installation is complete, start the Apache server by clicking on the Windows Start button, searching for "Apache HTTP Server", and selecting "Apache HTTP Server" from the list. This will start the Apache service. 4. Test Apache: Open a web browser and enter "http://localhost/" or "http://127.0.0.1/" in the address bar. If Apache is running properly, you should see the default Apache welcome page. 1.2.1 PHP Basics Basic PHP Syntax A PHP script can be placed anywhere in the document. A PHP script starts with : The default file extension for PHP files is ".php". A PHP file normally contains HTML tags, and some PHP scripting code. Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP function "echo" to output the text "Hello World!" on a web page: !DOCTYPE html> php My first PHP page Note: PHP statements end with a semicolon (;) 3 Comments in PHP A comment in PHP code is a line that is not read/executed as part of the program. Its only purpose is to be read by someone who is looking at the code. Comments can be used to:  Let others understand what you are doing  Remind yourself of what you did - Most programmers have experienced coming back to their own work a year or two later and having to re-figure out what they did. Comments can remind you of what you were thinking when you wrote the code PHP supports several ways of commenting: PHP Case Sensitivity In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are NOT case-sensitive. In the example below, all three echo statements below are legal (and equal): Example: However; all variable names are case-sensitive. In the example below, only the first statement will display the value of the $color variable (this is because $color, $COLOR, and $coLOR are treated as three different variables): Example: Creating (Declaring) PHP Variables In PHP, a variable starts with the $ sign, followed by the name of the variable: Example After the execution of the statements above, the variable $txt will hold the value Hello world!, the variable $x will hold the value 5, and the variable $y will hold the value 10.5. PHP Variables A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for PHP variables:  A variable starts with the $ sign, followed by the name of the variable  A variable name must start with a letter or the underscore character  A variable name cannot start with a number  A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _)  Variable names are case-sensitive ($age and $AGE are two different variables) PHP Variables Scope In PHP, variables can be declared anywhere in the script. The scope of a variable is the part of the script where the variable can be referenced/used. PHP has three different variable scopes:  local  global  static Global and Local Scope A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function: Example A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function: PHP The global Keyword The global keyword is used to access a global variable from within a function. To do this, use the global keyword before the variables (inside the function): Example PHP The static Keyword Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job. To do this, use the static keyword when you first declare the variable: Example function myTest() { static $x = 0; echo $x; $x++; } myTest(); 6 echo ""; myTest(); echo ""; myTest(); ?> PHP 5 echo and print Statements In PHP there are two basic ways to get output: echo and print. They are both used to output data to the screen. The differences are small:  echo has no return value while print has a return value of 1 so it can be used in expressions.  echo can take multiple parameters (although such usage is rare) while print can take one argument.  echo is marginally faster than print. PHP Data Types Variables can store data of different types, and different data types can do different things. PHP supports the following data types:  String , Integer, Float (floating point numbers - also called double), Boolean, Array, Object, NULL and Resource PHP Integer An integer is a whole number (without decimals). It is a number between - 2,147,483,648 and +2,147,483,647. Rules for integers:  An integer must have at least one digit (0-9)  An integer cannot contain comma or blanks  An integer must not have a decimal point  An integer can be either positive or negative  Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based - prefixed with 0x) or octal (8-based - prefixed with 0) PHP Array An array stores multiple values in one single variable. In the following example $cars is an array. The PHP var_dump() function returns the data type and value: Example: 7 PHP NULL Value Null is a special data type which can have only one value: NULL. A variable of data type NULL is a variable that has no value assigned to it. Tip: If a variable is created without a value, it is automatically assigned a value of NULL. Variables can also be emptied by setting the value to NULL: PHP String Functions In this chapter we will look at some commonly used functions to manipulate strings. Get the Length of a String The PHP strlen() function returns the length of a string (number of characters). The example below returns the length of the string "Hello world!": Example echo strlen("Hello world!"); // outputs 12 Count the Number of Words in a String The PHP str_word_count() function counts the number of words in a string: Example echo str_word_count("Hello world!"); // outputs 2 Reverse a String The PHP strrev() function reverses a string Example echo strrev("Hello world!"); // outputs !dlrow olleH Search For a Specific Text Within a String The PHP strpos() function searches for a specific text within a string. If a match is found, the function returns the character position of the first match. If no match is found, it will return FALSE. The example below searches for the text "world" in the string "Hello world!": Example echo strpos("Hello world!", "world"); // outputs 6 Replace Text Within a String PHP str_replace() function replaces some characters with some other characters in a string.The example below replaces the text "world" with "There": Example echo str_replace("world", "There", "Hello world!"); // outputs Hello There! PHP Constants 8 A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name). Note: Unlike variables, constants are automatically global across the entire script. Create a PHP Constant To create a constant, use the define() function. Syntax define(name, value, case-insensitive) Parameters: name: Specifies the name of the constant value: Specifies the value of the constant case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false The example below creates a constant with a case-sensitive name: Example Constants are Global Constants are automatically global and can be used across the entire script. The example below uses a constant inside a function, even if it is defined outside the function: Example PHP Operators Operators are used to perform operations on variables and values. PHP divides the operators in the following groups:  Arithmetic operators  Assignment operators  Comparison operators  Increment/Decrement operators  Logical operators  String operators  Array operators 9 PHP Arithmetic Operators The PHP arithmetic operators are used with numeric values to perform common arithmetical operations, such as addition, subtraction, multiplication etc. Operator Name Example Result + Addition $x + $y Sum of $x and $y - Subtraction $x - $y Difference of $x and $y * Multiplication $x * $y Product of $x and $y / Division $x / $y Quotient of $x and $y % Modulus $x % $y Remainder of $x divided by $y ** Exponentiation $x ** $y Result of raising $x to the $y'th power PHP Assignment Operators The PHP assignment operators are used with numeric values to write a value to a variable. The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the assignment expression on the right Assignment Same as... Description x=yx=y The left operand gets set to the value of the expression on the right x += y x = x + y Addition x -= y x = x - y Subtraction x *= y x = x * y Multiplication x /= y x = x / y Division x %= y x = x % y Modulus PHP Increment / Decrement Operators The PHP increment operators are used to increment a variable's value and decrement operators are used to decrement a variable's value Operator Name Description ++$x Preincrement Increments $x by one, then returns $x $x++ Postincrement Returns $x, then increments $x by one --$x Predecrement Decrements $x by one, then returns $x $x-- Postdecrement Returns $x, then decrements $x by one PHP Logical Operators Operator Name Example Result and And $x and $y True if both $x and $y are true or Or $x or $y True if either $x or $y is true xor Xor $x xor $y True if either $x or $y is true, but not both && And $x && $y True if both $x and $y are true || Or $x || $y True if either $x or $y is true ! Not !$x True if $x is not true PHP Advanced: Control Structures PHP Conditional Statements Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this. In PHP we have the four conditional statements: 1. if statement - executes some code only if a specified condition is true 10 2. if...else statement - executes some code if a condition is true and another code if the condition is false 3. if...elseif....else statement - specifies a new condition to test, if the first condition is false 4. switch statement - selects one of many blocks of code to be executed without range. PHP - The if Statement The if statement is used to execute some code only if a specified condition is true. if (condition) { code to be executed if condition is true; } The example below will output "Have a good day!" if the current time (HOUR) is less than 20: Example PHP - The if...else Statement Use the if....else statement to execute some code if a condition is true and another code if the condition is false. Syntax if (condition) { code to be executed if condition is true; } else { code to be executed if condition is false; } The example below will output "Have a good day!" if the current time is less than 20, and "Have a good night!" otherwise: PHP - The if...elseif....else Statement Use the if....elseif...else statement to specify a new condition to test, if the first condition is false 11 Syntax if (condition) { code to be executed if condition is true; } elseif (condition) { code to be executed if condition is true; } else { code to be executed if condition is false; } Example: The PHP switch Statement Use the switch statement to select one of many blocks of code to be executed. Syntax switch (n) { case label1: code to be executed if n=label1; break; case label2: code to be executed if n=label2; break; case label3: code to be executed if n=label3; break;... default: code to be executed if n is different from all labels; } This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. 12 If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found. Example: PHP while loops execute a block of code while the specified condition is true. PHP Loops Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal code-lines in a script, we can use loops to perform a task like this. In PHP, we have the four looping statements: 1. while - loops through a block of code as long as the specified condition is true 2. do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true 3. for - loops through a block of code a specified number of times 4. foreach - loops through a block of code for each element in an array The PHP while Loop The while loop executes a block of code as long as the specified condition is true. Syntax while (condition is true) { code to be executed; } Example: The PHP do...while Loop The do...while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true. Syntax do { code to be executed; } while (condition is true); The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will write some output, and then increment the variable $x with 1. Then the condition is checked (is $x less than, or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5: Example: Notice that in a do while loop the condition is tested AFTER executing the statements within the loop. This means that the do while loop would execute its statements at least once, even if the condition is false the first time. The example below sets the $x variable to 6, then it runs the loop, and then the condition is checked Example: The PHP for Loop The for loop is used when you know in advance how many times thescript should run. Syntax for (init counter; test counter; increment counter) { code to be executed; } 14 Parameters:  init counter: Initialize the loop counter value  test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.  increment counter: Increases the loop counter value The example below displays the numbers from 0 to 10: The PHP foreach Loop The foreach loop works only on arrays, and is used to loop through each key/value pair in an array. Syntax foreach ($array as $value) { code to be executed; } For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element. The following example demonstrates a loop that will output the values of the given array ($colors): PHP 5 Functions PHP User Defined Functions Besides the built-in PHP functions, we can create our own functions. A function is a block of statements that can be used repeatedly in a program.  A function will not execute immediately when a page loads.  A function will be executed by a call to the function. Create a User Defined Function in PHP A user defined function declaration starts with the word "function": Syntax function functionName() { code to be executed; } Note: A function name can start with a letter or underscore (not anumber). Tip: Give the function a name that reflects what the function does! 15 In the example below, we create a function named "writeMsg()". The opening curly brace ( { ) indicates the beginning of the function code and the closing curly brace ( } ) indicates the end of the function. The function outputs "Hello world!". To call the function, just write its name: PHP Function Arguments Information can be passed to functions through arguments. An argument is just like a variable. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just seperate them with a comma. The following example has a function with one argument ($fname). When the familyName() function is called, we also pass along a name (e.g. Jani), and the name is used inside the function, which outputs several different first names, but an equal last name: The following example has a function with two arguments ($fname and$year): PHP Functions - Returning values To let a function return a value, use the return statement: PHP Arrays An array stores multiple values in one single variable: Example What is an Array? An array is a special variable, which can hold more than one value at a time. If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this: $cars1 = "Volvo"; $cars2 = "BMW"; $cars3 = "Toyota"; However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300? The solution is to create an array! An array can hold many values under a single name, and you can access the values by referring to an index number. Create an Array in PHP In PHP, the array() function is used to create an array: array(); In PHP, there are three types of arrays:  Indexed arrays - Arrays with a numeric index  Associative arrays - Arrays with named keys  Multidimensional arrays - Arrays containing one or more arrays Loop through an Indexed Array To loop through and print all the values of an indexed array, you could use a for loop, like this: 17 PHP Global Variables - Superglobals Several predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special. The PHP superglobal variables are:  $GLOBALS  $_SERVER  $_REQUEST  $_POST  $_GET  $_FILES  $_ENV  $_COOKIE  $_SESSION $GLOBALS: This variable is an associative array that holds references to all global variables in the PHP script. It allows you to access global variables from anywhere in the script. $_SERVER: It is an array that contains information about the server and the execution environment. It includes details such as server paths, request headers, script location, and more. $_REQUEST: This variable contains the values of both $_GET and $_POST variables, as well as the values from cookies. It provides a way to access user input data regardless of whether it was sent via GET or POST methods. $_POST: It is an associative array that holds the values of variables sent to the script using the HTTP POST method. It is commonly used to retrieve form data submitted by the user. $_GET: Similar to $_POST, $_GET is an associative array that holds the values of variables sent to the script using the HTTP GET method. It is commonly used to retrieve values from URLs or query strings. $_FILES: This variable is an associative array that contains information about uploaded files in a multipart form request. It provides access to details such as file names, temporary file locations, and file sizes. $_ENV: It is an associative array that holds the values of environment variables set on the server or in the system. These variables can be useful for accessing configuration settings or system- specific information. $_COOKIE: This variable holds the values of cookies sent by the client to the server. It allows you to access and manipulate cookie data, such as user preferences or session identifiers. $_SESSION: It is an associative array that contains session variables that are specific to each user session. It is commonly used to store and retrieve user-specific data across multiple pages or requests. 18

Use Quizgecko on...
Browser
Browser