An open API service indexing awesome lists of open source software.

https://github.com/makstyle119/php

PHP from beginner to advanced
https://github.com/makstyle119/php

begginer-friendly makstyle119 php tutorial

Last synced: 8 months ago
JSON representation

PHP from beginner to advanced

Awesome Lists containing this project

README

          

# PHP

this is my journey to learn and understand PHP

## Folder Structure:

```
├── 📂 php-revision
├── 📂 src
|- 001_output.php
|- 002_variables.php
|- 003_arrays.php
|- 004_conditionals.php
|- 005_loops.php
|- 006_functions.php
|- 007_array_functions.php
|- 008_string_functions.php
|- 009_super_globals.php
|- 010_get_post.php
|- 011_sanitizing_inputs.php
|- 012_cookies.php
|- 013_sessions.php
|- 014_file_handling.php
|- 015_file_upload.php
|- 016_exception.php
|- 017_oop.php
docker-compose.yml
Dockerfile
README.md
```

## Code Explaining

- 000/folder-structure
```
Nothing much just basic folder structure
```

- php-revision/src/001_output.php
- `echo` most common thing use for printing (specially for debugging) - with `echo` you can print multiple values using as comma separated values - only string and numbers
- `print` same as `echo` but only print single value
- `print_r()` use a lot with arrays
- `var_dump()` against use a lot with array but can use with anything - return type as well
- `var_export()` similar with `var_dump()` but not as efficient as `var_dump()` is
- `= 'Some Text' ?>` single line only - same as `echo`
```




01_output





='Post Two' ?>

```

- php-revision/src/002_variables.php
- `Variables`
- `String` - A string is a series of characters surrounded by quotes
- `Integer` - Whole numbers
- `Float` - Decimal numbers
- `Boolean` - true or false
- `Array` - An array is a special variable, which can hold more than one value
- `Object` - A class
- `NULL` - Empty variable
- `Resource` - A special variable that holds a resource
- `Data Types`
- `Variables` must be prefixed with $
- `Variables` must start with a letter or the underscore character
- `variables` can't start with a number
- `Variables` can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
- `Variables` are case-sensitive ($name and $NAME are two different variables)
```
" . $name . ' is ' . $age . ' year old. and have ' . $has_on_hand . ' money'; // this is how you can do contact in php
echo "
$name is $age year old. and have $has_on_hand money
"; // this is another way

$x = '5' + '5'; // php will still consider it as int;
var_dump($x);

echo "\t" . 10 - 5 . "\t";
echo 10 * 5 . "\t";
echo 10 / 5 . "\t";
echo 10 % 5 . "\t";

echo "
";

// constant
define('HOST', 'localhost'); // never change

echo HOST;
```

- php-revision/src/003_arrays.php
- `Arrays`
- `Simple Array` - anything between two large brackets with a comma to separate them is a simple array.
- `Associate Array` - in associate array we will set key and value just like object in js.
- `Multi Dimension Array` - here we will have array inside another array
```
'#000',
'white' => '#fff'
];

echo $color['black'];

// Multi Dimension Array
$people = [
[
'first_name' => 'Moiz',
'last_name' => 'Ali',
'email' => 'some.email@cool.com'
],
[
'first_name' => 'Maria',
'last_name' => 'Khan',
'email' => 'some.email2@cool.com'
]
];

echo $people[1]['email'];

// convert an array into json
var_dump(json_encode($people));
```

