December 6, 2017

Addressing in ipv4 : part 1 (Lesson: 6)

Addressing in ipv4 (part 1)

Overview

In the previous chapter, we looked at the network layer and its involvement in communication. in this chapter, we will look at ipv4 addressing. This is one of the most important concepts in networking and will be critical in your overall success in networking. Understanding this chapter is critical to the rest of your studies. This chapter is divided into two parts so that it can better understood. In the first part, we will look at binary vs decimal, then we will be introduced to subnetting. Then we will finish up by subnetting a few addresses.

Decimal vs binary

We are used to decimals. The number systems used everywhere today is mostly binary. Base of 10.

10^0=1
10^1=10
10^2=100

This is what we use in day to day activities. However, computers are limited to only 2 digits. “1” and “0”, which represent “ON” and “OFF”. The ip addressing system we use is based on this concept. All ipv4 addresses that we use are a decimal representation of the binary form that the computer knows about.

The table below shows the difference between decimal and binary connotations.


You will be seeing the binary table more frequently as we continue in this chapter and others.

How networks are addressed

I believe the most of you have seen an ip address. The ip addressing scheme used contains two parts.
  • The network part – from the left hand side
  • The host part – from the right hand side
In IPv4 addresses, the high-order bits (bits starting from the left side) represent the network address, the low-order bits (bits on the right hand side) represent the host portion. In IPv4 addressing, hosts who have matching high-order bits are said to be in the same network.

December 3, 2017

Windows Ink: How to use Sketch pad

Windows Ink: How to use Sketch pad


Sketch pad is a new feature available in the Windows 10 Anniversary Update, part of the new Windows Ink Workspace feature-set. It allows tablet users to doodle, take notes and more directly on their tablets in a dedicated inking environment, equipped with virtual rulers, pen-types and more. Here's how to use it.


How to open Sketch pad

1. Tap the Pen icon on the taskbar to open the Ink Workspace.


2. Tap the "Sketch pad" feature when Ink Workspace is open. It will be the second block in the list. You'll be greeted with a white canvas.

September 29, 2017

Network layer (Lesson: 5)

Network layer

Overview

In the previous chapter, we looked at the role of the OSI transport layer in communication. In this chapter, we will look at the network layer. We will discuss the addressing used, the functions, and the different network layer protocols, introduce IPv4, understand how packets move in the network and finally give an overview in how we address the network using IPv4. You should be able to understand these concepts as they will be used in the chapter on addressing in IPv4 as well as in subsequent chapters.

Introduction

The network layer defines communication over the network through four basic processes which are addressing, routing, encapsulation and decapsulation. These concepts are vital in understanding routing.

Addressing

You may have sent a letter through the post office, while doing this, you are required to write the address of the recipient on the envelope and most likely your address for reply purposes.

In the same manner, the network layer is responsible for identifying the various devices in the network. However, unlike the postal addresses, addressing in the network layer is logical. This means that addresses are not fixed to the devices and they may change.

The addresses that are used in this layer are for remote delivery, if we use the post office analogy, remote delivery would be sending a letter to another organization. Local delivery – which will be discussed in a later chapter can be likened to sending a note to a colleague who is seated next to you.

Encapsulation

The network layer PDU- protocol Data Unit is the packet. Encapsulation entails adding layer 3 specific information based on the segments from the transport layer. Such information includes headers and trailers. It also divides the segments from the transport layer for remote delivery.

The Echo doesn’t have one killer app, so Amazon is creating Alexa gadgets for every use case

The Echo doesn’t have one killer app, so Amazon is creating Alexa gadgets for every use case

The new smaller, cheaper flagship Amazon Echo Amazon


Amazon on Wednesday announced five new Alexa-powered Echo devices in a dizzying product rollout that comes across as either impressively ambitious or insane and unfocused.

There was an upgrade to the original Echo that is smaller and cheaper at $100; a touchscreen Alexa-powered alarm clock called the Echo Spot for $130; and the Echo Plus with a smart-home hub embedded in it for $150. Then there were tiny Echo Buttons to be used for trivia or games at $20 a pop, and even a $35 Echo Connect gadget to turn your home phone line into an Alexa-powered speaker phone.

Add the existing Echo Dot, Echo Show, Echo Tap and Echo Look to that portfolio, and that gives Amazon nine different Echo gadgets in a little more than two years.

Alexa, what’s up with that strategy?

One theory — well, my theory: Amazon hasn’t found one, single, no-brainer use case for the Echo, so it’s releasing different form factors that can push different behavior.

The Echo Look is designed specifically for fashion advice. The Echo Show and new Echo Spot have touchscreens, making them well suited for video calls and video clips.

There’s also the new Echo Plus, which is built to be a hub to a smart home, making it easier for consumers to use voice commands to control in-home systems like lighting or heating. And the new $100 flagship Echo, which comes with improved sound that may make it a popular choice for those who prioritize music streaming over other Alexa features.

You get the idea.

