Vous êtes sur la page 1sur 77

HTML

1. Pengertian HTML

HTML stands for HyperText Markup Language.

Unlike a scripting or programming language that uses scripts to perform functions, a markup language uses tags to identify content.

Here is an example of an HTML tag:


<p> I'm a paragraph </p>

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.

Modern Web Design


HTML: Structure
CSS: Presentation
JavaScript: Behavior
PHP or similar: Backend
CMS: Content Management

2. Struktur Dasar Dokumen HTML


a. The <html> Tag
Although various versions have been released over the years, HTML basics remain the same.
The structure of an HTML document has been compared with that of a sandwich. As a sandwich has two slices of bread, the HTML document has
opening and closing HTML tags.
These tags, like the bread in a sandwich, surround everything else:
<html>

</html>

b. The <head> Tag


Immediately following the opening HTML tag, you'll find the head of the document, which is identified by opening and closing head tags.
The head of an HTML file contains all of the non-visual elements that help make the page work.
<html>
<head>…</head>
</html>

c. The <body> Tag


The body tag follows the head tag.
All visual-structural elements are contained within the body tag.
Headings, paragraphs, lists, quotes, images, and links are just a few of the elements that can be contained within the body tag.
Basic HTML Structure:
<html>
<head>
</head>
<body>
</body>
</html>

3. Dasar Tag HTML


a. Paragraph
To create a paragraph, simply type in the <p> element with its opening and closing tags:
<html>
<head>
<title>first page</title>
</head>
<body>
<p>This is a paragraph. </p>
<p>This is another paragraph.
</p>
</body>
</html>
Use the <br /> tag to add a single line of text without starting a new paragraph:
<html>
<head>
<title>first page</title>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph. </p>
<p>This is <br /> a line break </p>
</body>
</html>
----------------------------------------
b. format teks
In HTML, there is a list of elements that specify text style.
Formatting elements were designed to display special types of text:
<html>
<head>
<title>first page</title>
</head>
<body>
<p>This is regular text </p>
<p><b> bold text </b></p>
<p><big> big text </big></p>
<p><i> italic text </i></p>
<p><small> small text </small></p>
<p><strong> strong text </strong></p>
<p><sub> subscripted text </sub></p>
<p><sup> superscripted text </sup></p>
<p><ins> inserted text </ins></p>
<p><del> deleted text </del></p>
</body>
</html>

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

To create a horizontal line, use the <hr /> tag.


<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>
<p>This is a paragraph </p>
<hr />
<p>This is a paragraph </p>
</body>
</html>
Comments

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.

So HTML is really scripting with elements within elements.


<html>
<head>
<title>first page</title>
</head>
<body>
<p>This is a paragraph</p>
<p>This is a <br /> line break</p>
</body>
</html>

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

As an example, we can modify the horizontal line so it has a width of 50 pixels.

This can be done by using the width attribute:


<hr width="50px" />

An element's width can also be defined using percentages:


<hr width="50%" />

An element's width can be defined using pixels or percentages.

The Align Attribute

The align attribute is used to specify how the text is aligned.

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>

The align attribute of <p> is not supported in HTML5.

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.

The HTML image syntax looks like this:


<img src="image.jpg" />

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.

Use the href attribute to define the link's destination address:


<a href=""></a>

The target Attribute

The target attribute specifies where to open the linked document.


Giving a _blank value to your attribute will have the link open in a new window or new tab:
<a href="http://www.sololearn.com" target="_blank">
Learn Playing
</a>

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

An unordered list starts with the <ul> tag.


<html>
<head>
<title>first page</title>
</head>
<body>
<ul>
<li>Red</li>
<li>Blue</li>
<li>Green</li>
</ul>
</body>
</html>

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.

Here is an example of a table with one row and three columns:


<table>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>

A border can be added using the border attribute:


<table border="2">

A table cell can span two or more columns:


<table border="2">
<tr>
<td>Red</td>
<td>Blue</td>
<td>Green</td>
</tr>
<tr>
<td><br /></td>
<td colspan="2"><br /></td>
</tr>
</table>
The example below demonstrates the colspan attribute in action:
<table border="2">
<tr>
<td>Red</td>
<td>Blue</td>
<td>Green</td>
</tr>
<tr>
<td>Yellow</td>
<td colspan="2">Orange</td>
</tr>
You can see that the cell containing "Orange" spans two cells.
To make a cell span more than one row, use the rowspan attribute.

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.

Inline elements are normally displayed without line breaks.


For example: <b>, <a>, <strong>, <img>, <input>, <em>, <span>, 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>