- php-revision/src/04_conditionals.php
- If else
- `if (condition)` - check if the statement is true
- `elseif (condition)` - same as if check for second or more condition - optional
- `else` - this will run if no condition match - optional
- Ternary operator
- `?` this is if statement
- `-` this is else
- `?` and `-` should run together
- `&&` this is and operator
- `??` this will check for first value and if not exist then go for second
- Switch cases
- `switch(condition)` - switch case are same as if else here you start with passing the parameter then check if on every case
- `case value` - check if provided value is same as parameter
- `break` - to break the switch case
- `default` - it will run if no other case match - optional
```
Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
=== Identical to
!= Not equal to
!== Not identical to
*/

/* ---------- If & If-Else Statements --------- */

/*
** If Statement Syntax
if (condition) {
// code to be executed if condition is true
}
*/

$age = 20;

if ($age > 18)
{
echo 'you are old enough' + "\n";
}
elseif ($age < 100) // elseif is adding a second or more conditions
{
echo 'too much old' + "\n";
}
else // else is a default which will run if no condition match
{
echo 'you are not old enough' + "\n";
}

$sports = ['Cricket'];

if (empty($sports)) // empty is a built in function to check is array is empty or not
{
echo 'no sports exist' + "\n";
}

/* -------- Ternary Operator -------- */
/*
The ternary operator is a shorthand if statement.
Ternary Syntax:
condition ? true : false;
*/

echo empty($sports) ? 'no sports exist' : $sports[0] + "\n";

echo empty($sports) && 'no sports exist' + "\n";

$first_post = $sports[0] ?? null; // ?? will check for first value if not exist add second value

/* -------- Switch Statements ------- */

$fav_color = 'red';

switch($fav_color) // switch case are same as if else here you start with passing the parameter then check if on every case
{
case 'red': // check if provided value is same as parameter
echo 'Your Favorite color is red';
break; // to break the switch case
case 'blue':
echo 'Your Favorite color is blue';
break;
default: // it will run if no other case match
echo 'I don\'t recognized your favorite color';
break;
}

?>
```

- php-revision/src/005_loop.php
- `for loop`
- `for($a = 0; $a <= 10; $a++)` - for loop have 3 parts - 1. initialize the variable - 2. add the condition (how much you want to run this loop) - 3. increment or decrement the value
- `while Loop`
- `while ($b <= 0)` - same as for loop you put your condition and it will run until condition become true
- `$b -= 1;` - here we will pu increment or decrement
- `do while loop`
- `do {}` - in do while loop we perform the task first then check condition - in other words if you want to run condition at least one time use this
- `$c++;` - increment or decrement
- `while ($c < 0);` - checking the condition here
- `foreach loop`
- `foreach ($posts as $index => $post)` - we use this for array - you can use above loops for arrays as well it just it more common to use - we can get index and individual value from the array using foreach
```
" . "
";

for($a = 0; $a <= 10; $a++) // for loop have 3 parts - 1) initialize the variable - 2) add the condition (how much you want to run this loop) - 3) increment or decrement the value
{
echo $a . "
"; // do whatever you like here
}

echo "
" . "for loop ends here" . "
";

/* ------------ While Loop ------------ */

/*
** While Loop Syntax
while (condition) {
// code to be executed
}
*/

echo "
" . "while loop start here" . "
" . "
";

$b = 15;
while ($b <= 0) // same as for loop you put your condition and it will run until condition become true
{
echo $b . "
";
$b -= 1; // here we will pu increment or decrement
}

echo "
" . "while loop ends here" . "
";

/* ---------- Do While Loop --------- */

/*
** Do While Loop Syntax
do {
// code to be executed
} while (condition);

do...while loop will always execute the block of code once, even if the condition is false.
*/

echo "
" . "do while loop start here" . "
" . "
";

$c = 0;

do { // in do while loop we perform the task first then check condition - in other words if you want to run condition at least one time use this
echo $c . "
";
$c++; // increment or decrement
} while ($c < 0); // checking the condition here

echo "
" . "do while loop ends here" . "
";

/* ---------- Foreach Loop ---------- */

/*
** Foreach Loop Syntax
foreach ($array as $value) {
// code to be executed
}
*/

echo "
" . "foreach loop start here" . "
" . "
";

$posts = ['first post', 'second post', 'third post'];

foreach ($posts as $index => $post) // we use this for array - you can use above loops for arrays as well it just it more common to use - we can get index and individual value from the array using foreach
{
echo "(" . $index . ")" . " " .$post . "
";
}

echo "
" . "foreach loop ends here" . "
";

?>
```