The beauty of Alexa is that all of these devices come with the same brain that can offer many of the same experiences. But tweaks to the body that sits around the brain — the hardware — can produce different behavior.

Amazon may find enough people that see value in enough different use cases for all of these different devices to succeed. But, more likely, some new Echos will drive use cases that become way more popular than others, helping Amazon to focus more on fewer variations over the long-term.
Source 

September 28, 2017

iOS 11 Update Fixes Bugs, Email Support for Outlook Users

iOS 11 Update Fixes Bugs, Email Support for Outlook Users

Image: iPhone
Image credit: Justin Sullivan/Getty

Having some trouble sending an office email on your iPhone? You downloaded iOS 11, didn’t you. Sure, it’s got some dope upgrades inside, but it’s also the first version of the new operating system, and that means bugs. True to form, a software issue in iOS 11 is preventing Exchange email servers from sending and receiving messages, affecting Outlook, Office 365, and Exchange Server 2016 users. The good news is that Apple’s latest iOS update, 11.0.1 fixes the issue, along with some other unspecified bugs.

Users of the Microsoft-hosted email services were greeted with the message “Cannot Send Mail. The message was rejected by the server” after downloading the first version of the new iOS. Not a great feeling, to be sure. Apple has since addressed the issue in a support page, where it tells users to upgrade to iOS 11.0.1. We generally recommend performing software updates through iTunes and a wired connection, but visiting Settings > General > Software Update will also let you update the OS from your device.

While it probably did fix a few bugs, and Outlook and Exchange users can send emails again, iOS 11 still feels a bit unpolished. App rearranging is a buggy affair, and essential shortcuts in the updated Control Center aren’t as useful as they once were. If you’ve been holding out until the first bug-fixing update, then go right ahead and upgrade your device. Just check to see if it’s compatible first. Don’t want you to get your hopes up.
Source

Apple explains how Face ID learns from its mistakes

Apple explains how Face ID learns from its mistakes
Picture: Apple

Today, Apple published a newly refreshed privacy page. With it came the most new information the company has released on Face ID since the iPhone X was announced. The details come from a new support page and a technical white paper on Face ID security, mentioned during the keynote and currently live on Apple.com. Over the course of six pages, the paper walks through the various privacy and security measures built into the new facial recognition system, including crucial details on how the new system works and how it will hold up under pressure.

The most detailed information comes from the description of how the iPhone X stores faceprints. In broad strokes, Face ID works the same way Touch ID did: the system reads your face (or fingerprint), then creates a partial version to compare against future prints. It’s a purposefully incomplete picture, so even if you could extract the data, it would be impossible to fully reconstruct a person’s face. According to the white paper, there’s also a random element to which information is retained, making it even harder to predict and spoof the system.

Even more interesting is that the initial enrollment is just the beginning of the process. Once you’ve registered your face with the system, Face ID will update its model by occasionally pulling images from successful login photos. The white paper insists those updated face images won’t leave your phone, although they may be stored there for longer than usual. That rolling enrollment explains why Face ID won’t be thrown off if a user grows a beard or buys new glasses. With new images periodically incorporated into the model, the phone’s idea of what you look like can grow incrementally, just like the face itself. Here’s how the white paper puts it:

To improve unlock performance and keep pace with the natural changes of your face and look, Face ID augments its stored mathematical representation over time. Upon successful unlock, Face ID may use the newly calculated mathematical representation — if its quality is sufficient — for a finite number of additional unlocks before that data is discarded. Conversely, if Face ID fails to recognize you, but the match quality is higher than a certain threshold and you immediately follow the failure by entering your passcode, Face ID takes another capture and augments its enrolled Face ID data with the newly calculated mathematical representation. This new Face ID data is discarded after a finite number of unlocks and if you stop matching against it. These augmentation processes allow Face ID to keep up with dramatic changes in your facial hair or makeup use, while minimizing false acceptance.

Apple is also preparing to step in when the system doesn’t work. The white paper goes into detail on a process Apple calls “Face ID Diagnostics,” which lets users reset the enrollment process and walk through it with Apple riding shotgun. If you’re setting up Face ID in diagnostics mode, you’ll be able to send enrolled pictures to Apple for examination and veto any enrolled pictures that might be throwing off the system. Apple insists that process would only take place as part of customer support, basically as one more option for an Apple employee trying to fix a misbehaving phone. Still, the measures go well beyond what’s available for Touch ID, suggesting Apple wants to be prepared for any users that end up on the wrong side of the algorithm.

After Face ID was announced, one of the biggest concerns was the chance that it could be used to unlock a person’s phone against their will. The new document details some of the protections against that kind of unlocking, but it’s not entirely reassuring. Your eyes will have to be open and pointed at the phone for Face ID to trigger the system, but the system is fast enough that instinctively looking at a presented phone might be enough to unlock it. The good news is: you can disable Face ID by pinching the side buttons to put the phone in shutdown mode. After that, it will require a passcode to unlock.