Similarly, the <span> element is an


inline element that is often used as a
container for some text.
When used together with CSS, the
<span> element can be used to style
parts of the text:
<html>
<body>
<h2>Some
<span
style="color:red">Important</span>
Message</h2>
</body>
</html>
Summary
The <div> element defines a block-
level section in a document.
The <span> element defines an
inline section in a document.

Other elements can be used either as


block level elements or inline
elements. This includes the
following elements:
APPLET - embedded Java applet
IFRAME - Inline frame
INS - inserted text
MAP - image map
OBJECT - embedded object
SCRIPT - script within an HTML document

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">

<form action="url" method="POST">

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.

The example below shows a form requesting a username and password:


<form>
<input type="text" name="username" /><br />
<input type="password" name="password" />
</form>

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 />

The submit button submits a form to its action attribute:


<input type="submit" value="Submit" />
After the form is submitted, the data should
be processed on the server using a programming language, such as PHP.

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.

Here are only a few of them:

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">

Frame content should be defined using the src attribute.

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>

The <frame> tag is not supported in HTML5.


n. audio
Before HTML5, there was no standard for playing audio files on a web page.
The HTML5 <audio> element specifies a standard for embedding audio in a web page.

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>

The <audio> element creates an audio player inside the browser.


<audio controls>
<source src="audio.mp3" type="audio/mpeg">
<source src="audio.ogg" type="audio/ogg">
Audio element not supported by your browser.
</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

CSS stands for Cascading Style Sheets.


- Cascading refers to the way CSS applies one style on top of another.
- Style Sheets control the look and feel of web documents.

CSS and HTML work hand in hand:


- HTML sorts out the page structure.
- CSS defines how HTML elements are displayed.

CSS allows you to apply specific styles to specific HTML elements.

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.

For example, the following code styles all paragraphs:

<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>

All paragraphs have a white font and a gray background:


External CSS

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.

For example, the headline color can be defined as:


h1 { color: orange; }
Where:

The selector points to the HTML element you want to style.


The declaration block contains one or more declarations, separated by semicolons.
Each declaration includes a property name and a value, separated by a colon.

The most common and easy to understand selectors are type selectors. This selector targets element types on the page.

For example, to target all the paragraphs on the page:


p{
color: red;
font-size:130%;
}

id and class Selectors

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.

Let's use JavaScript to print "Hello World" to the browser.


<html>
<head> </head>
<body>
<script>
document.write("Hello World!");
</script>
</body>
</html>

The document.write() function writes a string into our HTML document. This function can be used to write text, HTML, or both.

The above code displays the following result


Formatting Text

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 the example above, the value 10 is assigned to the variable x.


JavaScript is case sensitive. For example, the variables lastName and lastname, are two different variables.

The Equal Sign

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

Let's assign a value to a variable and output it to the browser.


var x = 100;
document.write(x);
Using variables is useful in many ways. You might have a thousand lines of code that may include the variable x. When you change the value of x one
time, it will automatically be changed in all places where you used it

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.

JavaScript numbers can be written with or without decimals.


var num = 42; // A number without decimals

Floating-Point Numbers

JavaScript numbers can also have decimals.


<script>
var price = 55.55;
document.write(price);
</script>

Strings

JavaScript strings are used for storing and manipulating text.


A string can be any text that appears within quotes. You can use single or double quotes.
var name = 'John';
var text = "My name is John Smith";

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;

The Boolean value of 0 (zero), null, undefined, empty string is false.


Everything with a "real" value is true.

Arithmetic Operators

Arithmetic operators perform arithmetic functions on numbers (literals or variables).

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

Assignment operators assign values to JavaScript variables.

You can use multiple assignment


operators in one line, such as x -= y
+= 9.

Comparison Operators

Comparison operators are used in


logical statements to determine equality or difference between variables or values. They return true or false.

The equal to (==) operator checks


whether the operands' values are
equal.
var num = 10;
// num == 8 will return false

The table below explains the


comparison operators.
Logical 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 this expression to be true, both conditions must be true.


- The first condition determines whether 4 is greater than 2, which is true.
- The second condition determines whether 10 is less than 15, which is also true.
Based on these results, the whole expression is found to be true.

Conditional (Ternary) Operator


Another JavaScript conditional operator assigns a value to a variable, based on some condition.
Syntax:
variable = (condition) ? value1: value2

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
}

The statements will be executed only if the specified condition is true.

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>");
}

The above code says:


- if course is equal to 1, output "HTML Tutorial";
- else, if course is equal to 2, output "CSS Tutorial";
- if none of the above condition is true, then output "JavaScript Tutorial";