- php-revision/src/006_functions.php
- `function` - Functions are reusable blocks of code that we can call to perform a specific task. We can pass values into functions to change their behavior. Functions have their own local scope as opposed to global scope
- `normal function`
- `function register_user($email)` - to create a function you need to use function key word and then function name and the open brackets - you can use argument in the function - argument can be use to get user input or value which can help function functionality
- `echo $name . ' registered with ' . $email;` // function have strict scope you can't use anything outside or don't use any variable which you declare inside the function outside
- `global $name;` // using global keyword we can add global scope variable into local scope
- `register_user('makstyle119@gmail.com');` // function doesn't run by their own you have to run the manually by calling their name
- `$sum_value = sum(2, 3);` // function can run by them self or can be assign to a variable
- `anonymous function`
- `$subtraction = function($a, $b) {` // when you assign function directly to a variable like this - this is called anonymous function
- `arrow function`
- `$multiplication = fn($a, $b) => $a * $b;` // this is how you can create a arrow function use fn to create a function and if it's a single line function you don't need return or brackets
```
" . "
";

$name = 'MAK';

function register_user($email) // to create a function you need to use function key word and then function name and the open brackets - you can use argument in the function - argument can be use to get user input or value which can help function functionality
{
global $name; // using global keyword we can add global scope variable into local scope
echo $name . ' registered with ' . $email . "
"; // function have strict scope you can't use anything outside or don't use any variable which you declare inside the function outside
}

register_user('makstyle119@gmail.com'); // function doesn't run by their own you have to run the manually by calling their name

function sum($a, $b = 4) {
return $a + $b; // function can return and can be void - your argument can have a default value so you if you don't pass the parameter while calling the function default value will be use
}

$sum_value = sum(2, 3); // function can run by them self or can be assign to a variable

echo $sum_value . "
";

echo "
" . "normal function ends here" . "
";

echo "
" . "anonymous function start here" . "
";

$subtraction = function($a, $b) // when you assign function directly to a variable like this - this is called anonymous function
{
return $a - $b;
};

echo $subtraction(3, 1) . "
";

echo "
" . "anonymous function ends here" . "
";

echo "
" . "arrow function start here" . "
";

$multiplication = fn($a, $b) => $a * $b . "
"; // this is how you can create a arrow function use fn to create a function and if it's a single line function you don't need return or brackets

echo $multiplication(3, 4) . "
";

echo "
" . "arrow function ends here" . "
";

?>

```

