Introduction to PHP

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

Rasmus Lerdorf is best known for what contribution to web development?

  • Pioneering client-side scripting with JavaScript.
  • Developing the Apache HTTP Server.
  • Designing the MySQL database system.
  • Creating the first version of PHP for personal use. (correct)

Which characteristic distinguishes PHP from client-side scripting languages?

  • PHP is a server-side scripting language. (correct)
  • PHP is executed in the user's browser.
  • PHP only works with Microsoft SQL Server.
  • PHP code is visible to the end user.

What does it mean for PHP to be 'cross-platform'?

  • It runs natively on various operating systems like Unix, Windows, and Mac OS X. (correct)
  • It requires specific hardware configurations to operate.
  • It can only be used on Apache servers.
  • It is compatible with all web browsers.

How does PHP's open-source nature benefit web developers?

<p>It provides a large community for support and an abundant extension library. (B)</p> Signup and view all the answers

What aspect of PHP makes it easy for developers familiar with C to learn?

<p>PHP uses C link syntax. (A)</p> Signup and view all the answers

What role do opening and closing tags play in PHP parsing?

<p>They tell PHP where to start and stop interpreting code. (D)</p> Signup and view all the answers

Which of the following is NOT a valid way to open a PHP scripting block?

<p>&lt;// ?&gt; (A)</p> Signup and view all the answers

How does PHP handle whitespace in code?

<p>PHP ignores extra spaces, allowing for more readable code. (A)</p> Signup and view all the answers

What is the purpose of a semicolon in PHP?

<p>To separate and distinguish one instruction from another. (A)</p> Signup and view all the answers

Which of the following is true regarding case sensitivity in PHP?

<p>PHP is case-sensitive for variables, objects, and functions. (D)</p> Signup and view all the answers

How are comments typically added to PHP code for single-line comments?

<p><code>// Comment</code> or <code># Comment</code> (D)</p> Signup and view all the answers

In PHP, what is the role of the php.ini file?

<p>It configures PHP settings, affecting PHP's functionality. (C)</p> Signup and view all the answers

Which of the following php.ini settings is used to turn off short open tags?

<p><code>short_open_tag = Off</code> (A)</p> Signup and view all the answers

What is the purpose of the disable_functions directive in php.ini?

<p>To prevent certain functions from being used for security reasons. (B)</p> Signup and view all the answers

Which php.ini setting controls the maximum time a script is allowed to run?

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

Which php.ini setting would you use to automatically include a file at the beginning of every PHP script?

<p><code>auto-prepend-file</code> (B)</p> Signup and view all the answers

What significance does a dollar sign ($) have when defining variables in PHP?

<p>It represents a variable. (C)</p> Signup and view all the answers

In PHP, how do you define a constant?

<p>Using the <code>define()</code> function. (D)</p> Signup and view all the answers

Which of the following is true about variable scope in PHP functions?

<p>Variables declared inside a function are local by default. (A)</p> Signup and view all the answers

How can a global variable be accessed within a PHP function?

<p>By using the <code>global</code> keyword or the <code>$GLOBALS</code> array. (C)</p> Signup and view all the answers

What is the purpose of a static variable within a PHP function?

<p>It allows the variable to retain its value between function calls. (A)</p> Signup and view all the answers

How are variables passed from an HTML form to a PHP script using the GET method?

<p>As part of the URL, as a query string. (B)</p> Signup and view all the answers

How are variables accessed in a PHP script when they are submitted via the POST method?

<p>Using the <code>$_POST</code> array. (A)</p> Signup and view all the answers

What is a primary advantage of using the POST method over the GET method for submitting forms?

<p>POST requests are more secure because the data isn't visible in the URL. (B)</p> Signup and view all the answers

In PHP, how do you represent variables?

<p>With a dollar sign ($) at the beginning of the variable name. (A)</p> Signup and view all the answers

What determines how terms in an expression are grouped together?

<p>Operator precedence. (B)</p> Signup and view all the answers

Which type of operator is ?:?

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

Which control structure is best suited for selecting one of many blocks of code to execute?

<p>switch statement (C)</p> Signup and view all the answers

