Server-Side Scripting: Chapter 1

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

Which protocol is used for communication between a client and a server on the web?

  • HTTP (Hyper Text Transfer Protocol) (correct)
  • TCP (Transmission Control Protocol)
  • SMTP (Simple Mail Transfer Protocol)
  • FTP (File Transfer Protocol)

Client-side scripts have full access to the server's operating system.

False (B)

What is the primary function of server-side scripting?

executing scripts on the server

PHP files use the extension ______.

<p>.php</p>
Signup and view all the answers

Match the local development environments with their corresponding operating systems:

<p>WAMP = Windows MAMP = Mac OS LAMP = Linux</p>
Signup and view all the answers

Which of the following is NOT a function that PHP can perform on a system?

<p>Modifying system hardware (C)</p>
Signup and view all the answers

PHP is interpreted on the client-side before sending the result to the server.

<p>False (B)</p>
Signup and view all the answers

What does XAMPP primarily enable developers to do?

<p>test web applications locally</p>
Signup and view all the answers

In PHP, code is placed between ______ and ______.

<?php/?>
Signup and view all the answers

Match the comment style with its description in PHP:

<p>// = Single-line comment</p> <h1>= Single-line comment</h1> <p>/* ... */ = Multi-line comment</p>
Signup and view all the answers

Which statement about PHP variables is correct?

<p>Variable names must start with a letter or underscore. (A)</p>
Signup and view all the answers

In PHP, the echo keyword is case-sensitive.

<p>False (B)</p>
Signup and view all the answers

What character is used to start a variable name in PHP?

<p>$</p>
Signup and view all the answers

In PHP, a variable's data type is automatically determined based on its ______.

<p>value</p>
Signup and view all the answers

Match the PHP data type with its description:

<p>Integer = Non-decimal number Float = Decimal number Boolean = True or False</p>
Signup and view all the answers

What will be the output of the following PHP code? <?php $x = 5; function myTest() { $y = 10; echo $x; } myTest(); ?>

<p>Error: Undefined variable (D)</p>
Signup and view all the answers

Variables declared within a function have a global scope and can be accessed anywhere in the script.

<p>False (B)</p>
Signup and view all the answers

How can you access a global variable from within a function in PHP?

<p>using the global keyword</p>
Signup and view all the answers

The PHP _________ keyword is used to access a global variable from within a function.

<p>global</p>
Signup and view all the answers

Which type of control structure allows executing a block of code repeatedly based on a condition?

<p>Loop (D)</p>
Signup and view all the answers

The for loop is used when the number of iterations is unknown.

<p>False (B)</p>
Signup and view all the answers

What are the three parts of a for loop?

<p>initialization, condition, increment/decrement</p>
Signup and view all the answers

The _________ loop executes a block of code at least once before checking the condition.

<p>do...while</p>
Signup and view all the answers

What does the PHP strlen() function return?

<p>The length of a string (D)</p>
Signup and view all the answers

The strpos() function returns the character position of the last match found in a string.

<p>False (B)</p>
Signup and view all the answers

Which PHP function converts a string to uppercase?

<p>strtoupper()</p>
Signup and view all the answers

The PHP function _________ removes whitespace from the beginning and end of a string.

<p>trim()</p>
Signup and view all the answers

In PHP, what is the purpose of casting?

<p>To convert a variable from one data type to another (D)</p>
Signup and view all the answers

Variables and Constants are the same.

<p>False (B)</p>
Signup and view all the answers

How do you create a constant in PHP?

<p>using the define() function</p>
Signup and view all the answers