- php-revision/src/007_array_functions.php
- `count($fruits);` // count array length
- `var_dump(in_array('apple', $fruits));` // search in array
- `$fruits[] = 'grape';` // add in the last
- `array_push($fruits, 'blueberry', 'strawberry');` // add in the last
- `array_unshift($fruits, 'mango');` // add in the first
- `array_pop($fruits);` // remove last
- `array_shift($fruits);` // remove first
- `unset($fruits[2]);` // remove by index and also the index
- `$chunked_array` = array_chunk($fruits, 2); // second argument is the n
- `$arr3 = array_merge($arr1, $arr2);` // merge two arrays
- `$arr4 = [...$arr1, ...$arr2];` // merge two arrays
- `$combineColorAndFruitArray = array_combine($color, $fruit);` // combine two arrays
- `$keys = array_keys($combineColorAndFruitArray);` // return keys of an array
- `$flipped = array_flip($combineColorAndFruitArray);` // flip the array
- `$numbersTillTwenty = range(0, 20);` // make range in form of array
- `$numbersTillTwentyWithString = array_map(function($number) {`
`return "Number $number";`
`}, $numbersTillTwenty);` // run a map in the array
- `$lessThenTen = array_filter($numbersTillTwenty, fn($number) => $number < 10);` // run a map and return where condition match
- `$sum = array_reduce($numbersTillTwenty, fn($carry, $number) => $carry + $number);` // run a reducer in a array
```
" . "
";

echo count($fruits); // count array length

echo "
" . "
" . "================================================== count end ==================================================";
echo "
" . "
" . "================================================== search start ==================================================" . "
" . "
";

var_dump(in_array('apple', $fruits)); // search in array

echo "
" . "
" . "================================================== search end ==================================================";
echo "
" . "
" . "================================================== add in the array start ==================================================" . "
" . "
";

$fruits[] = 'grape'; // add in the last

print_r($fruits);

echo "
" . "
" . "================================================== add in the array end ==================================================";
echo "
" . "
" . "================================================== array_push start ==================================================" . "
" . "
";

array_push($fruits, 'blueberry', 'strawberry'); // add in the last

print_r($fruits);

echo "
" . "
" . "================================================== array_push end ==================================================";
echo "
" . "
" . "================================================== array_unshift start ==================================================" . "
" . "
";

array_unshift($fruits, 'mango'); // add in the first

print_r($fruits);

echo "
" . "
" . "================================================== array_unshift end ==================================================";
echo "
" . "
" . "================================================== array_pop start ==================================================" . "
" . "
";

array_pop($fruits); // remove last

print_r($fruits);

echo "
" . "
" . "================================================== array_pop end ==================================================";
echo "
" . "
" . "================================================== array_shift start ==================================================" . "
" . "
";

array_shift($fruits); // remove first

print_r($fruits);

echo "
" . "
" . "================================================== array_shift end ==================================================";
echo "
" . "
" . "================================================== unset start ==================================================" . "
" . "
";

unset($fruits[2]); // remove by index and also the index

print_r($fruits);

echo "
" . "
" . "================================================== unset end ==================================================";
echo "
" . "
" . "================================================== split the array into n number - start ==================================================" . "
" . "
";

$chunked_array = array_chunk($fruits, 2); // second argument is the n

print_r($chunked_array);

echo "
" . "
" . "================================================== split the array into n number - end ==================================================";
echo "
" . "
" . "================================================== array merge start ==================================================" . "
" . "
";

$arr1 = [1, 2, 3];
$arr2 = [4, 5, 6];

$arr3 = array_merge($arr1, $arr2); // merge two arrays

print_r($arr3);

echo "
" . "
" . "================================================== array merge end ==================================================";
echo "
" . "
" . "================================================== split operator start ==================================================" . "
" . "
";

$arr1 = [1, 2, 3];
$arr2 = [4, 5, 6];

$arr4 = [...$arr1, ...$arr2]; // merge two arrays

print_r($arr4);

echo "
" . "
" . "================================================== split operator end ==================================================";
echo "
" . "
" . "================================================== combine two array with key value pair - start ==================================================" . "
" . "
";

$color = ['green', 'red', 'yellow'];
$fruit = ['avocado', 'apple', 'banana'];

$combineColorAndFruitArray = array_combine($color, $fruit); // combine two arrays

print_r($combineColorAndFruitArray);

echo "
" . "
" . "================================================== combine two array with key value pair - end ==================================================";
echo "
" . "
" . "================================================== get only keys of an array - start ==================================================" . "
" . "
";

$keys = array_keys($combineColorAndFruitArray); // return keys of an array

print_r($keys);

echo "
" . "
" . "================================================== get only keys of an array - end ==================================================";
echo "
" . "
" . "================================================== flip the array - value become key and key become value - start ==================================================" . "
" . "
";

$flipped = array_flip($combineColorAndFruitArray); // flip the array

print_r($flipped);

echo "
" . "
" . "================================================== flip the array - value become key and key become value - end ==================================================";
echo "
" . "
" . "================================================== create a range from n to m - start ==================================================" . "
" . "
";

$numbersTillTwenty = range(0, 20); // make range in form of array

print_r($numbersTillTwenty);

echo "
" . "
" . "================================================== create a range from n to m - end ==================================================";
echo "
" . "
" . "================================================== create a range with adding more data in return - start ==================================================" . "
" . "
";

$numbersTillTwentyWithString = array_map(function($number) {
return "Number $number";
}, $numbersTillTwenty); // run a map in the array

print_r($numbersTillTwentyWithString);

echo "
" . "
" . "================================================== create a range with adding more data in return - end ==================================================";
echo "
" . "
" . "================================================== filter start ==================================================" . "
" . "
";

$lessThenTen = array_filter($numbersTillTwenty, fn($number) => $number < 10); // run a map and return where condition match

print_r($lessThenTen);

echo "
" . "
" . "================================================== filter end ==================================================";
echo "
" . "
" . "================================================== reduce start ==================================================" . "
" . "
";

$sum = array_reduce($numbersTillTwenty, fn($carry, $number) => $carry + $number); // run a reducer in a array

var_dump($sum);

echo "
" . "
" . "================================================== reduce end ==================================================";

?>

```