course is equal to 1, so we get the following result:

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

Consider the following example.


var day = 2;
switch (day) {
case 1:
document.write("Monday");
break;
case 2:
document.write("Tuesday");
break;
case 3:
document.write("Wednesday");
break;
default:
document.write("Another day");
}

// 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 for loop is commonly used when creating a loop.

The syntax:
for (statement 1; statement 2; statement 3) {
code block to be executed
}

Statement 1 is executed before the loop (the code block) starts.


Statement 2 defines the condition for running the loop (the code block).
Statement 3 is executed each time after the loop (the code block) has been executed.
As you can see, the classic for loop has three components, or statements.

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.

The While Loop

Consider the following example.


var i=0;
while (i<=10) {
document.write(i + "<br />");
i++;
}
The loop will continue to run as long as i is less than, or equal to, 10. Each time the loop runs, it will increase by 1.

This will output the values from 0 to 10.


The break statement "jumps out" of a loop and continues executing the code after the loop.
for (i = 0; i <= 10; i++) {
if (i == 5) {
break;
}
document.write(i + "<br />");
}

Once i reaches 5, it will break


out of the loop.
JavaScript Functions

A JavaScript function is a block of code designed to perform a particular task.


The main advantages of using functions:
Code reuse: Define the code once, and use it many times.
Use the same code many times with different arguments, to produce different results.
A JavaScript function is executed when "something" invokes, or calls, it.

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#
}

To execute the function, you need to call it.


To call a function, start with the name of the function, then follow it with the arguments in parentheses.
Example:
function myFunction() {
alert("Calling a Function!");
}

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
};

These values are called properties.

Object Properties

You can access object properties in two ways.


objectName.propertyName
//or
objectName['propertyName']

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

An object method is a property that contains a function definition.

Use the following syntax to access an object method.


objectName.methodName()

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

Arrays store multiple values in a single variable.

To store three course names, you need three variables.


var course1 ="HTML";
var course2 ="CSS";
var course3 ="JS";

But what if you had 500 courses? The solution is an array.


var courses = new Array("HTML", "CSS", "JS");
Accessing an Array

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.

The Date Object

The Date object enables us to work with dates.


A date consists of a year, a month, a day, an hour, a minute, a second, and milliseconds.

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);

//Fri Jan 02 2015 10:42:00


var d2 = new Date("January 2, 2015 10:42:00");

//Sat Jun 11 1988 11:42:00


var d3 = new Date(88,5,11,11,42,0,0);

JavaScript counts months from 0 to 11. January is 0, and December is 11.


Date objects are static, rather than dynamic. The computer time is ticking, but date objects don't change, once created.

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.

Just a short list of what PHP is capable of:


- Generating dynamic page content
- Creating, opening, reading, writing, deleting, and closing files on the server
- Collecting form data
- Adding, deleting, and modifying information stored in your database
- controlling user-access
- encrypting data
- and much more!

Before starting this tutorial, you should have a basic understanding of HTML.

PHP Syntax

A PHP script starts with <?php and ends with ?>:


<?php
// PHP code goes here
?>

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

PHP has a built-in "echo" function, which is used to output text.


In actuality, it's not a function; it's a language construct. As such, it does not require parentheses.

Let's output a text.


<?php
echo "I love PHP!";
?>

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.

A single-line comment starts with //:


<?php
echo "<p>Hello World!</p>";
// This is a single-line comment
echo "<p>I am learning PHP!</p>";
echo "<p>This is my first program!</p>";
?>

Variables

Variables are used as "containers" in which we store information.


A PHP variable starts with a dollar sign ($), which is followed by the name of the variable.
$variable_name = value;

Rules for PHP variables:


- A variable name must start with a letter or an underscore
- A variable name cannot start with a number
- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
- Variable names are case-sensitive ($name and $NAME would be two different 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;

The example below creates a constant with a case-sensitive name:


<?php
define("MSG", "Hi SoloLearners!");
echo MSG;

// Outputs "Hi SoloLearners!"


?>

Data Types

Variables can store a variety of data types.


Data types supported by PHP: String, Integer, Float, Boolean, Array, Object, NULL, Resource.
PHP String
A string is a sequence of characters, like "Hello world!"
A string can be any text within a set of single or double quotes.
<?php
$string1 = "Hello world!"; //double quotes
$string2 = 'Hello world!'; //single quotes
?>

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
?>

Variables can store a variety of data types.

PHP Float

A float, or floating point number, is a number that includes a decimal point.


<?php
$x = 42.168;
?>

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

PHP variables can be declared anywhere in the script.


The scope of a variable is the part of the script in which the variable can be referenced or used.

PHP's most used variable scopes are local, global.


A variable declared outside a function has a global scope.
A variable declared within a function has a local scope, and can only be accessed within that function.

Consider the following example.


<?php
$name = 'David';
function getName() {
echo $name;
}
getName();

// Error: Undefined variable: name


?>

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

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

Operators carry out operations on variables and values.

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
?>

Increment & Decrement

The increment operators are used to increment a variable's value.


The decrement operators are used to decrement a variable's value.
$x++; // equivalent to $x = $x+1;
$x--; // equivalent to $x = $x-1;

Increment and decrement operators either precede or follow a variable.


$x++; // post-increment
$x--; // post-decrement
++$x; // pre-increment
--$x; // pre-decrement

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

The increment operators are used to increment a variable's value.

Assignment Operators
Assignment operators are used to write values to variables.
$num1 = 5;
$num2 = $num1;

$num1 and $num2 now contain the value of 5.

Assignments can also be used in conjunction with arithmetic operators.

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

Logical operators are used to combine conditional statements.


Arrays

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");

As an alternative, you can assign your index manually.


$names[0] = "David";
$names[1] = "Amy";
$names[2] = "John";

We defined an array called $names that stores three values.


You can access the array elements through their indices.
echo $names[1]; // Outputs "Amy"

Conditional Statements

Conditional statements perform different actions for different decisions.


The if else statement is used to execute a certain code if a condition is true, and another code if the condition is false.
Syntax:
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}

The Elseif Statement

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

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;
}

The switch Statement

The switch statement is an alternative to the if-elseif-else statement.


Use the switch statement to select one of a number of blocks of 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.

Assume that we have a standard header file called header.php.


<?php
echo '<h1>Welcome</h1>';
?>

Use the include statement to include the header file in a page.


<html>
<body>

<?php include 'header.php'; ?>

<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>

<?php include 'header.php'; ?>

<p>This is a paragraph</p>
</body>
</html>

Functions

A function is a block of statements that can be used repeatedly in a program.


A function will not execute immediately when a page loads. It will be executed by a call to the function.
A user defined function declaration starts with the word function:
function functionName() {
//code to be executed
}
A function name can start with a letter or an underscore, but not with a number or a special symbol.
Function names are NOT case-sensitive.

Return

A function can return a value using the return statement.


Return stops the function's execution, and sends the value back to the calling code.
For example:
function mult($num1, $num2) {
$res = $num1 * $num2;
return $res;
}

echo mult(8, 3);


// Outputs 24

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

$_SERVER['HTTP_HOST'] returns the Host header from the current request.


<?php
echo $_SERVER['HTTP_HOST'];
//Outputs "localhost"
?>

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/';
?>

Use the config.php file in your scripts:


<?php
require 'config.php';
echo '<img src="'.$image_path.'header.png" />';
?>

The path to your images is now dynamic. It will change automatically, based on the Host header.

This graphic shows the main elements of $_SERVER.


Forms

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>

Welcome <?php echo $_POST["name"]; ?><br />


Your age: <?php echo $_POST["age"]; ?>

</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.

Start a PHP Session


A session is started using the session_start() function.
Use the PHP global $_SESSION to set session variables.
<?php
// Start the session
session_start();

$_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.

Create cookies using the setcookie() function:


setcookie(name, value, expire, path, domain, secure, httponly);

name: Specifies the cookie's name


value: Specifies the cookie's value
expire: Specifies (in seconds) when the cookie is to expire. The value: time()+86400*30, will set the cookie to expire in 30 days. If this parameter is
omitted or set to 0, the cookie will expire at the end of the session (when the browser closes). Default is 0.
path: Specifies the server path of the cookie. If set to "/", the cookie will be available within the entire domain. If set to "/php/", the cookie will only be
available within the php directory and all sub-directories of php. The default value is the current directory in which the cookie is being set.
domain: Specifies the cookie's domain name. To make the cookie available on all subdomains of example.com, set the domain to "example.com".
secure: 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.
httponly: If set to TRUE, the cookie will be accessible only through the HTTP protocol (the cookie will not be accessible to scripting languages). Using
httponly helps reduce identity theft using XSS attacks. Default is FALSE.
The name parameter is the only one that's required. All of the other parameters are optional.

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"
?>

The setcookie() function must appear BEFORE the <html> tag.


The value of the cookie is automatically encoded when the cookie is sent, and is automatically decoded when it's received. Nevertheless, NEVER store
sensitive information in cookies.

Vous aimerez peut-être aussi