Some measures seem to acknowledge the possibility of an accidental unlock. Face ID is designed to work with Apple Pay, giving users an easy way to transfer money without typing in any passwords. But just looking at your phone won’t be enough to trigger a transaction. Apple Pay requires you to “confirm intent” by double-clicking the sleep button before holding the phone up to the payment terminal. It’s a smart protection to have, but it suggests Face ID is every bit as easy to accidentally trigger as the early demos indicated.

Then there’s the impostor problem. Phil Schiller joked about evil twins (specifically Evil Spock) at the keynote, but Apple clearly takes the problem seriously, recommending against Face ID use if you’re worried about someone with your facial features accessing your phone. The support page puts it this way:

The probability that a random person in the population could look at your iPhone X and unlock it using Face ID is approximately 1 in 1,000,000 (versus 1 in 50,000 for Touch ID).... The statistical probability is different for twins and siblings that look like you and among children under the age of 13, because their distinct facial features may not have fully developed. If you're concerned about this, we recommend using a passcode to authenticate.

In security terms, this is a pretty obscure line of attack. Even if you have a twin, it seems unlikely that an attacker could successfully enlist them in a scheme to unlock your phone. (Let’s call it a Bowfinger attack.) Still, the attack tells us something about Face ID’s limitations. Apple has built protections against printed photos and masks, but if there’s a real face with the same features as yours, it might slide through. That’s the price of a fast and seamless system.

There are still a lot of unanswered questions — most notably how well Face ID will hold up across different races. Apple says it tested the system on a diverse set of a billion different photos, but like a host of other questions, we won’t have a solid answer until the iPhone X goes on sale next month. Facial recognition is a much trickier process than fingerprint scanning, but so far, Apple seems to be treating Face ID like a smarter, faster version of Touch ID.
Source

iOS 11 update killing your iPhone’s battery? Here’s how to fix

iOS 11 update killing your iPhone’s battery? Here’s how to fix

figure: iOS 11 update Killing your iPhone's battery?

iOS 11 is already installed on more than a quarter of existing iOS devices, but it’s not all good news for users who installed it. Slower performance and battery life issues are among the most problematic “features” of iOS 11. And while things will surely get better as Apple further improves iOS 11, some of you will still have to live with worse battery life on your iPhones. iPad doesn’t really count here, not because it has a massive battery, but because it’s the iPhone you take and use everywhere throughout the day.

Here’s what you can do to “fix” your iPhone 7 or iPhone 6s while you wait for Apple’s future improvements.

The radical approach

Buying a new device if yours is experiencing worse and worse battery life is a good idea. I’m not talking about iPhone 7 users here, but iOS fans who are still on older hardware. The older the batteries in these devices get, the worse they’ll perform.

If that’s not what you want to do, then you can always purchase a charging case or an external battery. These will likely fix all your battery problems. As an iPhone 6s owner, I have to say I haven’t noticed significant battery issues since the first iOS 11 betas. That’s because I usually charge the phone via an external battery.

If you have specific iPhone 6s models, you may qualify for a free battery replacement. You have to bring in your iPhone and have an Apple employee see if you are eligible. Or just go in for a battery replacement if your phone is ancient. Batteries only have so many cycles in them, especially smartphone batteries.

Getting into the software

You can use what’s readily available to you, free of charge, although it will consume your time while you test the changes in the Settings app in iOS 11.

Apply the right tweaks, and you may end up improving your battery life on the iPhone without paying a dime. It’s what some of the more experienced iOS users have been doing each year, with each new iOS release.

You can start using Low Power Mode more aggressively to get you through the day. You can lower screen brightness on the phone, and the Auto-Lock time to make sure the screen consumes as little battery juice as possible.

Be sure to check what apps “kill” battery life and consider uninstalling some of them, at least until developers optimize them for iOS 11. You can also disable some of their features, including Background App Refresh and Location Services. Yes, these are useful features that you may use on a regular basis, but if they kill your battery faster then try turning them off.

All these changes can be made via Control Center (Low Power Mode) or the Settings app, and 9to5Mac has a handy visual guide to help you find all the right toggles.

Apple’s smarts

Not too long ago, Tim Cook bragged that the iPhone’s AI and Machine Learning capabilities will let it optimize battery life to meet your needs. That’s one other way that might help you save battery life, but it’s out of your control. Let’s just hope Apple keeps improving it as it fixes iOS 11’s energy needs.
Source

Transport layer (Lesson: 4)

Transport layer

Overview

In the previous chapter, we looked at the application layer and saw that it is the interface between the human network and the data network. In this chapter, we will look at the transport layer and discuss how it aids in communication. At the end of this chapter, you should be able to describe the transport layer as well as its functions.

The transport layer in the OSI model, gets user data from the application layer and prepares it for transport over divergent devices. It also prepares the data for transfer over the network layer. The transport layer is responsible for the delivery of the application data from the source to the destination. In this layer, the PDU in use is the segment.