What is the primary use case for the for loop in PHP?

<p>Executing a block of code a specified number of times. (B)</p> Signup and view all the answers

What is the key difference between a while loop and a do...while loop in PHP?

<p>A <code>do...while</code> loop always executes the code block at least once. (A)</p> Signup and view all the answers

What is the foreach loop primarily used for in PHP?

<p>Looping through arrays. (B)</p> Signup and view all the answers

What does the break statement do within a loop?

<p>It terminates the execution of the loop prematurely. (B)</p> Signup and view all the answers

What is the function of the continue statement in a loop?

<p>It terminates the current iteration and proceeds to the next one. (A)</p> Signup and view all the answers

Which of the following best describes what an array is?

<p>A data structure that stores one or more similar types of values in a single value. (C)</p> Signup and view all the answers

What is the key difference between a numeric array and an associative array in PHP?

<p>Numeric arrays use numbers as indices, while associative arrays use strings. (D)</p> Signup and view all the answers

What distinguishes a multi-dimensional array from a single-dimensional array?

<p>Each element in a multi-dimensional array can also be an array. (A)</p> Signup and view all the answers

In PHP, if you’re working with salary data of each employee in a company, what type of array will be helpful?

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

What are the key components of a function definition?

<p>A special word function, name, a parameter list and function body. (A)</p> Signup and view all the answers

In PHP, what allows a function to modify its arguments?

<p>Call-time pass-by-reference (A)</p> Signup and view all the answers

Flashcards

What is PHP?

PHP is a recursive acronym for "PHP: Hypertext Preprocessor". It is a server-side scripting language that can be embedded in HTML or used as a stand-alone language.

What is PHP used for?

PHP is used to manage dynamic content, databases, session tracking, and even build entire e-commerce sites.

PHP and Apache

PHP is an official module of the Apache HTTP Server.

PHP platform compatibility

PHP is fully cross-platform, meaning it runs natively on several flavors of Unix, as well as on Windows and Mac OS X.

Signup and view all the flashcards

Structure of a PHP file

A PHP file normally contains HTML tags and PHP scripting code.

Signup and view all the flashcards

PHP scripting block delimiters

A PHP scripting block starts with ''.

Signup and view all the flashcards

PHP statement terminator

Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish one set of instructions from another.

Signup and view all the flashcards

PHP case sensitivity

PHP is case sensitive, therefore watch the capitalization closely when you create or call variables, objects, and functions.

Signup and view all the flashcards

php.ini

The php.ini file is read each time PHP is initialized. It is the most immediate way to affect PHP's functionality.

Signup and view all the flashcards

PHP Variables

Variables in PHP are represented by a dollar sign followed by the name of the variable.

Signup and view all the flashcards

Variable scope

The scope of a variable is the context within which it is defined. In PHP, global variables must be declared global inside a function to be used within that function.

Signup and view all the flashcards

Static Variable

A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.

Signup and view all the flashcards

GET Method

The GET method passes arguments from a page to the next page as part of the URL. Each item is accessed via the $_GET array.

Signup and view all the flashcards

POST Method

The POST method includes the form data set in the body of the form when it is forwarded to the processing agent (web server). Each item is accessed via the $_POST array.

Signup and view all the flashcards

PHP Operators

PHP supports various operators, including arithmetic, comparison, logical, assignment, and conditional operators.

Signup and view all the flashcards

If-else statement

The 'if...else' statement is used to execute a set of code when a condition is true and another if the condition is not true.

Signup and view all the flashcards

ElseIf statement

The 'elseif' statement is used with the 'if...else' statement to execute a set of code if one of several conditions is true.

Signup and view all the flashcards

Switch Statement

The 'switch' statement is used if you want to select one of many blocks of code to be executed.

Signup and view all the flashcards

For loop

The 'for' loop repeats through a block of code a specified number of times.

Signup and view all the flashcards

While loop

The 'while' loop repeats through a block of code if and as long as a specified condition is true.

Signup and view all the flashcards

Do...While loop

The do...while loop executes a block of code once, and then repeats the loop as long as a condition is true.

Signup and view all the flashcards

Foreach loop