- php-revision/src/008_string_functions.php
- `strlen($string);` // Get the length of a string
- `strpos($string, 'o');` // Find the position of the first occurrence of a substring in a string
- `strrpos($string, 'o');` // Find the position of the last occurrence of a substring in a string
- `strrev($string);` // Reverse a string
- `strtolower($string);` // Convert all characters to lowercase
- `strtoupper($string);` // Convert all characters to uppercase
- `ucwords($string);` // Uppercase the first character of each word
- `str_replace('World', 'Everyone', $string);` // String replace
- `substr($string, 0, 5);` // Return portion of a string specified by the offset and length
- `substr($string, 5);` // Return portion of a string specified by the offset and length
- `str_starts_with($string, 'Hello')` // Starts with
- `str_ends_with($string, 'Hello')` // Starts with
- `htmlentities($string2);` // HTML Entities
- `printf('%s is a %s', 'Brad', 'nice guy');` // Formatted Strings - useful when you have outside data - Different specifiers for different data types
```
Hello World';
echo htmlentities($string2);

// Formatted Strings - useful when you have outside data
// Different specifiers for different data types
printf('%s is a %s', 'Brad', 'nice guy');
printf('1 + 1 = %f', 1 + 1); // float

?>
```

- php-revision/src/009_super_globals.php
- `$GLOBALS` // A superglobal variable that holds information about any variables in global scope.
- `$_GET` // Contains information about variables passed through a URL or a form.
- `$_POST` // Contains information about variables passed through a form.
- `$_COOKIE` // Contains information about variables passed through a cookie.
- `$_SESSION` // Contains information about variables passed through a session.
- `$_SERVER` // Contains information about the server environment.
- `$_ENV` // Contains information about the environment variables.
- `$_FILES` // Contains information about files uploaded to the script.
- `$_REQUEST` // Contains information about variables passed through the form or URL.
```




Document


  • Host:

  • Document Root:

  • System Root:

  • Server Name:

  • Server Port:

  • Current File Dir:

  • Request URI:

  • Server Software:

  • Client Info:

  • Remote Address:

  • Remote Port:

```

- php-revision/src/010_get_post.php
```
';
// echo $_GET['age'] . '
';

if ($_POST['submit'])
{
echo $_POST['name'] . '
';
echo $_POST['age'] . '
';
}

?>


Click


Name:



Age:


```

- php-revision/src/011_sanitizing_inputs.php
- `htmlspecialchars()` // Convert special characters to HTML entities
- `filter_var()` // Sanitize data
- `filter_input()` // Sanitize inputs
- `FILTER_SANITIZE_STRING` // Convert string to string with only alphanumeric, whitespace, and the following characters - _.:/
- `FILTER_SANITIZE_EMAIL` // Convert string to a valid email address
- `FILTER_SANITIZE_URL` // Convert string to a valid URL
- `FILTER_SANITIZE_NUMBER_INT` // Convert string to an integer
- `FILTER_SANITIZE_NUMBER_FLOAT` // Convert string to a float
- `FILTER_SANITIZE_FULL_SPECIAL_CHARS` // HTML-encodes special characters, keeps spaces and most other characters

```


Name:




Email:




```