Purpose of transport layer

The transport layer is responsible for segmentation and control of the various communication streams, it is also responsible for assembly of the communication at the recipients end. The main functions defined at the OSI transport layer include:
  • Tracking of communication between the upper (application layer) and lower (network layer) from the source to the destination. This means that it separates the different applications from the packets it receives from the network layer.
  • Segmentation of application data from the sender. As mentioned earlier, the segment is the transport layer PDU.
  • Reassembly of the various segments into the various applications at the recipients.
  • Identification and differentiation of the different applications.
Segmentation is the splitting of the application data. If we use an analogy of sending a parcel, we can say it is like breaking up pieces of a big machine into small pieces which can then be sent easily as opposed to sending the whole machine. Reassembly would be the bringing together of the machine pieces together. This is necessary since most networks limit the amount of data that can be sent as a single PDU.

September 27, 2017

Bill Gates now uses an Android phone.

Bill Gates now uses an Android phone.


The billionaire Microsoft founder told Fox News Sunday's Chris Wallace he recently switched to a mobile device that runs Google's Android software.

The company officially killed off its Windows Phone line and software in July, due largely to dwindling consumer interest and a lackluster app store. In the first quarter of 2017, Windows Phones' market share was 0.1%, according to a May report from market intelligence firm IDC.

Now, Gates has presumably put his own device aside in favor of another.

While Gates didn't say which phone he uses, he said it has "a lot of Microsoft software."

"So, no iPhone?" Wallace asked.

"No iPhone," Gates said.

Apple and Microsoft have been at odds for years. Its fierce competition goes back decades and was often showcased in TV ads, such as Apple's famous "I'm a Mac" and "I'm a PC" commercials. More recently, Microsoft has gone after Apple customers with products like the Surface Studio intended for designers.

Gates said it's "great" Apple is continuing to do good work, but noted he still uses all Windows-based PCs. In the interview, he praised late Apple founder Steve Jobs, despite their famous rivalry.

"The relationship I had with Steve had every aspect you can imagine. Particularly in the last few years, our friendship -- which had always been there -- was greatly strengthened as he was dealing with cancer," Gates told Wallace. "He and I had a lot in common ... Steve was a genius. Absolutely amazing."

He also credited Jobs with helping to spur competition in the sector.

"The competition in the software and IT space that Steve helped foster, it's phenomenal. And Microsoft's a big part of that. It's been a miraculous industry that he and I got to work in," Gates said.

Separately, Microsoft on Tuesday announced Microsoft Office 2019 will be available in the second half of next year. The big update will have more IT features and server upgrades to improve usability, voice and security, according to the tech giant.

Application layer (Lesson: 3)

Application layer

Overview

As I am sure, most of you use the internet in a number of ways; be it browsing the web, downloading movies, financial transactions, blogging, IM messaging among others. We are most likely oblivious of what it is that makes this communication possible.

In this chapter, we will look at the first layer of the TCP/IP and OSI models, which is the application layer.

In this chapter, you will learn to:

  • Describe the first 3 layers of the OSI model
  • Describe some of the application layer applications

Introduction

The application layer is the 7th layer in the OSI model. When communicating, messages move from the application layer, down the other layers up to the physical layer, after transmission, the information moves from the physical layer up the model to the application layer again from where it is usable.

The application layer in the TCP/IP model defines 3 layers in the OSI model. These are; the application, presentation and session layers.

Presentation Layer

The presentation layer is the 6th layer in the OSI model. It defines three main functions when it comes to communication over the network.

  • Data from the application layer is converted and coded into a form that can be understood by the recipient’s device.
  • Since application data may be uncompressed, the presentation layer compresses the data and this is in a manner that can be interpreted and decompressed by the destination device.
  • To ensure security of the data which may be transmitted over insecure networks, the presentation layer also encrypts the data.

In this course you are not expected to fully understand the functionality at this layer, however, you are supposed to be familiar with the processes that are involved as listed above.

September 26, 2017

TCP/IP and the OSI Model (Lesson: 2)

TCP/IP and the OSI Model

Overview

In the previous chapter we were introduced to computer networks and we got to know their importance in everyday lives. In this chapter, we will look at the layered models that are used in communication over networks.

We will discuss the TCP/ip model and the OSI model to better understand how communication works. This will lead into detailed discussion on each of the layers so as to better understand them.

Use of layered models

To better understand the various protocols and how they work with each other, we use layered models. A layered model shows how the protocols work at each layer as well as how the layers interact with the layers either above them or below them. The layered models that are used in modern computer networks are two; the OSI model (Open Systems Interconnection) and the TCP/IP model (Transmission Control Protocol/ Internet Protocol)