The 'foreach' loop loops through a block of code for each element in an array.

Signup and view all the flashcards

Numeric Array

Arrays with a numeric index. Values are stored and accessed in linear fashion.

Signup and view all the flashcards

Associative Array

Arrays with strings as index. Stores element values in association with key values rather than in a strict linear index order.

Signup and view all the flashcards

Multidimensional Array

An array containing one or more arrays, with values accessed via multiple indices.

Signup and view all the flashcards

What is a function?

A function is a way of wrapping up a chunk of code and giving that chunk a name, so that you can use that chunk later in just one line of code.

Signup and view all the flashcards

Function Arguments

Information may be passed to functions via the argument list, which is a comma-delimited list of expressions.

Signup and view all the flashcards

gettype()

This function is used to get data type of variable.

Signup and view all the flashcards

settype()

This function is used to change datatype of varibale

Signup and view all the flashcards

isset()

This function is used for check wether variable value is set or not? if any value set to variable then this function retrun true otherwise retrun false.

Signup and view all the flashcards

unset()

This functioin is used for destroy variable.

Signup and view all the flashcards

strtolower()

This function is used to convert string in lowercase.

Signup and view all the flashcards

strtoupper()

This function is used to convert string in uppercase.

Signup and view all the flashcards

strlen()

This function is used to count string total character.

Signup and view all the flashcards

ltrim()

This function is used to remove space or character from left side of string.

Signup and view all the flashcards

rtrim()

this function is used to remove space or character from right side of string

Signup and view all the flashcards

substr()

this function is used to get substring form string

Signup and view all the flashcards

ftell()

is used to find current pointer position in file.

Signup and view all the flashcards

fseek()

is used to move pointer in specific position

Signup and view all the flashcards

Study Notes

Introduction to PHP

  • PHP stands for "PHP: Hypertext Preprocessor," a recursive acronym
  • Originally named “Personal Home Page”
  • PHP was developed by Rasmus Lerdorf, a software engineer and member of the Apache team
  • The first part of PHP was developed in late 1994 for personal use

Usage and Integration

  • By mid-1997, PHP was being used on approximately 50,000 sites worldwide
  • PHP is a server-side scripting language
  • PHP can be embedded in HTML or used as a stand-alone language
  • Used to manage dynamic content, databases, session tracking, and even build entire E-commerce sites
  • It integrates with popular databases like MySQL, PostgreSQL, Oracle, Sybase Informix, and Microsoft SQL Server
  • PHP does not manage a page's looks or sounds
  • Most of what PHP does is invisible to the end user
  • It's an official module of the Apache HTTP Server
  • PHP is fully cross-platform
  • It can be natively run on several flavors of Unix, as well as on Windows and Mac OS X

Advantages of PHP

  • Open Source: large community for support
  • It is developed and maintained by a large group of PHP developers
  • It creates a support community and an abundant extension library
  • Easy to Use: especially for those familiar with C
  • It uses C link Syntax
  • It is easy to pick up and create website scripts
  • Speed: It uses much system resource so is relatively fast
  • Stable: Bugs are quickly fixed because it is maintained by many developers
  • Powerful Library Support: functional modules available such as PDF and Graph
  • Built-in Database Connection Modules: connects easily to databases
  • Reduces web app development time
  • Can be run on many platforms including Windows, Linux, and Mac
  • Easy for users to find hosting service providers

Basic PHP Syntax

  • A PHP file typically contains HTML tags and PHP scripting code
  • PHP scripting blocks start with .
  • Scripting blocks can be placed anywhere in the document
  • Each code line in PHP must end with a semicolon
  • Semicolons separate instructions
  • echo and print are the two basic statements to output text with PHP

Escaping from HTML

  • PHP parses a file, looking for opening and closing tags to start and stop code interpretation
  • This allows PHP to be embedded in different documents
  • Everything outside of the tags are ignored
  • PHP is embedded in HTML documents

Opening and Closing Tags

  • Four pairs of opening and closing tags can be used in PHP:
    • ``
    • ``
    • `` (Short Tag): Requires "short_open_tag = On"
    • <% %> (ASP Style Tag): Requires "asp_tags = on"
  • ```` and `` are always available
  • Short tags and ASP style tags can be turned on and off in the php.ini configuration file