In PHP, to use a constant you just refer to it like a regular variable (but it isn't preceded by a ______ sign).

<p>dollar</p>
Signup and view all the answers

Match PHP Magic Constants with their descriptions:

<p><strong>LINE</strong> = Current line number <strong>FILE</strong> = Full path and filename <strong>DIR</strong> = Directory of the file.</p>
Signup and view all the answers

In PHP, how are arguments passed by reference?

<p>Use &amp; before the parameter name (B)</p>
Signup and view all the answers

By using the ... operator in front of a function parameter, a function accepts an unknown number of arguments..

<p>True (A)</p>
Signup and view all the answers

If the data type mismatches in PHP7, what will occur?

<p>Fatal Error</p>
Signup and view all the answers

Arrays can be created _______ or formally

<p>informally</p>
Signup and view all the answers

Signup and view all the answers

Flashcards

How does the web work?

Uses the HTTP protocol to communicate between a client and a server.

Client-side scripts

Client-side scripts are executed by the client's browser, focusing on appearance and behavior.

Server-Side Scripting

Server-side scripting is executed on the server, allowing full access to the server's operating system.

When to use server-side scripting?

Dynamic web pages, authentication, and personalized content.

Signup and view all the flashcards

What is PHP?

PHP is a widely-used, open-source language for web development that is interpreted on the server.

Signup and view all the flashcards

What is a web server?

Software that accepts requests via HTTP or HTTPS.

Signup and view all the flashcards

WAMP, MAMP, LAMP

Software packages for setting up a local web server for development.

Signup and view all the flashcards

What is XAMPP?

An open-source web server solution package for web application testing on a local host.

Signup and view all the flashcards

PHP Syntax

PHP code is placed between and .

Signup and view all the flashcards

PHP Comments

Use //, # for single-line comments and /* */ for multi-line comments.

Signup and view all the flashcards

PHP Case Sensitivity

Keywords, classes, functions are not case-sensitive, but variable names are.

Signup and view all the flashcards

PHP Variables

In PHP, a variable starts with the $ sign.

Signup and view all the flashcards

PHP: Loosely Typed

PHP automatically associates a data type to the variable, depending on its value.

Signup and view all the flashcards

PHP Data Types

Strings, Integers, Floats, Booleans, Arrays, Objects, NULL, Resources.

Signup and view all the flashcards

Variable Scope

The part of the script where the variable can be referenced/used.

Signup and view all the flashcards

What is Global Scope?

A variable declared outside a function has GLOBAL SCOPE and can only be accessed outside a function

Signup and view all the flashcards

What is Local Scope?

A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function

Signup and view all the flashcards

PHP Comments

Single-Line Comments// comment here # comment here Multi-Line Comments /* multiple lines of comments here */

Signup and view all the flashcards

The global Keyword

The global keyword is used to access a global variable from within a function..

Signup and view all the flashcards

Echo

Outputs one or more strings, does not return a value.Can handle multiple parameters separated by commas.

Signup and view all the flashcards

Print

Output a single string and always returns 1.Sligth slower compared to echo in most cases.

Signup and view all the flashcards

Control Structures

Conditional statements, Loops and Jumps PHP has a number of control structures to change this default order of execution

Signup and view all the flashcards

Conditionals

Statements like if and switch that execute or skip statements depending on the value of an expression

Signup and view all the flashcards

Loops

Loops: Statements like while and for that execute other statements repetitively

Signup and view all the flashcards

Jumps

Jumps: Statements like break, return, and throw that cause the interpreter to jump to another part of the program

Signup and view all the flashcards

How do you assign string in PHP

Strings in PHP are surrounded by either double quotation marks, or single quotation marks.

Signup and view all the flashcards

How do you identify a length of string?

The PHP strlen() function returns the length of a string.

Signup and view all the flashcards

How to convert to a string in uppercase

The PHP strtoupper() function returns the string function

Signup and view all the flashcards

How to convert string in lower case

The PHP strtolower() function returns the string in lower case:

Signup and view all the flashcards

What is Casting?

Ensures a value is treated as the desired data type. Commonly done when mixing data from forms, URLs, or text to numeric operations.

Signup and view all the flashcards

PHP Constants

define(name, value);

Signup and view all the flashcards

PHP Magic constants

PHP also have predefined constants which always available.

Signup and view all the flashcards

PHP function

PHP has more than 1000 built-in functions

Signup and view all the flashcards

definition

Associative arrays are arrays that use named keys that you assign to them.

Signup and view all the flashcards

array combine

array array_combine(array keys, array values) produces a new array consisting of keys residing in the input parameter array keys, and corresponding values found in the input parameter array values

Signup and view all the flashcards

Study Notes

  • Server-Side Scripting is the first chapter. Included in the chapter are:
    • Introduction to server-side scripting
    • Server-side scripting languages
    • Use Basic Syntax
    • Write Comments
    • Utilize Variables
    • Manipulate Strings
    • Manipulate Numbers
    • Work with constants

Introduction to Server-Side Scripting

  • Web communication uses HTTP (Hyper Text Transfer Protocol) between a client and a server.
  • Requests range from a simple get request (fetch static content) to post and delete requests (add/delete resources).
  • Each request/response has a header and an optional body.
  • Servers remain active, waiting for and handling client requests.

Communication Scenarios

  • Communication Scenarios include communication between files and the Web Server, as well as database access.
  • Static content includes files processed directly through the web server.
  • Dynamic content uses web applications to access files and databases to deliver a customized output.

Server-Side vs Client-Side Scripting Languages

  • Client-side scripts:
    • Executed by the client (browser).
    • They are used for the appearance/behavior of a webpage.
    • Limited access to the underlying operating system.
    • Rendering issues can occur differently depending on browser.
  • Server-Side Scripting Languages:
    • Scripts are executed on the server and require a server-side scripting engine.
    • They have full access to the server's operating system.
    • Languages include PHP, Python, Ruby, C#, and JavaScript (Node.js).

Uses for Server-Side Scripting

  • Dynamic webpages:
    • Authentication, authorization, and session tracking.
    • Content personalization/customization based on user behavior.
    • Template-driven page generation.
    • Handling POST form input.
    • Communication with other programs, libraries, and APIs (e.g., sending emails).

PHP

  • PHP (Hypertext Protocol) is free, open-source language for web pages suitable for web development.
  • It can run on various platforms and works with most servers, using ".php" file extensions.
  • PHP can perform system functions, such as creating/modifying/closing files.
  • PHP functions include adding/deleting/modifying elements within a database.
  • It can restrict user access to specific webpages.
  • It offers data encryption and runs on Windows, Linux, and macOS.
  • PHP requires an Apache web server or XAMPP to run; it is interpreted on the server before browser delivery.

Apache Web Server

  • A Web server accepts requests via HTTP/HTTPS.
  • The Apache HTTP Server is open-source, free and cross-platform.
  • It manages various files, including HTML, images, MP3s, and RSS feeds.
  • It dynamically generates non-static files using server-side programs like PHP.
  • It is released under Apache License 2.0.

Local Web Servers

  • WAMP, MAMP, and LAMP are software packages used to setup local web servers for development.
    • WAMP (Windows, Apache, MySQL, PHP) for Windows.
    • MAMP (Mac, Apache, MySQL, PHP) for Mac.
    • LAMP (Linux, Apache, MySQL, PHP) for Linux.
  • These servers are easy to set up, but not secure enough for public use (development and testing purposes only).

XAMPP

  • XAMPP is a free and open-source web server solution package mainly for local web application testing.
  • X = Cross-platform
  • A = Apache Server
  • M = MariaDB/MySQL
  • P = PHP
  • P = Perl

Benefits of XAMPP

  • Development and website testing locally, which reduces the need for live internet connections.
  • It supports backend development utilizing PHP and MySQL/MariaDB.
  • It works with all operating systems including: Windows, macOS, and Linux.
  • Apache, MySQL, and PHP are bundled together, simplifying manual setup and configuration.
  • It allows for local website and application testing, before launch.

PHP Syntax

  • PHP code is enclosed between and .
  • One or more code blocks may be embedded in an HTML file.
  • Function names are not case-sensitive, but variable names are.

PHP Code Blocks in HTML

  • PHP can be embedded within HTML.

PHP Comments

  • Single-line comments use "// comment here" or "# comment here".
  • Multi-line comments use "/* multiple lines of comments here */".
  • You can use comments to explain code logic or disable code segments.

PHP Case Sensitivity

  • Keywords (if, else, while, echo, etc.), classes, functions, and user-defined functions are NOT case-sensitive.
  • Variable names are case-sensitive.

PHP Variables

  • Start with a $ sign, such as $x = 5; or $y = "John";
  • Variable names must start with a letters or underscore and can only contain alpha-numeric characters and underscores.
  • PHP does not need a command to declare variables; they are created upon initial assignment.

Data Typing

  • PHP automatically sets a data type to a variable based on its value.
  • Using PHP7 there is the option to type the variable, and declare which datatype is expected.

Examples of variable types

  • $x = 5; // $x is an integer
  • $y = "John"; // $y is a string
  • echo $x;
  • echo $y;
  • The Data Types that PHP supports include: String, Integer, Float, Boolean, Array, Object, NULL, and Resource

PHP Data Types

  • Strings: Represented as text in quotes ("Hello World").
  • Integers: Represented as non-decimal numbers.
  • Floats (Doubles): Represented with decimals.
  • Booleans: Represented with true or false values.
  • Arrays: Represented as collections of values in one variable.
  • Objects: Represented as a hold for data and methods related to that data.
  • NULL: A variable with no value assigned.
  • Resources: Represented as special references (e.g., database connections).

Variable Scope

  • Variables in PHP can be delcared anywhere on a script.
  • Variable scope refers to the section of the script from where the variable can be used.
    • Local: Only assessable within a function.
    • Global: A variable declared outside a function.
      • Using x within a function will generate an error.
    • Static Scope

The global Keyword

  • Used to access a global variable from within a function, using global before the variables (inside the function).
  • PHP stores all global variables using $GLOBALS[index], the index holds its' name. The array can update variables directly.

PHP Echo/Print

  • Echo: Outputs one or more strings; does not return a value, and can handle multiple comma separated parameters.
  • Print: Outputs one string, always returns 1, and is slightly slower than echo.

Control Structures

  • Control structures alter the default order of execution.
    • Conditionals: (if and switch) execute/skip statements based on an expression.
    • Loops: (while and for) repeatedly execute statements.
    • Jumps: (break, return, and throw) cause the interpreter to jump to another part of the program.

Conditionals in PHP

  • Conditionals perform actions based on "if", "else" and "else if" parameters.

Loops in PHP

  • PHP has a number of built in loops:
    • For: loops through a block of code a set number of times
    • While: loops through a block of code while a set condition is true
    • Do/While: loops through a block of code once before checking to see if the condition is true

For Loop syntax

  • For: loops through a block of code a set number of times
  • for (initialization; condition; increment/decrement) { // code block to execute. }

While Loop syntax

  • While: loops through a block of code while a set condition is true
  • while (condition) { // code block to execute. }

Do...While Loop syntax

  • Do/While: loops through a block of code once before checking to see if the condition is true
  • while (condition) { // code block to execute. }

PHP Strings

  • PHP strings are surrounded by either single/double quotation marks.
  • Double quotes perform operations for special characters: example:
    • $x = "John";
    • echo "Hello $x";
  • Single quotes do not perform operations, so variable names are returned as written.

String Functions in PHP

  • strlen(): Returns the length of a string. Example: echo strlen("Hello world!"); returns //12
  • str_word_count(): Counts the words in a string. Example: echo str_word_count("Hello world!"); returns //2
  • strpos(): Searches a text within a string. Upon finding a match, the character postion of the first match is returned. Example: echo strpos("Hello world!", "world"); returns //6

PHP - Modify Strings

  • strtoupper() : The string is returned in uppercase. To use this function $x = "Hello World!"; followed by echo strtoupper($x);
  • strtolower() : The string is returned in lowercase. To use this function $x = "Hello World!"; followed by echo strtolower($x);
  • str_replace() : The function replaces characters in the string. To use this function $x = "Hello World!";; Followed by echo str_replace("World", "Dolly", $x);
  • strrev(): The function reverses a string. $x = "Hello World!"; followed by echo strrev($x).
  • trim(): Any whitespace at the start and end is removed. $x = " Hello World! "; followed by echo trim($x);
  • explode(): The function splits a string into an array. The first parameter in explode() represents the "seperator". To use the function: $x = "Hello World!"; followed by the code $y = explode(" ", $x);

PHP Casting

  • Ensure data is treated as the intended type; used when mixing data from forms, URLs, or text to numeric operations.
  • Cast Syntax: (int) $variable, (float) $variable, (bool) $variable, etc.
  • Example:

PHP Constants

  • A constant's value cannot be changed during the script.
  • Valid constant names must start with a letter or underscore (without a $ sign).
  • Constants are automatically global across the script.
  • To create a constant use define().
    • define(name, value);
    • define("ROOT_LOCATION", "/usr/local/www/");
  • To display use: $directory = ROOT_LOCATION;

Example of PHP Constants

  • constants are global and can be used throughout the whole script. define("GREETING", "Welcome to W3Schools.com!"); function myTest() { echo GREETING; } myTest();

PHP Magic Constants

__LINE__ : Current line number. __FILE__ : Full path and filename. __DIR__ : Directory of the file. __FUNCTION__,__CLASS__,__METHOD__,__NAMESPACE__.

PHP Functions

  • PHP has more than 1000 built in functions that can be modified.
  • A function is a block of statements that can be used repeatedly in a program, however the functions will not run unless it is activated.
  • A function will be executed by a call to the function.
  • A user-defined function word function, followed by the word echo "$fname Refsnes.";

Passing arguments to functions

  • Passing by value is used ,and the orginal variables value is not changed if the recipient variable is changed.
  • Passing by reference, appends an ampersand(&) to the front of the parameter(s). Any changes made to a variable passed by refernce change the original version.

Default and Optional arguments

  • Default values can input during the declarations of arguments. The value will automatically be assigned if not declared for a particular parameter
  • Arguments are designated options as long as they are made the end of the list and assigned to a default value of "nothing".
  • Example: function salestax($price,$tax="")

Various Arguments.

  • functions use three dots in front of functions to accept an unknown number arguments.
  • This type of function is called a variadic function and becomes an array
  • Only one variable with this variable can be used at a time and must be the last argument.

PHP 7 Declarations

  • An option to specify the expected data type when declare a function.
  • When the strict declarations are specified, if PHP sees different data type, a fatal error will appear.
  • To use declaration: <?php declare(strict_types=1); function addNumbers (int a, int b)

Arrays

  • Arrays store more than a single value.
  • Arrays ca nbe made informally, simply by making its data by referencing it $state[0] = "Delaware";
  • Arrays can be created formally by using the array() function array array([item1 [,item2 ... [,itemN]]]) $languages = array ("English", "Gaelic", "Spanish");

Indexed arrays

  • arrays can use numerical values for reference
  • Two ways this can be done:
    • $cars = array("Volvo", "BMW", "Toyota"); or
    • $cars[0] = "Volvo";
    • $cars[1] = "BMW";
    • $cars[2] = "Toyota"

Associative Arrays

  • Associative arrays assign the keys.
  • There are two ways that can set up the key's:
    • $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); OR
    • $age['Peter'] = "35";
    • $age['Ben'] = "37";
    • $age['Joe'] = "43";

Array functions

  • Range(): function provides a way to to fill the array consisting of range of values:
    • $die = range(0,6);
    • $even = range(0,20,2);
    • $letters = range("A","F")

How to Output Arrays

  • print_r() Is used to show the code of arrays and objects in formatted form to read.
  • To use the command: <?php $fruits = array ("Value", "Value2); print_r($fruits);

How to add and remove array elements

  • array_push() The array_push() function adds variable onto the end of the target array. Example: $states = array=("Valuet", "Value2); array_push($states,"California","Texas").

array_pop() function

  • Returns the element from the target array. Example: $states = array("Valuet"."Name", Secondname): $state=array_pop($states):

Array Shift

  • array_shift() The array_shift() function can be similar to array_pop- the differnece, it will return the first item it finds in the target array.

  • Array unshift Array is similar in the way array_push () works. However it adds elements to the top of the array instead of top of the array. $states = array("Secondname"."Name"):

Array_unshift ($states, Cailifornia, second Name).

Array-pad () function

  • array_pad() is used to modify an array by changing the length by adding a variable to the beginning or the end. array_pad ($array; $size; $value).

Syntax for locating array elements.

  • array-keys () Returns all the keys located the array
  • Synatx array_Keys(array; search- value, $, strict) Array - the input array Search_Value the optional value. If the the provided array. Keys. Will only the provide, the key of the mathing elements in the array. ###array Key- exists Determines if the specified indicator occurs to the arrary

array intersect is used to array, and it returns (false) otherwise. The value array Key (_ exists S key to check, $ array Name); array Key ( "key",$ is fruit the ///.

array intersect) is used to find the common values in one array,

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

Server-side Web Scripting Fundamentals
5 questions
Server-side Web Scripting Quiz
16 questions
Servidores Web: Características y Peticiones HTTP
10 questions
Use Quizgecko on...
Browser
Browser