There are several benefits that to using the OSI and TCP/IP models in explaining how network protocols work and these include the following.

  • Each layer in a model defines different protocols, therefore by using a layered model, network engineers can be able to define and design protocols which conform to the specific layer.
  • Competitions between different vendors is increased, this is because the models define standards and therefore product superiority is not based on the use of certain protocols since all products support them.
  • The layered model is useful since it allows for independence between other layers. This means that if a change in technology or capabilities is made in one layer, it will not affect another layer either above it or below it.
  • Since the layered model is an open standard, it provides for conformity and interoperability between different networking devices.

As mentioned earlier, the two models that we will be discussing in this course are the OSI and the TCP/IP models. However, these two models are different.

September 25, 2017

The World of Networks (Lesson: 1)

The World of Networks

Introduction

Communication has evolved greatly. Traditional communication methods such as mail have been overtaken by more sophisticated forms. Electronic Communication methods offer higher speeds; more efficiency, reliability, integrity, security; scale across larger geographical areas and require less resources to use. Tools and services such as e-mail, blogs, podcasts, instant messaging, and social networks among other multimedia methods have changed the way we communicate to a great extent.

In this chapter, we give an overview of the world of networks: we will discuss the following:

  1. The role of networks in our lives
  2. Explain the qualities and elements of a network
  3. Define key terms and diagrams used in this course
  4. Explain what a converged network is
  5. Give a brief history of computer networks

This chapter is crucial since some of the concepts learned in it will be useful in understanding the rest of the course.

The role of networks.

The need to communicate is human nature. Communication has evolved over the years, from carvings on rocks to more complex forms. The diagram below is an apt description of this evolution.
Figure: The evolution of communication
Figure: The evolution of communication

Modern communication methods are as a result of the evolution of computer networks. Since the first e-mail was sent back in 1965, communication has come a long way.

We are no longer restricted with face to face communication. And with the internet the world has become more interconnected than ever before.

September 24, 2017

Core PHP: Reading a File (8.6)

Reading a File


At the end of the output in the previous example, we would have a comma, as we print it after each element of the array.
The following code lets us avoid printing that final comma.
$read = file('names.txt');
$count = count($read);
$i = 1;
foreach ($read as $line) {
  echo $line;
  if($i < $count) {
    echo ', ';
  }
  $i++;
}

The $count variable uses the count function to obtain the number of elements in the $read array.
Then, in the foreach loop, after each line prints, we determine whether the current line is less than the total number of lines, and print a comma if it is.
This avoids printing that final comma, as for the last line, $i is equal to $count.

Core PHP: Reading a File (8.5)

Reading a File


The file() function reads the entire file into an array. Each element within the array corresponds to a line in the file:
$read = file('names.txt');
foreach ($read as $line) {
  echo $line .", ";
}

This prints all of the lines in the file, and separates them with commas.
We used the foreach loop, because the $read variable is an array.

Core PHP: Appending to a File (8.4)

Appending to a File


Let's create an example of a form that adds filled-in data to a file.
<?php
if(isset($_POST['text'])) {
  $name = $_POST['text'];
  $handle = fopen('names.txt', 'a');
  fwrite($handle, $name."\n");
  fclose($handle);
}
?>
<form method="post">
  Name: <input type="text" name="text" />
  <input type="submit" name="submit" />
</form>

Now, each time a name is entered and submitted, it's added to the "names.txt" file, along with a new line.

The isset() function determined whether the form had been submitted, as well as whether the text contained a value.
We did not specify an action attribute for the form, so it will submit to itself.

Core PHP: Appending to a File (8.3)

Appending to a File


If you want to append content to a file, you need to open the file in append mode.

For example:
$myFile = "test.txt";
$fh = fopen($myFile, 'a');
fwrite($fh, "Some text");
fclose($fh);

When appending to a file using the 'a' mode, the file pointer is placed at the end of the file, ensuring that all new data is added at the end of the file.

Core PHP: Writing to a File (8.2)

fclose()


The fclose() function closes an open file and returns TRUE on success or FALSE on failure.
It's a good practice to close all files after you have finished working with them.

Core PHP: Writing to a File (8.1)

Write to File


When writing to a file, use the fwrite() function.
The first parameter of fwrite() is the file to write to; the second parameter is the string to be written.

The example below writes a couple of names into a new file called "names.txt".
<?php
$myfile = fopen("names.txt", "w");

$txt = "John\n";
fwrite($myfile, $txt);
$txt = "David\n";
fwrite($myfile, $txt);

fclose($myfile);

/* File contains:
John
David
*/
?>

Notice that we wrote to the file "names.txt" twice, and then we used the fclose() function to close the file.
The \n symbol is used when writing new lines.

Core PHP: Manipulating Files (8.0)

Manipulating Files


PHP offers a number of functions to use when creating, reading, uploading, and editing files.
The fopen() function creates or opens a file. If you use fopen() with a file that does not exist, the file will be created, given that the file has been opened for writing (w) or appending (a).