PHP.ini File

  • The PHP configuration file, php.ini, affects PHP's functionality
  • PHP initializes the php.ini file each time
  • PHP initializes it when httpd is restarted for the module version, or with each script execution for the CGI version
  • Restart httpd if changes are not showing up
  • Use phpinfo() to check the path to php.ini
  • Keys are case sensitive
  • Keyword values are not
  • Whitespace and lines beginning with semicolons are ignored
  • Booleans are represented by 1/0, Yes/No, On/Off, or True/False

Important settings in php.ini

  • short_open_tag = Off: Required to use XML functions Short open tags look like this: ``
  • disable_functions = [function1, function2...]: ability to disable selected functions for security reasons
  • max_execution_time = 30: sets the time limit for script execution
  • set_time_limit() won’t work in safe mode
  • Abort based on maximum memory consumed in Windows
  • Apache timeout setting will also apply to non-PHP files on the site error_reporting = E_ALL & ~E_NOTICE
  • The default value is E_ALL & ~E_NOTICE, all errors except notices
  • Development servers should be set to at least the default, only production servers should even consider a lesser value
  • auto-prepend-file = [path/to/file]: PHP must automatically include() it at the beginning of every PHP file, include path restrictions apply
  • auto-append-file = [path/to/file]: PHP must automatically include() it at the end of every PHP file, include path restrictions apply
  • file_uploads = [on/off]: Turn on this flag to upload files using PHP script
  • mysql.default_host = hostname: default server host connecting host if host not specified
  • mysql.default_user = username: default username for connecting to database
  • mysql.default_password = password: default password for connecting to database

.htaccess in PHP

  • .htaccess is a configuration file for web servers running on the Apache web server software
  • When placed in a directory, it's loaded by the Apache web server
  • .htaccess files modify the setup of Apache to empower additional features, various configurations
  • .htaccess empower Apache server functionality

PHP Variables

  • PHP variables start with a dollar sign ($)
  • Variable names are case-sensitive
  • Variable names must start with a letter or underscore, followed by letters, numbers, or underscores

Variable Scope

  • Variable scope is the context in which it is defined
  • PHP variables mostly have a single scope
  • User-defined functions introduce a local function scope
  • Variables used inside functions are limited to the local function scope by default unless globalized

The "global" Keyword

  • PHP global variables used in functions must be declared global inside the function using the "global" keyword or the $GLOBALS array
  • Declaring variables as global within the function makes all references to them refer to the global version

Using Static Variables

  • Static variables exist only in the local function scope
  • Static variables do not lose their value when program execution leaves the scope
  • It sets $a to 0 and prints "0", which is useless as the $a++ serves no purpose and the $a variable disappears as soon as the function exits
  • Declaring $a as static makes Test() retain current count

Variables from outside PHP (HTML Forms GET and POST)

  • Information from a submitted form becomes automatically available to the PHP script
  • GET and POST methods for form objects

GET Method

  • The GET method passes arguments as part of the URL (Uniform Resource Locator) Query String
  • When you use form handling, GET then appends the indicated variable name and value to the designated URL in the ACTION attribute
  • it uses a question mark separator
  • Each item that you submit goes through the GET method in the $_GET array

Advantage of GET Method

  • Advantage: It constructs a differentiated URL query string so the user can bookmark the page

Disadvantages of GET Method

  • GET is not suitable for login forms because username & password are fully visible on screen
  • Every GET submission is recorded in the web server log, data set included
  • There is a limit to the URL's length, so there is a limit to the data passed using GET method

POST Method

  • Generally POST method is the better option for form submissions
  • The form dataset is included in the body of form when forwarded to the processing agent which is the web server
  • There is no visible change to the URL that results to the data that has been submitted
  • Each item you submit via the POST method goes to the handler via the $_POST array

Advantages of POST Method

  • POST method is a way more secure option because the user's entered information is never visible in the URL
  • There is a larger limit on the amount of data that you can pass which is a couple of kilobytes

