This document provides an introduction to PHP, including an overview of server-side scripting, how PHP code is processed, basic PHP syntax, variables, operators, control structures like conditional statements and loops, and other key PHP concepts. It explains what PHP is, how it is used to create dynamic web content, and some of the basic building blocks needed to get started with PHP programming.
The PHP is a powerful web scripting language that is free and efficient language for building dynamic web pages. This presentation is an introduction to the basics of PHP programming with a little sample program.
Introduction to PHP: Declaring variables, data types, arrays, strings, operators, expressions, control structures, functions, Handling sessions and cookies
File Handling in PHP: File operations like opening, closing, reading, writing appending, deleting etc.
PHP is a server-side scripting language designed for web development but also used as a general-purpose programming language. As of January 2013, PHP was installed on more than 240 million websites (39% of those sampled) and 2.1 million web servers.[4] Originally created by Rasmus Lerdorf in 1994,[5] the reference implementation of PHP (powered by the Zend Engine) is now produced by The PHP Group.[6] While PHP originally stood for Personal Home Page,[5] it now stands for PHP: Hypertext Preprocessor, which is a recursive backronym
PHP stands for “PHP: Hypertext Preprocessor”. It is very good for creating dynamic content. PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.
The PHP is a powerful web scripting language that is free and efficient language for building dynamic web pages. This presentation is an introduction to the basics of PHP programming with a little sample program.
Introduction to PHP: Declaring variables, data types, arrays, strings, operators, expressions, control structures, functions, Handling sessions and cookies
File Handling in PHP: File operations like opening, closing, reading, writing appending, deleting etc.
PHP is a server-side scripting language designed for web development but also used as a general-purpose programming language. As of January 2013, PHP was installed on more than 240 million websites (39% of those sampled) and 2.1 million web servers.[4] Originally created by Rasmus Lerdorf in 1994,[5] the reference implementation of PHP (powered by the Zend Engine) is now produced by The PHP Group.[6] While PHP originally stood for Personal Home Page,[5] it now stands for PHP: Hypertext Preprocessor, which is a recursive backronym
PHP stands for “PHP: Hypertext Preprocessor”. It is very good for creating dynamic content. PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...anshkhurana01
php-mysql classes in navi-mumbai,php-mysql course-provider-in-navi-mumbai,best php-mysql class in navi-mumbai
B2/6/2 Vashi ,Navi Mumbai, Contact:09892900103/9892900173 enquiry@vibrantgroup.co.in
Custom, in depth 5 day PHP course I put together in 2014. I'm available to deliver this training in person at your offices - contact me at rich@quicloud.com for rate quotes.
PHP: Why PHP and MySQL? Server-side scripting, PHP syntax and variables, comments, types, control structures, branching, looping, termination, functions, passing information with PHP, GET, POST, formatting form variables, superglobal arrays, strings and string functions, regular expressions, arrays, number handling, basic PHP errors/problems
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
3. Server-Side Scripting
A "skrip" adalah koleksi program atau urutan
arahan yang ditafsirkan atau dijalankan oleh
program lain dan bukannya oleh pemproses
komputer.
Server-side / Server-side
Client-side / Pelanggan-side
Dalam server-side scripting, (seperti PHP, ASP)
skrip diproses oleh pelayan Like: Apache,
ColdFusion, ISAPI dan Microsoft IIS pada
Windows.
4. Server-Side Scripting – Continued
Advantages of Server-Side Scripting
Dynamic content.
Computational capability.
Database and file system access.
Network access (from the server only).
Built-in libraries and functions.
Known platform for execution (as opposed to
client-side, where the platform is uncontrolled.)
Security improvements
5. Introduction to PHP
• PHP stands for PHP: Hypertext Preprocessor
• Developed by Rasmus Lerdorf in 1994
• It is a powerful server-side scripting language
for creating dynamic and interactive websites.
• It is an open source software, which is widely
used and free to download and use (PHP is
FREE to download from the official PHP
resource: www.php.net).
• It is an efficient alternative to competitors such
as Microsoft's ASP.
6. Introduction to PHP
• PHP is perfectly suited for Web development
and can be embedded directly into the HTML
code.
• The PHP syntax is very similar to JavaScript,
Perl and C.
• PHP is often used together with Apache (web
server) on various operating systems. It also
supports ISAPI and can be used with
Microsoft's IIS on Windows.
• PHP supports many databases (MySQL,
Informix, Oracle, Sybase, Solid, PostgreSQL,
7. Introduction to PHP
• What is a PHPFile?
• PHP files have a file extension of ".php",
".php3", or ".phtml"
• PHP files can contain text, HTML tags and
scripts
• PHP files are returned to the browser as plain
HTML
8. Introduction to PHP
What you need to develop PHPApplication:
• Install Apache (or IIS) on your own server,
install PHP, and MySQL
• OR
• Install Wampserver2 (a bundle of PHP, Apache,
and MySql server) on your own server/machine
9. PHP Installation Downloads
Free Download
PHP: http://www.php.net/downloads.php
MySQL Database: http://www.mysql.com/downloads/index.html
Apache Server: http://httpd.apache.org/download.cgi
• How to install and configure apache
• Here is a link to a good tutorial from PHP.net on how to install PHP5:
http://www.php.net/manual/en/install.php
10. How PHP is Processed
• When a PHP document is requested of a
server, the server will send the document first
to a PHP processor
• Two modes of operation
– Copy mode in which plain HTML is copied to the
output
– Interpret mode in which PHP code is interpreted
and the output from that code sent to output
– The client never sees PHP code, only the output
produced by the code
11. Basic PHPSyntax
• PHP statements are terminated with semicolons ;
• Curly braces, { } are used to create compound
statements
• Variables cannot be defined in a compound statement
unless it is the body of a function
• PHP has typical scripting language characteristics
– Dynamic typing, un-typed variables
– Associative arrays
– Pattern matching
– Extensive libraries
• Primitives, Operations, Expressions
– Four scalar types: boolean, integer, double, string
– Two compound types: array, object
– Two special types: resource and NULL
12. Basic PHPSyntax
• A PHP scripting block always starts with <?php and
ends with ?>
<?php ……………. ?>
– Other options are:
1. <? ……………… ?>
2. <script> ... </script>
• There are three basic statements to output text with
PHP: echo, print, and printf. Example:
echo 'This is a <b>test</b>!';
• Comments:
– #
– //
– /* . . . * /
13. Basic PHPSyntax
Inserting external files:
PHP menyediakan empat fungsi yang
membolehkan anda untuk memasukkan
kod dari fail luaran : include() or require()
include_once() or require_once()
functions.
• E.g.
include("table2.php");
– Includedfiles start incopymode
14. Basic PHPSyntax
Example 1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head> <title>Simple PHP Example</title>
<body>
<?php
echo "Hello Class of 2011. This is my first PHP Script";
echo "<br />";
print "<b><i>What have you learnt and how many friends have you
made?</i></b>";
echo "<br /><a href='PHP I-BSIC.ppt'>PHP BASIC</a>";
?>
</body>
</html>
15. PHPVariables
• Variables are used for storing
values, such as numbers,
strings or function results, so
that they can be used many
times in a script.
• All variables in PHP start with a
$ sign symbol.
• Variables are assigned using
the assignment operator "="
• Variable names are case
sensitive in PHP: $name is not
the same as $NAME or $Name.
• In PHP a variable does not
need to be declared before
being set.
Example:
<html>
<head>
<title>My first PHP page</title>
</head>
<body>
<?php
$var1 = 'PHP'; // Assigns a value of 'PHP' to
$var1
$var2 = 5; // Assigns a value of 5 to $var2
$var3 = $var2 + 1; // Assigns a value of 6 to
$var3
$var2 = $var1; // Assigns a value of 'PHP' to $var2
echo $var1; // Outputs 'PHP‘
echo "<br/>";
echo $var2; // Outputs 'PHP'
echo "<br/>";
echo $var3; // Outputs '6'
echo "<br/>";
echo $var1 . ' rules!'; // Outputs 'PHP rules!'
echo "$var1 rules!"; // Outputs 'PHP rules!'
echo '$var1 rules!'; // Outputs '$var1 rules!‘
?>
16. Variable Naming Rules
A variable name must start with a letter or an
underscore "_"
A variable name can only contain alpha-numeric
characters and underscores (a-z, A-Z, 0-9, and _
)
If variable name is more than one word, it should
be separated with an underscore e.g.
($my_string), or with capitalization ($myString)
17. Variable Scope and Lifetime
The scope of a variable
defined within a function
is local to that function.
A variable defined in the
main body of code has a
global scope.
If a function needs to use
a variable that is defined
in the main body of the
program, it must reference
it using the "global"
• Example:
<?php
function mul()
{
global $start;
print "<tr>";
for ($num=1; $num <= 10; $num++ )
{
$cell = $num * $start;
print "<td> " . $cell . " </td>";
}
print "</tr>";
}
$start = 0;
print "<table border=1
cellpadding=3>";
while ( $start <=10 )
{
mul();
$start++;
}
print "</table>";
?>
18. Strings in PHP
• a string is a sequence of letters, symbols, characters and arithmetic values or
combination of all tied together in single or double quotes.
• String literals are enclosed in single or double quotes
• Example:
<?php
$sum = 20;
echo 'the sum is: $sum';
echo "<br />";
echo "the sum is: $sum";
echo "<br />";
echo '<input type="text" name="first_name" id="first_name">';
?>
– Double quoted strings have escape sequences (such as /n or /r) interpreted
and variables interpolated (substituted)
– Single quoted strings have neither escape sequence interpretation nor variable
interpolation
– A literal $ sign in a double quoted string must be escaped with a backslash,
– Double-quoted strings can cover multiple lines
19. Escaping quotes with in quotes
Example 1:
<?php
$str = ""This is a PHP string examples quotes"";
echo $str;
?>
Example 2
<?php
$str = 'It's a nice day today.';
echo $str;
?>
20. The Assignment Operator
The Assignment operator is the most widely used and well known of all the
operators in PHP. You use it every time you create a variable. The
"="(equal to) sign is used, and what it does is it takes the expression from
the right and places it into the operand on the left. It is simple.
In this example we use the assignment operator(=) to place a value of 8
into the variable:
<?php
$var1 = 8;
?>
We can also combine operators together to produce expression results that
are set into our variables as value. We demonstrate this in the next few
lessons quite well. Let us continue on.
22. String Operators
Use a dot to concatenate two strings:
e.g.
$firstname = ‘Rob’;
$surname = ‘Tuley’;
// displays ‘Rob Tuley’
echo $firstname.’ ‘.$surname;
23. Arithmetic Operators
Example Name Result
$a + $b Addition Sum of $a and $b.
$a - $b Subtraction Difference of $a and $b.
$a * $b Multiplication Product of $a and $b.
$a / $b Division Quotient of $a and $b.
$a % $b Modulus Remainder of $a divided by $b.
25. Combining Operators
Note that you can combine operators, for
example use =, + and / in one expression:
$a = 4;
$b = 2;
$c = $a + $b + ($a/$b);
// $c has value 4+2+(4/2) = 8
Brackets help group operators.
26. Comparison Operators
Example Name Result
$a == $b Equal TRUE if $a is equal to $b.
$a != $b Not equal TRUE if $a is not equal to $b.
$a <> $b Not equal TRUE if $a is not equal to $b.
$a < $b Less than TRUE if $a is strictly less than $b.
$a > $b Greater than TRUE if $a is strictly greater than $b.
$a <= $b Less than or equal to TRUE if $a is less than or equal to $b.
$a >= $b Gtr than or equal to TRUE if $a is greater than or equal to $b.
27. Comparisons
Comparison expressions return a value of
TRUE (or ‘1’) or FALSE (or ‘0’).
e.g.
$a = 10;
$b = 13;
// result is true (‘1’)
echo $a < $b;
28. Incrementing/Decrementing
Example Name Effect
++$a Pre-increment Increments $a by one, then returns $a.
$a++ Post-increment Returns $a, then increments $a by one.
--$a Pre-decrement Decrements $a by one, then returns $a.
$a-- Post-decrement Returns $a, then decrements $a by one.
29. Logical Operators
Example Name Result
$a and $b And TRUE if both $a and $b are TRUE.
$a or $b Or TRUE if either $a or $b is TRUE.
$a xor $b Xor TRUE if either $a or $b is TRUE, but not both.
!$a Not TRUE if $a is not TRUE.
$a && $b And TRUE if both $a and $b are TRUE.
$a || $b Or TRUE if either $a or $b is TRUE.
30. Finally, a tricky one!
A single ? is the ternary operator.
(expr) ? if_expr_true : if_expr_false;
A test expression evaluates to TRUE or
FALSE.
TRUE gives first result (before colon)
FALSE gives second result (after colon)
31. Ternary Operator example
<?php
$a = 10;
$b = 13;
echo $a<$b ? ‘a smaller’:‘b smaller’;
// string ‘a smaller’ is echoed
// to the browser..
?>
32. The Concatenation Operator
• The concatenation operator (.) is used to put
two string values together.
• Example:
<?php
$txt1="Hello Everyone,";
$txt2="1234 is Dan’s home address";
echo $txt1.$txt2;
?>
33. Constants in PHP
Constants are named values whose values cannot be changed. When you create a
constant you should use all capital letters and underscores separating words to let
yourself and others know they are constants. A dollar sign is not needed in front of
the name when creating constants. We use the define() function in PHP to create
them.
Here is how we create a constant, and use true on the end to make it not worry about
letter casing:
Output:
The person that created this web page is named Adam Khoury.
<?php
// define(constant_name, value, case_sensitive=true);
define("AUTHOR_NAME", "Adam Khoury", true);
echo "The person that created this web page is named " . AUTHOR_NAME . ".";
?>
34. Control Structure
Control structures are the building blocks of
any programming language. PHP provides all
the control structures that you may have
encountered anywhere. The syntax is the
same as C or Perl.
Making computers think has always been the
goal of the computer architect and the
programmer. Using control structures
computers can make simple decisions and
when programmed cleverly they can do some
complex things.
35. Conditional Statements
1. The If...Else
Statement
Syntax
if (co nditio n) co de to be
e xe cute d if co nditio n is
true ;
else co de to be e xe cute d if
co nditio n is false ;
<?php
$d=date("D");
if ($d=="Fri") echo "Have a
nice weekend!";
If more than one line should
be executed if a
condition is true/false,
the lines should be
enclosed within curly
braces:
<?php
$d=date("D");
if ($d=="Fri")
{ echo "Hello!<br />";
echo "Have a nice
weekend!";
echo "See you on
36. Conditional Statements
2.The ElseIf Statement
• If you want to execute some
code if one of several
conditions is true use the
elseif statement
Syntax
if (co nditio n) co de to be
e xe cute d if co nditio n is
true ;
elseif (co nditio n) co de to
be e xe cute d if co nditio n
is true ;
<html><head> <title>good ......</title>
</head>
<body>
<?php
$hour= date("H");
if ($hour<= 11) {
echo "good morning my friend"; }
elseif ($hour> 11 && $hour< 18) {
echo "good afternoon my friend"; }
else { echo "good evening my
friend"; }
?>
</body></html>
37. PHPSwitch Statement
• If you want to select one of many
blocks of code to be executed, use
the Switch statement.
• The switch statement is used to
avoid long blocks of if..elseif..else
code.
Syntax
switch (e xpre ssio n)
{
case labe l1 : co de to be e xe cute d if
e xpre ssio n = labe l1 ;
break;
case labe l2: co de to be e xe cute d if
e xpre ssio n = labe l2;
break;
default: co de to be e xe cute d if
e xpre ssio n is diffe re nt fro m bo th
switch ($textcolor)
{
case "black":
echo "I'm black";
break;
case "blue":
echo "I'm blue";
break;
case "red":
echo "I'm red";
break;
default: // It must be
something else
echo "too bad!!, I'm
something else";
}
38. PHPLooping
• Looping statements in PHP are used to
execute the same block of code a specified
number of times.
• In PHP we have the following looping
statements:
– while - loops through a block of code if and as
long as a specified condition is true
– do...while - loops through a block of code once,
and then repeats the loop as long as a special
condition is true
– for- loops through a block of code a specified
number of times
– foreach - loops through a block of code for each
39. The while Statement
Syntax
while (condition)
{
// statements
}
Example
<html> <head> <title>Let us count !!!
</title></head>
<body>
<?php
$limit = 10;
echo "<h2> Let us count from 1 to $limit
</h2><br />";
$count = 1;
while ($count <= $limit)
{
echo "counting $count of $limit <br>";
$count++;
}
?>
40. The do...while Statement
• The do...while
statement will
execute a block of
code at least once -
it then will repeat the
loop as long as a
condition is true.
Syntax
• do { co de to be
e xe cute d; } while
(co nditio n);
Example
<html> <body>
<?php
$i=0;
do { $i++; echo "The number
is " . $i . "<br />"; }
while ($i<5);
?>
</body> </html>
41. The forStatement
• It is used when you know how many
times you want to execute a statement
or a list of statements.
Syntax
• for (init; co nd; incr) { co de to be
e xe cute d; } Parameters:
• init: Is mostly used to set a counter,
but can be any code to be executed
once at the beginning of the loop
statement.
• cond: Is evaluated at beginning of
each loop iteration. If the condition
evaluates to TRUE, the loop continues
and the code executes. If it evaluates
to FALSE, the execution of the loop
ends.
• incr: Is mostly used to increment a
Example
<html> <body>
<?php
for ($i=1; $i<=5; $i++)
{
echo "Hello World!
<br />";
}
?>
</body> </html>
42. The foreach Statement
• The foreach statement is
used to loop through arrays.
• For every loop, the value of
the current array element is
assigned to $value (and the
array pointer is moved by
one) - so on the next loop,
you'll be looking at the next
element.
Syntax
• foreach (array as value )
{ co de to be e xe cute d; }
Example
<html> <body>
<?php
$arr=array("one", "two",
"three");
foreach ($arr as $value) {
echo "Value: " . $value .
"<br />";
}
?>
</body> </html>
43. Object and Classes in PHP
PHP, like most modern programming languages (C++, Java, Perl, JavaScript, etc.),
supports the creation of objects.
Creating an object requires you to first define an object class (containing variables
and/or function definitions) and then using the “new” keyword to create an instance of
the object class. (Note that the object must be defined before you instantiate it.)
<?php
// Assume that the "Person" object has been previously defined. . .
$x = new Person; // creates an instance of the Person class (*no* quotes)
// The object type need not be "hardcoded" into the declaration.
$object_type = 'Person';
$y = new $object_type; // equivalent to $y = new Person;
$z = new Vehicle('Jaguar','green'); // creating an object and passing
// arguments to its constructor
44. Defining (declaring) a class
Use the “class” keyword which includes the class name (case-insensitive, but
otherwise following the rules for PHP identifiers). Note: The name “stdClass” is
reserved for use by the PHP interpreter.
<?php
class Person
{
var $name;
function set_name($new_name) {
$name = $this -> new_name;
}
function get_name() {
return $this -> name;
}
}
Use the “$this” variable when accessing properties and functions of the current
object. Inside a method this variable contains a reference to the object on which
the method was called.
45. Declaring a class (cont.)
Properties and functions can be declared as “public” (accessible outside the
object’s scope), “private” (accessible only by methods within the same class), or
“protected” (accessible only through the class methods and the class methods of
classes inheriting from the class.
Note that unless a property is going to be explicitly declared as public, private, or
protected, it need not be declared before being used (like regular PHP variables).
<?php
class Person
{
protected $name;
protected $age;
function set_name($new_name) {
$name = $this -> new_name;
}
function get_name() {
return $this -> name;
}
}
46. Declaring a class (cont.)
Classes can also have their own constants defined (using the “const” keyword), can
have their own static properties and functions (using the keyword “static” before
“var” or “function”), and can also can constructors and destructors (see below).
Static properties and functions are accessed (see below) using a different format
than usual for objects, and static functions cannot access the objects properties
(i.e. the variable $this is not defined inside of a static function).
<?php
class HTMLtable {
static function start() {
echo "<table> n";
}
static function end() {
echo "</table> n";
}
}
HTMLtable::start();
?>
47. Accessing properties and
methods
Once you have an object, you access methods and properties (variables) of the
object using the -> notation.
<?php
$me = new Person;
$me -> set_name('Russ');
$me -> print_name();
$name = $me -> get_name();
echo $me -> get_name();
$age = 36;
$me -> set_age($age);
?>
48. PHP Function
In php a function is a predefined set of
commands that are carried out when the
function is called.
The real power of PHP comes from its
functions.
PHP has more than 700 built-in or predefine
functions for you to use.
Complete php string reference
You can write your own functions
50. Using Built-in Function
<html>
<head>
<title>My first PHP page</title>
</head>
<body>
<?php
$a = abs(-.43);
$b = sqrt(16);
$c = round(12.3);
print "The absolute value of -.43 is " . $a . "<br />";
print "The square root of 16 is " . $b . "<br />";
print "12.3 rounded is " . $c . " and 12.5 rounded is " . round(12.5);
?>
</body>
</html>
51. Using Built-in Function
Examples: Inserting external files:
PHP provides four functions that enable you to insert code
from external files: include() or require() include_once() or
require_once() functions.
A sample include file called add.php
<html> <body>
<?php
function add( $x, $y ) {
return $x + $y; }
?>
<h1>Welcome to my home page</h1>
<p>Some text</p>
</body> </html>
Using the include function
<?php
include('add.php');
echo add(2, 2); ?>
52. Using Built-in Function
Inserting external files - continued:
The functions are identical in every way, except how they
handle errors.
The include() and include_once() functions generates a warning (but
the script will continue execution)
The require() and require_once() functions generates a fatal error
(and the script execution will stop after the error).
These functions are used to create functions, headers,
footers, or elements that can be reused on multiple pages.
This can save the developer a considerable amount of time for
updating/editing.
53. Date Function Formatting
DAYS
d - day of the month 2 digits (01-31)
j - day of the month (1-31)
D - 3 letter day (Mon - Sun)
l - full name of day (Monday - Sunday)
N - 1=Monday, 2=Tuesday, etc (1-7)
S - suffix for date (st, nd, rd)
w - 0=Sunday, 1=Monday (0-6)
z - day of the year (1=365)
WEEK
W - week of the year (1-52)
MONTH
F - Full name of month (January - December)
m - 2 digit month number (01-12)
n - month number (1-12)
M - 3 letter month (Jan - Dec)
t - Days in the month (28-31)
YEAR
L - leap year (0 no, 1 yes)
o - ISO-8601 year number (Ex. 1979, 2006)
Y - four digit year (Ex. 1979, 2006)
y - two digit year (Ex. 79, 06)
• Date Function
Formatting
• TIME
a - am or pm
A - AM or PM
B - Swatch Internet time
(000 - 999)
g - 12 hour (1-12)
G - 24 hour c (0-23)
h - 2 digit 12 hour (01-12)
H - 2 digit 24 hour (00-
23)
i - 2 digit minutes (00-59)
s 0 2 digit seconds (00-
59)
• OTHERe - timezone (Ex:
GMT, CST)
I - daylight savings
(1=yes, 0=no)
O - offset GMT (Ex:
0200)
Z - offset in seconds (-
43200 - 43200)
54. Using Built-in Function
PHP Date() function
formatting characters:
Example 1:
<?php
$theDate =
date("m/d/y");
echo "Today's date
is: $theDate";
?>
Example 2
<?php
$b = time ();
print date("m/d/y",$b) . "<br />";
print date("D, F jS",$b) . "<br />";
print date("l, F jS Y",$b) . "<br />";
print date("g:i A",$b) . "<br />";
print date("r",$b) . "<br />";
print date("g:i:s A D, F jS Y",$b) . "<br />";
?>
55. Defining and Referencing a
Function
Syntax
function functionname () { your code }
Example:
<html> <body>
<?php
Function Name()
{
echo "Ben John";
}
Name();
?>
</body> </html>
56. PHPFunctions - Adding
parameters
A parameter is just like a
variable.
The parameters are specified
inside the parentheses.
Syntax:
<?php
function
function_name(param_1,
... , param_n)
{
statement_1;
statement_2;
...
statement_m;
return
return_value;
}
?>
Functions can also be used to return
values.
Example:
<html>
<body>
<?php
function add($x,$y)
{
$total = $x + $y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>
</body>
</html>
57. PHPArrays
An array can store one or more values in a
single variable name.
There are three different kind of arrays:
Numeric array - An array with a numeric ID key
Associative array - An array where each ID key is
associated with a value
Multidimensional array - An array containing one
or more arrays
58. Numeric Array
• A numeric array stores each element with
a numeric ID key.
• There are different ways to create a
numeric array:
Example 1
• In this example the ID key is
automatically assigned:
• $names =
array("Peter","Quagmire","Joe");
Example 2
• In this example we assign the ID key
manually:
$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";
Example 3:
<?php
$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";
echo $names[1] . " and " .
$names[2] . " are ".
$names[0] . "'s
neighbors"; ?>
59. Associative Arrays
• Each ID key is associated with a
value.
• When storing data about
specific named values, a
numerical array is not always
the best way to do it.
• There are two ways of creating
Associative Array:
Example 1
• $ages = array("Peter"=>32,
"Quagmire"=>30, "Joe"=>34);
Example 2
• $ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
Example 3:
<?php
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
echo "Peter is " .
$ages['Peter'] . " years
old.";
?>
60. Multidimensional Arrays
• In a multidimensional array,
each element in the main
array can also be an array.
And each element in the
sub-array can be an array,
and so on.
• Example 1
• with automatically assigned
ID keys:
$families = array
( "Griffin"=>array
( "Peter", "Lois", "Megan" ),
"Quagmire"=>array
( "Glenn" ),
"Brown"=>array
( "Cleveland", "Loretta", "Junior"
)
Example 2:
The array above would look like this if written to the
output:
Array
(
[Griffin] => Array
(
[0] => Peter
[1] => Lois
[2] => Megan
)
[Quagmire] => Array
(
[0] => Glenn
)
[Brown] => Array
(
[0] => Cleveland
[1] => Loretta
[2] => Junior )
)
• displaying a single value from the array
above:
echo "Is " . $families['Griffin'][2] . " a part of the
Griffin family?";
63. Forms: how they work
We need to know..
1. How forms work.
2. How to write forms in XHTML.
3. How to access the data in PHP.
64. How forms work
Web Server
User
User requests a particular URL
XHTML Page supplied with Form
User fills in form and submits.
Another URL is requested and the
Form data is sent to this page either in
URL or as a separate piece of data.
XHTML Response
65. XHTML Form
The form is enclosed in form tags..
<form action=“path/to/submit/page”
method=“get”>
<!–- form contents -->
</form>
66. Form tags
action=“…” is the page that the form should
submit its data to.
method=“…” is the method by which the form
data is submitted. The option are either get or
post. If the method is get the data is passed
in the url string, if the method is post it is
passed as a separate file.
67. Form fields: text input
Use a text input within form tags for a single
line freeform text input.
<label for=“fn">First Name</label>
<input type="text"
name="firstname"
id=“fn"
size="20"/>
68. Form tags
name=“…” is the name of the field. You will
use this name in PHP to access the data.
id=“…” is label reference string – this should
be the same as that referenced in the
<label> tag.
size=“…” is the length of the displayed text
box (number of characters).
69. Form fields: password input
Use a starred text input for passwords.
<label for=“pw">Password</label>
<input type=“password"
name=“passwd"
id=“pw"
size="20"/>
70. Form fields: text input
If you need more than 1 line to enter data, use
a textarea.
<label for="desc">Description</label>
<textarea name=“description”
id=“desc“
rows=“10” cols=“30”>
Default text goes here…
</textarea>
71. Form fields: text area
name=“…” is the name of the field. You will
use this name in PHP to access the data.
id=“…” is label reference string – this should
be the same as that referenced in the
<label> tag.
rows=“…” cols=“..” is the size of the
displayed text box.
72. Form fields: drop down
<label for="tn">Where do you live?</label>
<select name="town" id="tn">
<option value="swindon">Swindon</option>
<option value="london”
selected="selected">London</option>
<option value=“bristol">Bristol</option>
</select>
73. Form fields: drop down
name=“…” is the name of the field.
id=“…” is label reference string.
<option value=“…” is the actual data sent
back to PHP if the option is selected.
<option>…</option> is the value
displayed to the user.
selected=“selected” this option is
selected by default.
74. Form fields: radio buttons
<input type="radio"
name="age"
id="u30“
checked=“checked”
value="Under30" />
<label for="u30">Under 30</label>
<br />
<input type="radio"
name="age"
id="thirty40"
value="30to40" />
<label for="thirty40">30 to 40</label>
75. Form fields: radio buttons
name=“…” is the name of the field. All radio
boxes with the same name are grouped with
only one selectable at a time.
id=“…” is label reference string.
value=“…” is the actual data sent back to
PHP if the option is selected.
checked=“checked” this option is selected
by default.
76. Form fields: check boxes
What colours do you like?<br />
<input type="checkbox"
name="colour[]"
id="r"
checked="checked"
value="red" />
<label for="r">Red</label>
<br />
<input type="checkbox"
name="colour[]"
id="b"
value="blue" />
<label for="b">Blue</label>
77. Form fields: check boxes
name=“…” is the name of the field. Multiple
checkboxes can be selected, so if the button are
given the same name, they will overwrite
previous values. The exception is if the name is
given with square brackets – an array is
returned to PHP.
id=“…” is label reference string.
value=“…” is the actual data sent back to
PHP if the option is selected.
checked=“checked” this option is selected
by default.
79. Submit button..
A submit button for the form can be created
with the code:
<input type="submit"
name="submit"
value="Submit" />
80. Fieldset
In XHTML 1.0, all inputs must be grouped within the form into
fieldsets. These represent logical divisions through larger forms.
For short forms, all inputs are contained in a single fieldset.
<form>
<fieldset>
<input … />
<input … />
</fieldset>
<fieldset>
<input … />
<input … />
</fieldset>
</form>
81. In PHP…
The form variables are available to PHP in the
page to which they have been submitted.
The variables are available in two superglobal
arrays created by PHP called $_POST and
$_GET.
82. Access data
Access submitted data in the relevant array for
the submission type, using the input name as a
key.
<form action=“path/to/submit/page”
method=“get”>
<input type=“text” name=“email”>
</form>
$email = $_GET[‘email’];
83. A warning..
NEVER TRUST USER INPUT
Always check what has been input.
Validation can be undertaken using Regular
expressions or in-built PHP functions.
84. A useful tip..
I find that storing the validated data in a
different array to the original useful.
I often name this array ‘clean’ or something
similarly intuitive.
I then *only* work with the data in $clean, and
never refer to $_POST/$_GET again.
86. Filter example
$clean = array();
if (ctype_alnum($_POST['username']))
{
$clean['username'] = $_POST['username'];
}
$clean = array();
Initialise an array to store
filtered data.
87. Filter example
$clean = array();
if (ctype_alnum($_POST['username']))
{
$clean['username'] = $_POST['username'];
}
if (ctype_alnum($_POST['username']))
Inspect username to make
sure that it is alphanumeric.
88. Filter example
$clean = array();
if (ctype_alnum($_POST['username']))
{
$clean['username'] = $_POST['username'];
}
$clean['username'] = $_POST['username'];
If it is, store it in the array.
89. Is it submitted?
We also need to check before accessing data
to see if the data is submitted, use isset()
function.
if (isset($_POST[‘username’])) {
// perform validation
}
90. FORM Handling
GET
$_GET['name']
POST
$_POST['name']
or just use the more general method
$_REQUEST[‘name’]
91. FORM Example
<form action="test.php" method="post">
<table>
<tr>
<th>Name:</th>
<td><input type="text" name="name"></td>
</tr>
<tr>
<th>Age:</th>
<td><input type="text" name="age"></td>
</tr>
</table>
</form>
<p>Hello <?=$_POST['name']?>.
You are <?=$_POST['age']?> years old.</p>
92. Example
(a) A Web page
containing a form
(b) A PHP script for
handling the
output of the form
(c) Output from the
PHP script when
the inputs are
"Barbara" and 24
respectively
93.
94. The need for persistence
Consider these examples
− Counting the number of “hits” on a website
− i. e . how many times does a client load your web page
source
− The questionnaire on computing experience
Somehow your .php needs to remember previous
instances of it being requested by a client
95. Persistence
Persistence is the ability of data to outlive
the execution of the program that created
them.
An obvious way of achieving persistence is
to simply save the data in a file
96. Persistence and HTTP
Recall http is a stateless protocol. It remembers nothing about
previous transfers
Two ways to achieve persistence:
PHP cookies
PHP sessions
HTTP
serverClient
Cookie
Session
97. HTTP Cookies
In internet programming, a cookie is a packet of information sent from the
server to client, and then sent back to the server each time it is accessed by the
client.
Introduces state into HTTP (remember: HTTP is stateless)
Cookies are transferred between server and client according to http.
PHP supports http cookies
Cookies can also be thought of as tickets used to identify clients and their
orders
98. How Cookies are implemented
Cookies are sent from the server to the client via “Set-
Cookie” headers
Set-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secure
The NAME value is a URL-encoded name that identifies
the cookie.
The PATHand DOMAIN specify where the cookie applies
99. setcookie(name,value,expire,path,domain,secure
)
Parameter Description
name (Required). Specifies the name of the cookie
value (Required). Specifies the value of the cookie
expire (Optional). Specifies when the cookie expires.
e.g. time()+3600*24*30 will set the cookie to expire in 30 days.
If this parameter is not set, the cookie will expire at the end of the session (when
the browser closes).
path (Optional). Specifies the server path of the cookie.
If set to "/", the cookie will be available within the entire domain.
If set to "/phptest/", the cookie will only be available within the test directory and
all sub-directories of phptest.
The default value is the current directory that the cookie is being set in.
domain (Optional). Specifies the domain name of the cookie.
To make the cookie available on all subdomains of example.com then you'd set it
to ".example.com".
Setting it to www.example.com will make the cookie only available in the www
subdomain
secure (Optional). Specifies whether or not the cookie should only be transmitted over a
secure HTTPS connection.
TRUE indicates that the cookie will only be set if a secure connection exists.
Default is FALSE.
100. Cookies fromHTTPCookies fromHTTP
GET /*.html HTTP/1.1
Host: it026954.domain
GET /*.html HTTP/1.1
Host: it026945.domain
Cookie: name=value
Accept: */*
HTTP/1.1 200 OK
Content-type:
text/html
Set-Cookie:
name=value
(content of page)
Client (e.g. Firefox) it026945
101. Creating PHPcookiesCreating PHPcookies
Cookies can be set by directly manipulating the HTTP header using
the PHP header() function
<?php
header(“Set-Cookie: mycookie=myvalue; path=/; domain=.coggeshall.org”);
?>
102. Creating cookies with
setcookie()
Use the PHP setcookie() function:
Setcookie (name,value,expire, path, domain, secure)Setcookie (name,value,expire, path, domain, secure)
e.g.
<?php
setcookie("MyCookie", $value, time()+3600*24);
setcookie("AnotherCookie", $value, time()+3600);
?>
Name: name of the file
Value: data stored in the file
Expire: data string defining the life time
Path: subset of URLs in a domain where it is valid
Domain: domain for which the cookie is valid
Secure: set to '1' to transmit in HTTPS
103. Reading cookiesReading cookies
<?php
foreach ($_COOKIE as $key=>$val) {
print $key . " => " . $val . "<br/>";
}
?>
To access a cookie received from a client, use the PHP
$_COOKIE$_COOKIE superglobal array
Each key in the array represents a cookie - the key name is
the cookie name.
104. Creating and using cookiesCreating and using cookies
exampleexample
<?php
setcookie("MyCookie", $value, time()+7200);
setcookie("AnotherCookie", $value, time()+7);
?>
<?php
foreach ($_COOKIE as $key=>$val) {
print $key . " => " . $val . "<br/>";
}
?>
Cookies only become visible on the next page load
105. Using headers (wrong
approach!) <!DOCTYPE html PUBLIC "=//W3C//DTD XHMTL 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhmtl" xml:lang="en">
<head><title>PHP Script using Cookies</title>
<meta httpequiv="ContentType" content="text/html;
chatset=ISO88591" />
</head>
<body>
<?php
$strValue = "This is my first cookie";
setcookie ("mycookie", $strValue);
echo "Cookie set<br>";
?>
</body>
</html>
Gets an error!:
Warning: Cannot modify header information - headers already sent by (output started at
/var/www/html/TESTandre/159339/PHP/cookie_with_headers.php:9) in
/var/www/html/TESTandre/159339/PHP/cookie_with_headers.php on line 11
(adapted from Stobart & Parsons (2008))
106. Using headersUsing headers
setcookie() did not run before information
was sent to the browser...
Cookies have to be sent beforethe
heading elements
107. Using headers (correct
approach) <?php
$strValue = "This is my first cookie";
setcookie ("mycookie", $strValue);
echo "Cookie set<br>";
?>
<!DOCTYPE html PUBLIC "=//W3C//DTD XHMTL 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhmtl" xml:lang="en">
<head><title>PHP Script using Cookies</title>
<meta httpequiv="ContentType" content="text/html;
charset=ISO88591" />
</head>
<body>
<?php
echo “<p> A cookie has been set. </p>”;
?>This is the correct approach!
111. Where is the cookie stored
Depends on the browser...
e.g., firefox/mozilla under /home/a________
− Look for cookies.txt in .mozilla directory
− Usually under:
/home/a______/.mozilla/firefox/asdkfljy.default
− Cookie is stored only if there is an expiry date
− Otherwise it is deleted when leaving browser
− Persistent only if an e xpiry date is se t
112.
113. You can store user information (e.g. username,
items selected, etc.) in the serverside for later
use using PHP session.
SessionsSessions work by creating a unique id (UID) for
each visitor and storing variables based on this
UID.
The UID is either stored in a cookie or is
propagated in the URL.
PHPSessionsPHPSessions
114. When should you use sessions?When should you use sessions?
Need for data to stored on the server
Unique session information for each user
Transient data, only relevant for short time
Data does not contain secret information
Similar to Cookies, but it is stored on the
server
More secure, once established, no data is sent
back and forth between the machines
Works even if cookies are disabled
Example: we want to count the number of
“hits” on our web page.
116. PHPSessionsPHPSessions
Starting a PHP session:
<?php
session_start();
?>
• This tells PHP that a session is requested.
• A session ID is then allocated at the server end.
• session ID looks like:
sess_f1234781237468123768asjkhfa7891234g
118. Registering session variablesRegistering session variables
Instead of setting superglobals, one can register one’s
own session variables
<?php
$barney = “A big purple dinosaur.”;
$myvar_name = “barney”;
session_register($myvar_name);
?>
• $barney can now be accessed “globally” from session to
session
This only works if the register_globalsregister_globals directive is enabled
in php.ini - nowadays this is turned off by default
Use of session_register() is deprecated!
119. Make yourown session variablesMake yourown session variables
With session_start()session_start() a default session
variable is created - the name extracted
from the page name
To create your own session variable just
add a new key to the $_SESSION$_SESSION
superglobal
$_SESSION$_SESSION[‘dug’] = “a talking dog.”;
Use of $_SESSION is preferred, as of PHP 4.1.0.
120. Session Example 1
<?php
session_start();
if (!isset($_SESSION["intVar"]) ){
$_SESSION["intVar"] = 1;
} else {
$_SESSION["intVar"]++;
}
echo "<p>In this session you have accessed this
page " . $_SESSION["intVar"] . "times.</p>";
?>
122. Ending sessions
unset($_SESSION[‘name’])
–Remove a session variable
session_destroy()
– Destroys all data registered to a session
– does not unset session global variables and cookies
associated with the session
–Not normally done - leave to timeout
Can be used on characters too… (incrementing only, NOT decrementing) Follows Perl conventions… e.g. Code in initial.php : $i = "A"; $i++; echo $i; Output: B