Use one of the following modes to open the file.
r: Opens file for read only.
w: Opens file for write only. Erases the contents of the file or creates a new file if it doesn't exist.
a: Opens file for write only.
x: Creates new file for write only.
r+: Opens file for read/write.
w+: Opens file for read/write. Erases the contents of the file or creates a new file if it doesn't exist.
a+: Opens file for read/write. Creates a new file if the file doesn't exist
x+: Creates new file for read/write.

The example below creates a new file, "file.txt", which will be created in the same directory that houses the PHP code.
$myfile = fopen("file.txt", "w");

September 19, 2017

Core PHP: $_COOKIE (7.10)

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.

Core PHP: $_COOKIE (7.9)

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.

Core PHP: $_SESSION (7.8)

Session Variables


Another page can be created that can access the session variables we set in the previous page:
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
echo "Your name is " . $_SESSION['name'];
// Outputs "Your name is John"
?>
</body>
</html>

Your session variables remain available in the $_SESSION superglobal until you close your session.
All global session variables can be removed manually by using session_unset(). You can also destroy the session with session_destroy().

Core PHP: $_SESSION (7.7)

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.

Core PHP: GET and POST (7.6)

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!

Core PHP: GET and POST (7.5)

POST

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

Core PHP: PHP Forms (7.4)

Forms


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 super global 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!

Core PHP: PHP Forms (7.3)

Forms

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

Core PHP: PHP Forms (7.2)

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>

Result:
figure: PHP forms
Figure: PHP forms

August 13, 2017

Core PHP: $_SERVER Variables: Host Name (7.1)

$_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.
Figure: the main elements of $_SERVER
Figure: the main elements of $_SERVER

Core PHP: $_SERVER Variables: Script Name (7.0)

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

Our example was written in a file called somefile.php, which is located in the root of the web server.

Core PHP: The Return Statement (6.4)

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

Leaving out the return results in a NULL value being returned.
A function cannot return multiple values, but returning an array will produce similar results.

Core PHP: Function Parameters (6.3)

Default Arguments


Default arguments can be defined for the function arguments.
In the example below, we're calling the function setCounter(). There are no arguments, so it will take on the default values that have been defined.
function setCounter($num=10) {
   echo "Counter is ".$num;
}
setCounter(42);  //Counter is 42
setCounter();  //Counter is 10

When using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected.

Core PHP: Function Parameters (6.2)

Function Parameters


Information can be passed to functions through arguments, which are like variables.
Arguments are specified after the function name, and within the parentheses.
Here, our function takes a number, multiplies it by two, and prints the result:
function multiplyByTwo($number) {
  $answer = $number * 2;
  echo $answer;
}
multiplyByTwo(3);
//Outputs 6

You can add as many arguments as you want, as long as they are separated with commas.
function multiply($num1, $num2) {
  echo $num1 * $num2;
}
multiply(3, 6);
//Outputs 18

When you define a function, the variables that represent the values that will be passed to it for processing are called parameters. However, when you use a function, the value you pass to it is called an argument.

Core PHP: User-Defined Functions (6.1)

Functions


In the example below, we create the function sayHello(). The opening curly brace ({) indicates that this is the beginning of the function code, while the closing curly brace (}) indicates that this is the end.
To call the function, just write its name:
function sayHello() {
  echo "Hello!";
}

sayHello(); //call the function

//Outputs "Hello!"

Core PHP: User-Defined Functions (6.0)

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.

July 26, 2017

Core PHP: Include & Require (5.19)

include vs require


The require statement is identical to include, the exception being that, upon failure, it produces a fatal error.
When a file is included using the include statement, but PHP is unable to find it, the script continues to execute.
In the case of require, the script will cease execution and produce an error.

Use require when the file is required for the application to run.
Use include when the file is not required. The application should continue, even when the file is not found.

Core PHP: Include & Require (5.18)

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>

Result:
Example: include


Files are included based on the file path.
You can use an absolute or a relative path to specify which file should be included.

Core PHP: Include & Require (5.17)

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>

Core PHP: The continue Statement (5.16)

The continue Statement


When used within a looping structure, the continue statement allows for skipping over what remains of the current loop iteration. It then continues the execution at the condition evaluation and moves on to the beginning of the next iteration.

The following example skips the even numbers in the for loop:
for ($i=0; $i<10; $i++) {
  if ($i%2==0) {
    continue;
  }
  echo $i . ' ';
}

//Output: 1 3 5 7 9

You can use the continue statement with all looping structures.

Core PHP: The break Statement (5.15)

The break Statement


As discussed in the previous lesson, the break statement is used to break out of the switch when a case is matched.
If the break is absent, the code keeps running. For example:

$x=1;
switch ($x) {
  case 1:
    echo "One";
  case 2:
    echo "Two";
  case 3:
    echo "Three";
  default:
    echo "No match";
}

//Outputs "OneTwoThreeNo match"

Break can also be used to halt the execution of for, foreach, while, do-while structures.
The break statement ends the current for, foreach, while, do-while or switch and continues to run the program on the line coming up after the loop.
A break statement in the outer part of a program (e.g., not in a control loop) will stop the script.