Disadvantage of POST Method

  • The results at a given cannot be bookmarked
  • If the result expires from the browser's memory then the user can't revisit the page
  • There may be an error when employing Back button to revisit page
  • This method may be incompatible with certain firewall setups

PHP Operators

  • Operators are used in expressions where operands are being evaluated
  • Operators perform a calculation on each operand
  • Ex. 4 + 5 is equal to 9.
  • The "4" and "5" here are the operands, and add is what the "+" is

Arithmetic Operators

  • Arithmetic operators add, subtract, multiply, divide, modulus
  • + Adds two operands
  • - Subtracts second operand from the first
  • * Multiply both operands
  • / Divide numerator by de-numerator
  • % Modulus Operator and remainder after an integer division
  • ++ Increment operator increasing integer by one
  • -- Decrement operator decreasing integer by one

Comparison Operators

  • Comparison operators are comparing values, true or not true
  • Equal, Not Equal, Greater Than, Less Than
  • If conditions match, expression is true

Logical Operators

  • Logical operators determine logic and order
  • AND, OR, NOT
  • Based on the other condition, the outcome switches, like NOT's false/true switching

Assignment Operators

  • Assign values from left to right
  • If A is being added to B then assigned to C, then C becomes B

Conditional Operators

  • First evaluates expression for "true/false", then statements depending on result of expression are executed

Operator Categories

  • All the operators can be categorised into Unary prefix operator, Binary operators, Ternary Operators and Assignment Operators.
  • Unary prefix operators, which precede a single operand
  • Binary operators, which take two operands and perform a variety of arithmetic and logical operations
  • Conditional operator (a ternary operator), which takes three operands and evaluates either the second or third expression, depending on the evaluation of the first expression
  • Assignment operators, which assign a value to a variable

Precedence of PHP Operators

  • Operator precedence determines order of operations in an expression
  • Multiplication has higher precedence than addition
  • Ex: 7 + 3 * 2 is 13, not 20, because Operator "*" is performed first

Control Structures/Decision Making

  • If, elseif...else, and switch statements are used to make decisions based on different conditions
  • Statement that is to be executed with the different conditions

If...Else Statement

  • In case some code is to be executed when conditions are met or not met
if (condition) {
  code to be executed if condition is true;
} else {
  code to be executed if condition is false;
}
  • Output "Have a nice weekend!" if current date is Friday

ElseIf Statement

  • In case some code is to be executed if one of several conditions are true
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;
}
  • Output "Have a nice weekend!" if the current day is Friday, otherwise, it will output "Have a nice day!".

Switch Statement

  • Switch Statement is for when you want to choose one of many code blocks
  • Avoids Long if...elseif...else block statements
switch (expression){
    case label1:
     code to be executed if expression = label1;
     break;
     case label2:
     code to be executed if expression = label2;
     break;
     default:
     code to be executed
    if expression is different
    from both label1 and label2;
}

Control Statements

  • Loops in PHP are used to execute the same block of code a specified number of times
  • Four Loop Types:
    • for loops
    • while loops
    • do...while loops
    • foreach loops

For Loop

  • Loops a certain number of times
for (initialization; condition; increment){
    code to be executed;
}
  • the initializer sets the initial loop cycle count, normally called $i

While Loop

  • While the condition is true, the code in block will be executed repeated
while (condition) {
    code to be executed;
}
  • The test code is tested first

Do..While Loops

  • The statement will execute at least once first before any re-execution later
do {
  code to be executed;
}
while (condition);
  • The testing part is at the end

ForEach Loops

  • ForEach is used to loop through arrays
foreach (array as value) {
    code to be executed;
}
  • ForEach goes through a value sequence

Using the Break Statement

  • Terminate the execution of a loop early using break keywords
  • Provides complete control over loop behavior
  • For conditional loops, it will always be an option to come out

Using the Continue Statement

  • Halt current iteration of loop, but not terminate it unlike break
  • Just like the break statement, continue is situated inside the statement block
  • But it's preceed by conditional

Arrays

  • Collection of multiple things into one
  • It is easy to define a bunch of variables as elements of a single array
      Numeric array – An array with a numeric index. Values are stored and accessed in linear fashion.
      Associative array – An array with strings as index. This stores element values in association
         with key values rather than in a strict linear index order.
      Multidimensional array – An array containing one or more arrays and values are accessed
         using multiple indices