- php-revision/src/012_cookies.php
- `$_COOKIE` // get cookie
- `setcookie('name', 'MAK', time() + 86400);` // set a cookie - first parameter is name second is value and third is expiry - time() = current time (86400 second are equal to one minute)
```

```

- php-revision/src/013_sessions.php
- `$_SESSION` // get session
- `$_SESSION['username'] = $username;` // set a session - simple assign it to any value
- `header('Location: some-page');` // redirect to other page
- `session_start();` // to start a session - must use if you want to use a session
- `session_destroy();` // to end a session
```


Username:





Password:




```

- php-revision/src/014_file_handling.php
- `file_exists` // if file exist
- `fopen` // open a file - required file path and permission - 'r' Read | 'w' Write
- `fread` // read a file;
- `fclose` // close a file
- `fwrite` // write a file

```

```

- php-revision/src/015_file_upload.php
- `$_FILES` // get a file
- `$_FILES['upload']['name']` // file name
- `$_FILES['upload']['size']` // file size
- `$_FILES['upload']['tmp_name']` // file tmp_name
- `move_uploaded_file` // upload a file in the folder structure
```
File uploaded!';
} else {
echo '

File too large!

';
}
} else {
$message = '

Invalid file type!

';
}
} else {
$message = '

Please choose a file

';
}
}
?>




File Upload

Select image to upload:

```

- php-revision/src/016_exception.php
- `throw new Exception` // add a new error
- `try` // we will try things here - code which we want to run
- `catch (Exception $e)` // only if code break it will get here
- `finally` // always run no matter what you do in try or catch - optional
```
getMessage(). ' ';
} finally {
echo 'first finally';
}

echo 'hello world';

?>

```

- php-revision/src/017_oop.php
- `class` // class are like object we can create them to use them multiple times
- `Access Modifiers` // public, private, protected
- `public` // can be accessed from anywhere
- `private` // can only be accessed from inside the class
- `protected` // can only be accessed from inside the class and by inheriting classes
- `extends` // you can Inherit any class using extends keyword and you can now use protected and public method here
- `parent::` // access any parent method
```
name = $name;
$this->email = $email;
$this->password = $password;
}

// Methods are functions that belong to a class.
public function set_name($name) {
$this->name = $name;
}

function get_name() {
return $this->name;
}
}

$user1 = new User('Moiz', 'moiz@test.com', 'some-password');
$user2 = new User('Maria', 'moiz@test.com', 'some-password');

// $user1->name = 'MAK'; // you can't access a protected property
$user2->set_name('MAK');

var_dump($user1);

echo $user2->get_name();

// Inheritance

class employee extends User {

private $title;

public function __construct($name, $email, $password, $title)
{
parent::__construct($name, $email, $password);

$this->title = $title;
}

public function get_title()
{
return $this->title;
}
}

$employ1 = new employee('moiz ali', 'moiz.ali@test.com', 'someCoolPassword123!', 'Software Engineer');

// var_dump($employ1);

echo $employ1->get_title();

```

- `includes` // use to include a file - no error if file not found
- `require` // use to include a file - error if file not found
- `require_one` // use to include a file - if already include then doesn't include twice

## Logical Operators
- `<` = less than
- `>` = greater than
- `<=` = less than or equal to
- `>=` = greater than or equal to
- `==` = equal to
- `===` = identical to
- `!` = not comparison
- `!=` = mot equal to
- `!==` = not identical to
- `?` = (in ternary operator) if
- `:` = (in ternary operator) else
- `??` = or comparison
- `&&` = and comparison
- `||` = or comparison

## Style Guide
- `//` this is a single line comment = use for single line comments
- `/*
this is a multi-line
comment
*/` = use for multi line comments
- `kabab case` is recommended in `PHP`, eg: my_app.
- `PHP` ignore `white spaces` so you can hit the enter button as much as you want - ( not recommended )
- `inc` use for component folder

## Resources
I start my journey using this cool stuff so shout to them:
- https://www.youtube.com/watch?v=BUCiSSyIGGU