Core PHP: The Switch Statement (5.14)

Switch


Failing to specify the break statement causes PHP to continue to executing the statements that follow the case, until it finds a break. You can use this behavior if you need to arrive at the same output for more than one case.
$day = 'Wed';

switch ($day) {
  case 'Mon':
    echo 'First day of the week';
    break;
  case 'Tue':
  case 'Wed':
  case 'Thu':
    echo 'Working day';
    break;
  case 'Fri':
    echo 'Friday!';
    break;
  default:
    echo 'Weekend!';
}

//Outputs "Working day"

The example above will have the same output if $day equals 'Tue', 'Wed', or 'Thu'.

Core PHP: The Switch Statement (5.13)

default


The default statement is used if no match is found.

$x=5;
switch ($x) {
  case 1:
    echo "One";
    break;
  case 2:
    echo "Two";
    break;
  default:
    echo "No match";
}

//Outputs "No match"

The default statement is optional, so it can be omitted.

Core PHP: The Switch Statement (5.12)

Switch


Consider the following example, which displays the appropriate message for each day.
$today = 'Tue';

switch ($today) {
  case "Mon":
    echo "Today is Monday.";
    break;
  case "Tue":
    echo "Today is Tuesday.";
    break;
  case "Wed":
    echo "Today is Wednesday.";
    break;
  case "Thu":
    echo "Today is Thursday.";
    break;
  case "Fri":
     echo "Today is Friday.";
     break;
  case "Sat":
     echo "Today is Saturday.";
     break;
  case "Sun":
     echo "Today is Sunday.";
     break;
  default:
     echo "Invalid day.";
}
//Outputs "Today is Tuesday."

The break keyword that follows each case is used to keep the code from automatically running into the next case. If you forget the break; statement, PHP will automatically continue through the next case statements, even when the case doesn't match.

Core PHP: The Switch Statement (5.11)

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.

July 25, 2017

Core PHP: The foreach Loop (5.10)

The foreach Loop


The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

There are two syntaxes:

foreach (array as $value) {
  code to be executed;
}
//or
foreach (array as $key => $value) {
   code to be executed;
}

The first form loops over the array. On each iteration, the value of the current element is assigned to $value, and the array pointer is moved by one, until it reaches the last array element.
The second form will additionally assign the current element's key to the $key variable on each iteration.

The following example demonstrates a loop that outputs the values of the $names array.

$names = array("John", "David", "Amy");
foreach ($names as $name) {
   echo $name.'<br />';
}

// John
// David
// Amy

Core PHP: The For Loop (5.9)

The for Loop


The example below displays the numbers from 0 to 5:
for ($a = 0; $a < 6; $a++) {
   echo "Value of a : ". $a . "<br />";
}

Result:
Example: The for loop


The for loop in the example above first sets the variable $a to 0, then checks for the condition ($a < 6). If the condition is true, it runs the code. After that, it increments $a ($a++).

Core PHP: The For Loop (5.8)

The for Loop


The for loop is used when you know in advance how many times the script should run.
for (init; test; increment) {
   code to be executed;
}

Parameters:
init: Initialize the loop counter value
test: Evaluates each time the loop is iterated, continuing if evaluates to true, and ending if it evaluates to false
increment: Increases the loop counter value
Each of the parameter expressions can be empty or contain multiple expressions that are separated with commas.
In the for statement, the parameters are separated with semicolons.

Core PHP: The Do While Loop (5.7)

The do...while Loop


The example below will write some output, and then increment the variable $i by one. Then the condition is checked, and the loop continues to run, as long as $i is less than or equal to 7.
$i = 5;
do {
   echo "The number is " . $i . "<br/>";
   $i++;
} while($i <= 7);

//Output
//The number is 5
//The number is 6
//The number is 7

Note that in a do while loop, the condition is tested AFTER executing the statements within the loop. This means that the do while loop would execute its statements at least once, even if the condition is false the first time.

Core PHP: The Do While Loop (5.6)

The do...while Loop


The do...while loop will always execute the block of code once, check the condition, and repeat the loop as long as the specified condition is true.

Syntax:
do {
  code to be executed;
} while (condition is true);

Regardless of whether the condition is true or false, the code will be executed at least once, which could be needed in some situations.

July 24, 2017

Core PHP: The while Loop (5.5)

The while Loop

The example below first sets a variable $i to one ($i = 1). Then, the while loop runs as long as $i is less than seven ($i < 7). $i will increase by one each time the loop runs ($i++):
$i = 1;
while ($i < 7) {
  echo "The value is $i <br />";
  $i++;
}

This produces the following result:
Example: Loop

Core PHP: The while Loop (5.4)

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

If the condition never becomes false, the statement will continue to execute indefinitely.

July 15, 2017

Core PHP: The Elseif Statement (5.3)

The Elseif Statement

For example:
<?php
$age = 21;

