Tutorial Pemrograman Web
Tutorial Pemrograman Web
1. Pengertian HTML
Unlike a scripting or programming language that uses scripts to perform functions, a markup language uses tags to identify content.
The ability to code using HTML is essential for any web professional. Acquiring this skill should be the starting point for anyone who is learning how
to create content for the web.
Each paragraph in the example is formatted differently to demonstrate what each tag does:
-------------------
c. heading, lines, dan comments
HTML Headings
HTML includes six levels of headings, which are ranked according to importance.
These are <h1>, <h2>, <h3>, <h4>, <h5>, and <h6>.
The following code defines all of the headings:
<html>
<head>
<title>first page</title>
</head>
<body>
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
<h6>This is heading 6</h6>
</body>
</html>
Horizontal Lines
The browser does not display comments, but they help document the HTML and add descriptions, reminders, and other notes.
<!-- Your comment goes here -->
Example:
<html>
<head>
<title>first page</title>
</head>
<body>
<p>This is a paragraph </p>
<hr />
<p>This is a paragraph </p>
<!-- This is a comment -->
</body>
</html>
------------
d. Element HTML
HTML documents are made up of HTML elements.
An HTML element is written using a start tag and an end tag, and with the content in between.
HTML documents consist of nested HTML elements. In the example below, the body element includes the <p> tags, the <br /> tag and the content,
"This is a paragraph".
<html>
<head>
<title>first page</title>
</head>
<body>
<p>This is a paragraph <br /></p>
</body>
</html>
Some elements are quite small. Since you can't put contents within a break tag, and you don't have an opening and closing break tag, it’s a separate,
single element.
e. atribut
Attributes provide additional information about an element or a tag, while also modifying them. Most attributes have a value; the value modifies the
attribute.
<p align="center">
This text is aligned to center
</p>
In this example, the value of "center" indicates that the content within the p element should be aligned to the center:
Attribute Measurements
In the example below, we have a paragraph that is aligned to the center, and a line that is aligned to the right.
<html>
<head>
<title>Attributes</title>
</head>
<body>
<p align="center">This is a text <br />
<hr width="10%" align="right" /> This is also a text.
</p>
</body>
</html>
Attributes
You may be wondering what happens if you try to apply contradictory attributes within the same element.
<p align="center">
This is a text.
<hr width="50%" align="left" />
</p>
f.images
The <img> Tag
The <img> tag is used to insert an image. It contains only attributes, and does not have a closing tag.
The image's URL (address) can be defined using the src attribute.
Image Location
You need to put in the image location for the src attribute that is between the quotation marks.
For example, if you have a photo named "tree.jpg" in the same folder as the HTML file, your code should look like this:
<html>
<head>
<title>first page</title>
</head>
<body>
<img src="tree.jpg" alt="" />
</body>
</html>
Image Resizing
To define the image size, use the width and height attributes.
The value can be specified in pixels or as a percentage:
<html>
<head>
<title>first page</title>
</head>
<body>
<img src="tree.jpg" height="150px" width="150px" alt="" />
<!-- or -->
<img src="tree.jpg" height="50%" width="50%" alt="" />
</body>
</html>
Image Border
By default, an image has no borders. Use the border attribute within the image tag to create a border around the image.
<img src="tree.jpg" height="150px" width="150px" border="1px" alt="" />
g. links
The <a> Tag
Links are also an integral part of every web page. You can add links to text or images that will enable the user to click on them in order to be directed to
another file or webpage.
In HTML, links are defined using the <a> tag.
h. list
HTML Ordered Lists
An ordered list starts with the <ol> tag, and each list item is defined by the <li> tag.
Here is an example of an ordered list:
<html>
<head>
<title>first page</title>
</head>
<body>
<ol>
<li>Red</li>
<li>Blue</li>
<li>Green</li>
</ol>
</body>
</html>
HTML Unordered List
i. Tabel
Tables are defined by using the <table> tag.
Tables are divided into table rows with the <tr> tag.
Table rows are divided into table columns (table data) with the <td> tag.
To change your table's position, use the align attribute inside your table tag:
<table align="center">
Now let's specify a background color of red for a table cell. To do that, just use the bgcolor attribute.
<table border="2">
<tr>
<td bgcolor="red">Red</td>
<td>Blue</td>
<td>Green</td>
</tr>
<tr>
<td>Yellow</td>
<td colspan="2">Orange</td>
</tr>
</table>
j. Inline dan element block
In HTML, most elements are defined as block level or inline elements.
Block level elements start from a new line.
For example: <h1>, <form>, <li>, <ol>, <ul>, <p>, <pre>, <table>, <div>, etc.
The <div> element is a block-level element that is often used as a container for other HTML elements.
When used together with some CSS styling, the <div> element can be used to style blocks of content:
<html>
<body>
<h1>Headline</h1>
<div style="background-color:green; color:white; padding:20px;">
<p>Some paragraph text goes here.</p>
<p>Another paragraph goes here.</p>
</div>
</body>
</html>
You can insert inline elements inside block elements. For example, you can have multiple <span> elements inside a <div> element.
Inline elements cannot contain any block level elements.
k. Form
HTML forms are used to collect information from the user.
Forms are defined using the <form> element, with its opening and closing tags:
<body>
<form>…</form>
</body>
Use the action attribute to point to a webpage that will load after the user submits the form.
<form action="http://www.sololearn.com">
</form>
The method attribute specifies the HTTP method (GET or POST) to be used when forms are submitted (see below for description):
<form action="url" method="GET">
When you use GET, the form data will be visible in the page address.
Use POST if the form is updating data, or includes sensitive information (passwords).
POST offers better security because the submitted data is not visible in the page address.
To take in user input, you need the corresponding form elements, such as text fields. The <input> element has many variations, depending on the type
attribute. It can be a text, password, radio, URL, submit, etc.
If we change the input type to radio, it allows the user select only one of a number of choices:
<input type="radio" name="gender" value="male" /> Male <br />
<input type="radio" name="gender" value="female" /> Female <br />
The type "checkbox" allows the user to select more than one option:
<input type="checkbox" name="gender" value="1" /> Male <br />
<input type="checkbox" name="gender" value="2" /> Female <br />
l. html color
HTML colors are expressed as hexadecimal values.
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F
As you can see, there are 16 values there, 0 through F. Zero represents the lowest value, and F represents the highest.
Colors are displayed in combinations of red, green, and blue light (RGB).
Hex values are written using the hashtag symbol (#), followed by either three or six hex characters.
As shown in the picture below, the circles overlap,
forming new colors:
All of the possible red, green, and blue combinations potentially number over 16 million.
The bgcolor attribute can be used to change the web page's background color.
This example would produce a dark blue background with a white headline:
<html>
<head>
<title>first page</title>
</head>
<body bgcolor="#000099">
<h1>
<font color="#FFFFFF"> White headline </font>
</h1>
</body>
</html>
m. frames
A page can be divided into frames using a special frame document.
The <frame> tag defines one specific window (frame) within a <frameset>. Each <frame> in a <frameset> can have different attributes, such as border,
scrolling, the ability to resize, etc.
The <frameset> element specifies the number of columns or rows in the frameset, as well as what percentage or number of pixels of space each of
them occupies.
<frameset cols="100, 25%, *"></frameset>
<frameset rows="100, 25%, *"></frameset>
The <frameset> tag is not supported in HTML5.
Use the <noresize> attribute to specify that a user cannot resize a <frame> element:
<frame noresize="noresize">
Lastly, the <noframes> element provides a way for browsers that do not support frames to view the page. The element can contain an alternative page,
complete with a body tag and any other elements.
<frameset cols="25%,50%,25%">
<frame src="a.htm" />
<frame src="b.htm" />
<frame src="c.htm" />
<noframes>Frames not supported!</noframes>
</frameset>
There are two different ways to specify the audio source file's URL. The first uses the source attribute:
<audio src="audio.mp3" controls>
Audio element not supported by your browser
</audio>
The second way uses the <source> element inside the <audio> element:
<audio controls>
<source src="audio.mp3" type="audio/mpeg">
<source src="audio.ogg" type="audio/ogg">
</audio>
Attributes of <audio>
controls
Specifies that audio controls should be displayed (such as a play/pause button, etc.)
autoplay
When this attribute is defined, audio starts playing as soon as it is ready, without asking for the visitor's permission.
<audio controls autoplay>
loop
This attribute is used to have the audio replay every time it is finished.
<audio controls autoplay loop>
Currently, there are three supported file formats for the <audio> element: MP3, WAV, and OGG.
o. video
The video element is similar to the audio element.
You can specify the video source URL using an attribute in a video element, or using source elements inside the video element:
<video controls>
<source src="video.mp4" type="video/mp4">
<source src="video.ogg" type="video/ogg">
Video is not supported by your browser
</video>
CSS
The main benefit of CSS is that it allows you to separate style from content.
Using just HTML, all the styles and formatting are in the same place, which becomes rather difficult to maintain as the page grows.
All formatting can (and should) be removed from the HTML document and stored in a separate CSS file.
Using an inline style is one of the ways to insert a style sheet. With an inline style, a unique style is applied to a single element.
In order to use an inline style, add the style attribute to the relevant tag.
The example below shows how to create a paragraph with a gray background and white text:
<p style="color:white; background-color:gray;">
This is an example of inline styling.
</p>
Internal styles are defined within the <style> element, inside the head section of an HTML page.
<html>
<head>
<style>
p{
color:white;
background-color:gray;
}
</style>
</head>
<body>
<p>This is my first paragraph. </p>
<p>This is my second paragraph. </p>
</body>
</html>
With this method, all styling rules are contained in a single text file, which is saved with the .css extension.
This CSS file is then referenced in the HTML using the <link> tag. The <link> element goes inside the head section.
Here is an example:
The HTML:
<head>
<link rel="stylesheet" href="example.css">
</head>
<body>
<p>This is my first paragraph.</p>
<p>This is my second paragraph. </p>
<p>This is my third paragraph. </p>
</body>
The CSS:
p{
color:white;
background-color:gray;
}
Both relative and absolute paths can be used to define the href for the CSS file. In our example, the path is relative, as the CSS file is in the same
directory as the HTML file.
CSS Syntax
CSS is composed of style rules that the browser interprets and then applies to the corresponding elements in your document.
A style rule has three parts: selector, property, and value.
The most common and easy to understand selectors are type selectors. This selector targets element types on the page.
id selectors allow you to style an HTML element that has an id attribute, regardless of their position in the document tree. Here is an example of an id
selector:
The HTML:
<div id="intro">
<p> This paragraph is in the intro section.</p>
</div>
<p> This paragraph is not in the intro section.</p>
The CSS:
#intro {
color: white;
background-color: gray;
}
Class selectors work in a similar way. The major difference is that IDs can only be applied once per page, while classes can be used as many times on a
page as needed.
In the example below, both paragraphs having the class "first" will be affected by the CSS:
The HTML:
<div>
<p class="first">This is a paragraph</p>
<p> This is the second paragraph. </p>
</div>
<p class="first"> This is not in the intro section</p>
<p> The second paragraph is not in the intro section. </p>
The CSS:
.first {font-size: 200%;}
Descendant Selectors
These selectors are used to select elements that are descendants of another element. When selecting levels, you can select as many levels deep as you
need to.
For example, to target only <em> elements in the first paragraph of the "intro" section:
The HTML:
<div id="intro">
<p class="first">This is a <em> paragraph.</em></p>
<p> This is the second paragraph. </p>
</div>
<p class="first"> This is not in the intro section.</p>
<p> The second paragraph is not in the intro section. </p>
The CSS:
#intro .first em {
color: pink;
background-color:gray;
}
property teks
font family
size
style
weight
The CSS color property specifies the color of the text.
One method of specifying the color of the text is using a color name: like red, green, blue, etc.
Here's an example of changing the color of your font.
The HTML:
<p class="example">The text inside the paragraph is green.</p>
The text outside the paragraph is black (by default).
The CSS:
p.example {
color: green;
}
javascript
Welcome to JavaScript
JavaScript is one of the most popular programming languages on earth and is used to add interactivity to webpages, process data, as well as create
various applications (mobile apps, desktop apps, games, and more)
Learning the fundamentals of a language will enable you to create the program you desire, whether client-side or server-side.
The document.write() function writes a string into our HTML document. This function can be used to write text, HTML, or both.
Just like in HTML, we can use HTML tags to format text in JavaScript.
For example, we can output the text as a heading.
<html>
<head> </head>
<body>
<script>
document.write("<h1>Hello World!</h1>");
</script>
</body>
</html>
Variables
Variables are containers for storing data values. The value of a variable can change throughout the program.
Use the var keyword to declare a variable:
var x = 10;
In JavaScript, the equal sign (=) is called the "assignment" operator, rather than an "equal to" operator.
For example, x = y will assign the value of y to x.
A variable can be declared without a value. The value might require some calculation, something that will be provided later, like user input.
A variable declared without a value will have the value undefined.
Using Variables
Data Types
The term data type refers to the types of values with which a program can work. JavaScript variables can hold many data types, such as numbers,
strings, arrays, and more.
Unlike many other programming languages, JavaScript does not define different types of numbers, like integers, short, long, floating-point, etc.
Floating-Point Numbers
Strings
You can use quotes inside a string, as long as they don't match the quotes surrounding the string.
var text = "My name is 'John' ";
Booleans
In JavaScript Boolean, you can have one of two values, either true or false.
These are useful when you need a data type that can only have one of two values, such as Yes/No, On/Off, True/False.
Example:
var isActive = true;
var isHoliday = false;
Arithmetic Operators
In the example below, the addition operator is used to determine the sum of two numbers.
var x = 10 + 5;
document.write(x);
// Outputs 15
Assignment Operators
Comparison Operators
Logical Operators, also known as Boolean Operators, evaluate the expression and return true or false.
The table below explains the logical operators (AND, OR, NOT).
Logical Operators
In the following example, we have connected two Boolean expressions with the AND operator.
(4 > 2) && (10 < 15)
For example:
var isAdult = (age < 18) ? "Too young": "Old enough";
If the variable age is a value below 18, the value of the variable isAdult will be "Too young". Otherwise the value of isAdult will be "Old enough".
Logical operators allow you to connect as many expressions as you wish.
String Operators
The most useful operator for strings is concatenation, represented by the + sign.
Concatenation can be used to build strings by joining together multiple strings, or by joining strings with other types:
var mystring1 = "I am
learning ";
var mystring2 = "JavaScript
with SoloLearn.";
document.write(mystring1 +
mystring2);
The if Statement
Very often when you write code, you want to perform different actions based on different conditions.
You can do this by using conditional statements in your code.
Use if to specify a block of code that will be executed if a specified condition is true.
if (condition) {
statements
}
Example:
var myNum1 = 7;
var myNum2 = 10;
if (myNum1 < myNum2) {
alert("JavaScript is easy to learn.");
}
Use the else statement to specify a block of code that will execute if the condition is false.
if (expression) {
// executed if condition is true
}
else {
// executed if condition is false
}
You can use the else if statement to specify a new condition if the first condition is false.
Example:
var course = 1;
if (course == 1) {
document.write("<h1>HTML Tutorial</h1>");
} else if (course == 2) {
document.write("<h1>CSS Tutorial</h1>");
} else {
document.write("<h1>JavaScript Tutorial</h1>");
}
Switch
In cases when you need to test for multiple conditions, writing if else statements for each condition might not be the best solution.
The switch statement is used to perform different actions based on different conditions.
Syntax:
switch (expression) {
case n1:
statements
break;
case n2:
statements
break;
default:
statements
}
The switch expression is evaluated once. The value of the expression is compared with the values of each case. If there is a match, the associated block
of code is executed
// Outputs "Tuesday"
Loops
Loops can execute a block of code a number of times. They are handy in cases in which you want to run the same code repeatedly, adding a different
value each time.
JavaScript has three types of loops: for, while, and do while.
The syntax:
for (statement 1; statement 2; statement 3) {
code block to be executed
}
The example below creates a for loop that prints numbers 1 through 5.
for (i=1; i<=5; i++) {
document.write(i + "<br />");
}
Try It Yourself
In this example, Statement 1 sets a variable before the loop starts (var i = 1).
Statement 2 defines the condition for the loop to run (i must be less than or equal to 5).
Statement 3 increases a value (i++) each time the code block in the loop has been executed.
Result:
The While Loop
The while loop repeats through a block of code, as long as a specified condition is true.
Syntax:
while (condition) {
code block
}
The condition can be any conditional statement that returns true or false.
To define a JavaScript function, use the function keyword, followed by a name, followed by a set of parentheses ().
The code to be executed by the function is placed inside curly brackets {}.
function name() {#
//code to be executed#
}
myFunction();
//Alerts "Calling a Function!"
JavaScript Objects
JavaScript variables are containers for data values. Objects are variables too, but they can contain many values.
Think of an object as a list of values that are written as name:value pairs, with the names and the values separated by colons.
Example:
var person = {
name: "John", age: 31,
favColor: "green", height: 183
};
Object Properties
This example demonstrates how to access the age of our person object.
var person = {
name: "John", age: 31,
favColor: "green", height: 183
};
var x = person.age;
var y = person['age'];
JavaScript's built-in length property is used to count the number of characters in a property or string.
var course = {name: "JS", lessons: 41};
document.write(course.name.length);
//Outputs 2
Object Methods
As you already know, document.write() outputs data. The write() function is actually a method of the document object.
document.write("This is some text");
JavaScript Arrays
You refer to an array element by referring to the index number written in square brackets.
This statement accesses the value of the first element in courses and changes the value of the second element.
var courses = new Array("HTML", "CSS", "JS");
var course = courses[0]; // HTML
courses[1] = "C++"; //Changes the second element
[0] is the first element in an array. [1] is the second. Array indexes start with 0.
Using new Date(), create a new date object with the current date and time.
var d = new Date();
//d stores the current date and time
The other ways to initialize dates allow for the creation of new date objects from the specified date and time.
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
JavaScript dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC). One day contains 86,400,000 millisecond.
For example:
//Fri Jan 02 1970 00:00:00
var d1 = new Date(86400000);
Date Methods
When a Date object is created, a number of methods make it possible to perform operations on it
For example:
var d = new Date();
var hours = d.getHours();
//hours is equal to the current hour
Let's create a program that prints the current time to the browser once every second.
function printTime() {
var d = new Date();
var hours = d.getHours();
var mins = d.getMinutes();
var secs = d.getSeconds();
document.body.innerHTML = hours+":"+mins+":"+secs;
}
setInterval(printTime, 1000);
We declared a function printTime(), which gets the current time from the date object, and prints it to the screen.
We then called the function once every second, using the setInterval method.
The innerHTML property sets or returns the HTML content of an element.
In our case, we are changing the HTML content of our document's body. This overwrites the content every second, instead of printing it repeatedly to
the screen.
Php
Welcome to PHP
PHP: Hypertext Preprocessor (PHP) is a free, highly popular, open source scripting language. PHP scripts are executed on the server.
Before starting this tutorial, you should have a basic understanding of HTML.
PHP Syntax
Here is an example of a simple PHP file. The PHP script uses a built in function called "echo" to output the text "Hello World!" to a web page.
<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
Echo
Comments
In PHP code, a comment is a line that is not executed as part of the program. You can use comments to communicate to others so they understand what
you're doing, or as a reminder to yourself of what you did.
Variables
For example:
<?php
$name = 'John';
$age = 25;
echo $name;
// Outputs 'John'
?>
In the example above, notice that we did not have to tell PHP which data type the variable is.
PHP automatically converts the variable to the correct data type, depending on its value.
Unlike other programming languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it.
Constants are similar to variables except that they cannot be changed or undefined after they've been defined.
Begin the name of your constant with a letter or an underscore.
To create a constant, use the define() function:
define(name, value, case-insensitive)
Parameters:
name: Specifies the name of the constant;
value: Specifies the value of the constant;
case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false;
Data Types
You can join two strings together using the dot ( .) concatenation operator.
For example: echo $s1 . $s2
PHP Integer
An integer is a whole number (without decimals) that must fit the following criteria:
- It cannot contain commas or blanks
- It must not have a decimal point
- It can be either positive or negative
<?php
$int1 = 42; // positive number
$int2 = -42; // negative number
?>
PHP Float
PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.
<?php
$x = true; $y = false;
?>
Booleans are often used in conditional testing, which will be covered later on in the course.
Most of the data types can be used in combination with one another. In this example, string and integer are put together to determine the sum of two
numbers.
<?php
$str = "10";
$int = 20;
$sum = $str + $int;
echo ($sum);
// Outputs 30
?>
Variables Scope
This script will produce an error, as the $name variable has a global scope, and is not accessible within the getName() function. Tap continue to see
how functions can access global variables.
Functions will be discussed in the coming lessons.
The global keyword is used to access a global variable from within a function.
To do this, use the global keyword within the function, prior to the variables.
<?php
$name = 'David';
function getName() {
global $name;
echo $name;
}
getName();
//Outputs 'David'
?>
Variable Variables
With PHP, you can use one variable to specify another variable's name.
So, a variable variable treats the value of another variable as its name.
For example:
<?php
$a = 'hello';
$hello = "Hi!";
echo $$a;
// Outputs 'Hi!'
?>
Operators
Arithmetic Operators
Arithmetic operators work with numeric values to perform common arithmetical operations.
Example:
<?php
$num1 = 8;
$num2 = 6;
//Addition
echo $num1 + $num2; //14
//Subtraction
echo $num1 - $num2; //2
//Multiplication
echo $num1 * $num2; //48
//Division
echo $num1 / $num2; //1.33333333333
?>
Modulus
The modulus operator, represented by the % sign, returns the remainder of the division of the first operand by the second operand:
<?php
$x = 14;
$y = 3;
echo $x % $y; // 2
?>
The difference is that the post-increment returns the original value before it changes the variable, while the pre-increment changes the variable first and
then returns the value.
Example:
$a = 2; $b = $a++; // $a=3, $b=2
$a = 2; $b = ++$a; // $a=3, $b=3
Assignment Operators
Assignment operators are used to write values to variables.
$num1 = 5;
$num2 = $num1;
Example:
<?php
$x = 50;
$x += 100;
echo $x;
// Outputs: 150
?>
Comparison Operators
Comparison operators compare two values (numbers or strings).
Comparison operators are used inside conditional statements, and evaluate to either TRUE or FALSE.
Logical Operators
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of names, for example), storing them in single variables would look like this:
$name1 = "David";
$name2 = "Amy";
$name3 = "John";
But what if you have 100 names on your list? The solution: Create an array!
Numeric Arrays
Numeric or indexed arrays associate a numeric index with their values.
The index can be assigned automatically (index always starts at 0), like this:
$names = array("David", "Amy", "John");
Conditional Statements
Use the if...elseif...else statement to specify a new condition to test, if the first condition is false.
Syntax:
if (condition) {
code to be executed if condition is true;
} elseif (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Loops
When writing code, you may want the same block of code to run over and over again. Instead of adding several almost equal code-lines in a script, we
can use loops to perform a task like this.
The while loop executes a block of code as long as the specified condition is true.
Syntax:
while (condition is true) {
code to be executed;
}
Syntax:
switch (n) {
case value1:
//code to be executed if n=value1
break;
case value2:
//code to be executed if n=value2
break;
...
default:
// code to be executed if n is different from all labels
}
First, our single expression, n (most often a variable), is evaluated once. Next, the value of the expression is compared with the value of each case in
the structure. If there is a match, the block of code associated with that case is executed.
Using nested if else statements results in similar behavior, but switch offers a more elegant and optimal solution.
include
The include and require statements allow for the insertion of the content of one PHP file into another PHP file, before the server executes it.
Including files saves quite a bit of work. You can create a standard header, footer, or menu file for all of your web pages. Then, when the header is
requiring updating, you can update the header include file only.
<p>Some text.</p>
<p>Some text.</p>
</body>
</html>
The include and require statements allow for the insertion of the content of one PHP file into another PHP file, before the server executes it.
include
Using this approach, we have the ability to include the same header.php file into multiple pages.
<html>
<body>
<p>This is a paragraph</p>
</body>
</html>
Functions
Return
Predefined Variables
A superglobal is a predefined variable that is always accessible, regardless of scope. You can access the PHP superglobals through any function, class,
or file.
PHP's superglobal variables are $_SERVER, $GLOBALS, $_REQUEST, $_POST, $_GET, $_FILES, $_ENV, $_COOKIE, $_SESSION.
$_SERVER
$_SERVER is an array that includes information such as headers, paths, and script locations. The entries in this array are created by the web server.
$_SERVER['SCRIPT_NAME'] returns the path of the current script:
<?php
echo $_SERVER['SCRIPT_NAME'];
//Outputs "/somefile.php"
?>
$_SERVER
This method can be useful when you have a lot of images on your server and need to transfer the website to another host. Instead of changing the path
for each image, you can do the following:
Create a config.php file, that holds the path to your images:
<?php
$host = $_SERVER['HTTP_HOST'];
$image_path = $host.'/images/';
?>
The path to your images is now dynamic. It will change automatically, based on the Host header.
The purpose of the PHP superglobals $_GET and $_POST is to collect data that has been entered into a form.
The example below shows a simple HTML form that includes two input fields and a submit button:
<form action="first.php" method="post">
<p>Name: <input type="text" name="name" /></p>
<p>Age: <input type="text" name="age" /></p>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>
The action attribute specifies that when the form is submitted, the data is sent to a PHP file named first.php.
HTML form elements have names, which will be used when accessing the data with PHP.
The method attribute will be discussed in the next lesson. For now, we'll set the value to "post".
Now, when we have an HTML form with the action attribute set to our PHP file, we can access the posted form data using the $_POST associative
array.
In the first.php file:
<html>
<body>
</body>
</html>
The $_POST superglobal array holds key/value pairs. In the pairs, keys are the names of the form controls and values are the input data entered by the
user.
We used the $_POST array, as the method="post" was specified in the form.
To learn more about the form methods, press Continue!
The two methods for submitting forms are GET and POST.
Information sent from a form via the POST method is invisible to others, since all names and/or values are embedded within the body of the HTTP
request. Also, there are no limits on the amount of information to be sent.
Moreover, POST supports advanced functionality such as support for multi-part binary input while uploading files to the server.
However, it is not possible to bookmark the page, as the submitted values are not visible.
POST is the preferred method for sending form data.
GET
Information sent via a form using the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also sets limits
on the amount of information that can be sent - about 2000 characters.
However, because the variables are displayed in the URL, it is possible to bookmark the page, which can be useful in some situations.
For example:
<form action="actionGet.php" method="get">
Name: <input type="text" name="name" /><br /><br />
Age: <input type="text" name="age" /><br /><br />
<input type="submit" name="submit" value="Submit" />
</form>
actionGet.php
<?php
echo "Hi ".$_GET['name'].". ";
echo "You are ".$_GET['age']." years old.";
?>
Now, the form is submitted to the actionGet.php, and you can see the submitted data in the URL:
GET should NEVER be used for sending passwords or other sensitive information!
When using POST or GET, proper validation of form data through filtering and processing is vitally important to protect your form from hackers and
exploits!
Sessions
Using a session, you can store information in variables, to be used across multiple pages.
Information is not stored on the user's computer, as it is with cookies.
By default, session variables last until the user closes the browser.
$_SESSION['color'] = "red";
$_SESSION['name'] = "John";
?>
Now, the color and name session variables are accessible on multiple pages, throughout the entire session.
The session_start() function must be the very first thing in your document. Before any HTML tags.
Cookies
Cookies are often used to identify the user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer
requests a page through a browser, it will send the cookie, too. With PHP, you can both create and retrieve cookie values.
Cookies
The following example creates a cookie named "user" with the value "John". The cookie will expire after 30 days, which is written as 86,400 * 30, in
which 86,400 seconds = one day. The '/' means that the cookie is available throughout the entire website.
We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also use the isset() function to find out if the cookie is set:
<?php
$value = "John";
setcookie("user", $value, time() + (86400 * 30), '/');
if(isset($_COOKIE['user'])) {
echo "Value is: ". $_COOKIE['user'];
}
//Outputs "Value is: John"
?>