User Defined Functions

  • User-defined functions are not requirement in PHP
  • If there are many code files, it may be indication that functions should be used

What is a Function

  • Way of wrapping section of code & name
  • Like methods from other languages
function function-name ($argument-1 ,$argument-2..)
 {
        statement - 1;
        statement - 2; ...
 }
  • Function definition has four parts:
    • The special word function
    • The name that you want to give your function
    • The function’s parameter list-dollar-sign variable separate by commas
    • The function body – a brace-enclosed set of statements
  • Function naming rule: rules on parameters
  • Function parameter information can be passed via arguments
  • PHP supports passing arguments:
  • by value (default)
  • by reference
  • default argument values
  • variable-length argument lists

Making Passing be by Referencing

  • By default, arguments are passed by value
  • Using ampersand (&) gives code access

Default Arguments

  • Ability to have default values
  • Must define right
  • Must define any arguments with default value to the right of any arguments without default value

PHP Variable Length Argument Function

  • PHP supports variable length argument function. It means you can pass 0, 1 or n number of arguments in function
  • Use ellipses (...): three dots
  • PHP 5.6 implements three dot concept
  • Number of arguments must be specific: numargs = func_num_args();

Built-In Functions

  • Variable Functions

    • gettype() returns data type of a variable
    • settype(variable,datatype) changes variable
    • isset() checks if value is or is not set in variable
    • unset() Destroys variable
    • strval() Converts var to string
    • floatval() Converts var to float
    • intval() Converts var to int
    • print_r() print structure of array
  • String function

    • chr() converts ASCII value to character
    • ord() converts character to ASCII value
    • strtolower() lowercase a string
    • strtoupper() uppercase a string
    • strlen() counts character
    • ltrim() remove spaces or char at left side of string
    • rtrim() remove spaces or char at right side of string
    • trim() remove spaces at both side
  • Math functions

    • abs() returns abs value of number
    • ceil() returns upper value of float
    • floor() returns lower vat of float
    • round() returns rounded value
    • fmod()
    • min() returns lowest valued parameters
    • max() returns highest valued parameters
    • pow() x to power of y
    • sqrt() Returns square root
      
    • rand() returns andom number
    • sin() sin
    • cos() cos
    • tan() tan
    • asin() arcsin
    • acos() arccos
    • atan() arctan
    • is_infinite checks if value is infinity
    • is_finite checks if value is finite or not
    • deg2rad() convert number of degrees to corresponding number of radians
    • decbin() converts decimal to bin
    • bindec()
    • hexdec()
    • dechex()
    • base_convert()
  • Array

    • count() elements available
    • list() creates numbered variables
    • in_array value in arr or not
    • current() the pointed node
    • next() moves the pointer to next
    • prev() moves to previous
    • end() moves to end of the array
    • each() current + moves
    • stristr()
    • sort() sorted
  • File Handling

    • File Open Modes fopen() - Open and Read File - Open and Write File - Check - Close - FileExists - is_readable - is_writable
  • String function - File

         -   Get contents
         -   put contents
    
  • String Manipulation -String compare - string replace 12 Miscellaneous function : - Header File - Include - die()/ exit - constants

  • Date and time functions

Single vs Double quotes

  • single quotes does not interpret escape sequences but double quotes
  • variables in code do not expand in Single Quotes, only complex variables in double
  • simple way to enclose string in single quotes

PHP Call by Value/Reference

  • Call function reference and value
PHP call by value,
actual value is unmodified inside.
PHP call by reference,
actual value modified inside.

Studying That Suits You

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

Quiz Team

Related Documents

More Like This

Introductory PHP Scripting Quiz
5 questions

Introductory PHP Scripting Quiz

ReachableEnlightenment avatar
ReachableEnlightenment
Server-side Scripting cu PHP
8 questions
PHP Scripting Basics
149 questions

PHP Scripting Basics

ConciseAndradite avatar
ConciseAndradite
Use Quizgecko on...
Browser
Browser