if ($age<=13) {
   echo "Child.";
} elseif ($age>13 && $age<19) {
   echo "Teenager";
} else {
   echo "Adult";
}

//Outputs "Adult"
?>

We used the logical AND (&&) operator to combine the two conditions and check to determine whether $age is between 13 and 19.

Core PHP: The Elseif Statement (5.2)

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

You can add as many elseif statements as you want. Just note, that the elseif statement must begin with an if statement.

Core PHP: The If Else Statement (5.1)

If Else

The example below will output the greatest number of the two.
<?php
$x = 10;
$y = 20;
if ($x >= $y) {
   echo $x;
} else {
   echo $y;
}

// Outputs "20"
?>

Core PHP: The If Else Statement (5.0)

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

You can also use the if statement without the else statement, if you do not need to do anything, in case the condition is false.

July 11, 2017

Core PHP: Multi-Dimensional Arrays (4.5)

Multi-Dimensional Arrays

Let's create a two-dimensional array that contains 3 arrays:
$people = array(
   'online'=>array('David', 'Amy'),
   'offline'=>array('John', 'Rob', 'Jack'),
   'away'=>array('Arthur', 'Daniel')
);

Now the two-dimensional $people array contains 3 arrays, and it has two indices: row and column.
To access the elements of the $people array, we must point to the two indices.
echo $people['online'][0]; //Outputs "David"

echo $people['away'][1]; //Outputs "Daniel"

The arrays in the multi-dimensional array can be both numeric and associative.

Core PHP: Multi-Dimensional Arrays (4.4)

Multi-Dimensional Arrays

A multi-dimensional array contains one or more arrays.

The dimension of an array indicates the number of indices you would need to select an element.
- For a two-dimensional array, you need two indices to select an element
- For a three-dimensional array, you need three indices to select an element
Arrays more than three levels deep are difficult to manage.

Core PHP: Associative Arrays (4.3)

Associative Arrays

Use the named keys to access the array's members.
$people = array("David"=>"27", "Amy"=>"21", "John"=>"42");

echo $people['Amy']; // Outputs 21"

Core PHP: Associative Arrays (4.2)

Associative Arrays

Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
$people = array("David"=>"27", "Amy"=>"21", "John"=>"42");
// or
$people['David'] = "27";
$people['Amy'] = "21";
$people['John'] = "42";

In the first example, note the use of the => signs in assigning values to the named keys.

Core PHP: Numeric Arrays (4.1)

Numeric Arrays

You can have integers, strings, and other data types together in one array.
Example:
<?php
$myArray[0] = "John";
$myArray[1] = "<strong>PHP</strong>";
$myArray[2] = 21;

echo "$myArray[0] is $myArray[2] and knows $myArray[1]";

// Outputs "John is 21 and knows PHP"
?>

Core PHP: Numeric Arrays (4.0)

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"

Remember that the first element in an array has the index of 0, not 1.

Core PHP: Logical Operators (3.6)

Logical Operators

Logical operators are used to combine conditional statements.

PHP: Logical Operators

Core PHP: Comparison Operators (3.5)

Comparison Operators

Additional comparison operators:
PHP: Comparison Operators

Core PHP: Comparison Operators (3.4)

Comparison Operators

Comparison operators compare two values (numbers or strings).
Comparison operators are used inside conditional statements, and evaluate to either TRUE or FALSE.

PHP: Comparison Operators

Core PHP: Assignment Operators (3.3)

Assignment Operators

Assignment operators work with numeric values 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.
PHP: Assignment Operators


Example:
<?php
 $x = 50;
 $x += 100;
 echo $x;

 // Outputs: 150
?> 

Core PHP: Increment & Decrement (3.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

Core PHP: Modulus (3.1)

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

If you use floating point numbers with the modulus operator, they will be converted to integers before the operation.

Core PHP: Arithmetic Operators (3.0)

Operators

Operators carry out operations on variables and values.

Example: operand and operator

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

Core PHP: Variable Variables (2.6)

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

$$a is a variable that is using the value of another variable, $a, as its name. The value of $a is equal to "hello". The resulting variable is $hello, which holds the value "Hi!".

July 10, 2017

Core PHP: Variable Scope (2.5)

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

Core PHP: Variables Scope (2.4)

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, and can only be accessed outside of a function.
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.
Functions will be discussed in the coming lessons.

Core PHP: Data Types (2.3)

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

PHP automatically converts each variable to the correct data type, according to its value. This is why the variable $str is treated as a number in the addition.

Core PHP: Data Types (2.2)

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

Core PHP: Constants (2.1)

Constants

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 Buzz Learners!");
  echo MSG;

   // Outputs "Hi Buzz Learners!"
?>


The example below creates a constant with a case-insensitive name:
<?php
  define("MSG", " Hi Buzz Learners!", true);
  echo msg;

  // Outputs "Hi Buzz Learners!"
?>

No dollar sign ($) is necessary before the constant name.

Core PHP: Variables (2.0)

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.