Added Perl, PHP.

This commit is contained in:
CSnap 2023-11-19 04:05:23 +00:00
parent b80f78b411
commit 608673cb2b
3 changed files with 740 additions and 1 deletions

454
PHP.md Normal file
View File

@ -0,0 +1,454 @@
# PHP Cheat Sheet
## Table of Contents
1. [Variables](#variables)
2. [Data Types](#data-types)
3. [Operators](#operators)
4. [Control Structures](#control-structures)
5. [Functions](#functions)
6. [Arrays](#arrays)
7. [Strings](#strings)
8. [File Handling](#file-handling)
9. [Error Handling](#error-handling)
10. [Classes and Objects](#classes-and-objects)
11. [Sessions and Cookies](#sessions-and-cookies)
12. [Database Connectivity](#database-connectivity)
13. [Regular Expressions](#regular-expressions)
## Variables
### Declaration and Assignment
```php
<?php
$variable_name = value;
?>
```
### Variable Types
- String: `$string_variable = "Hello";`
- Integer: `$int_variable = 42;`
- Float: `$float_variable = 3.14;`
- Boolean: `$bool_variable = true;`
## Data Types
### Scalar Types
- String
- Integer
- Float (double)
- Boolean
### Compound Types
- Array
- Object
### Special Types
- Resource
- NULL
## Operators
### Arithmetic Operators
```php
+, -, *, /, %, ** (exponentiation)
```
### Comparison Operators
```php
==, ===, !=, !==, <, >, <=, >=
```
### Logical Operators
```php
&& (and), || (or), ! (not)
```
### Assignment Operators
```php
=, +=, -=, *=, /=, %=
```
## Control Structures
### If Statement
```php
if (condition) {
// code to be executed if the condition is true
} elseif (another_condition) {
// code to be executed if the previous condition was false and this one is true
} else {
// code to be executed if all conditions are false
}
```
### Switch Statement
```php
switch (variable) {
case value1:
// code to be executed if variable equals value1
break;
case value2:
// code to be executed if variable equals value2
break;
default:
// code to be executed if variable doesn't match any case
}
```
### Loops
#### For Loop
```php
for ($i = 0; $i < 5; $i++) {
// code to be executed in each iteration
}
```
#### While Loop
```php
while (condition) {
// code to be executed as long as the condition is true
}
```
#### Do-While Loop
```php
do {
// code to be executed at least once, then repeated as long as the condition is true
} while (condition);
```
## Functions
### Function Declaration
```php
function functionName($param1, $param2) {
// code to be executed
return $result; // optional
}
```
### Function Call
```php
$result = functionName($arg1, $arg2);
```
## Arrays
### Indexed Array
```php
$indexed_array = array("value1", "value2", "value3");
```
### Associative Array
```php
$assoc_array = array("key1" => "value1", "key2" => "value2");
```
### Multidimensional Array
```php
$multi_array = array(
array("value1", "value2"),
array("value3", "value4")
);
```
## Strings
### Concatenation
```php
$string1 = "Hello";
$string2 = "World";
$concatenated = $string1 . " " . $string2;
```
### String Functions
```php
strlen($string); // length of the string
strpos($string, "find"); // position of the first occurrence of "find"
substr($string, start, length); // extract a portion of the string
```
## File Handling
### Reading from a File
```php
$file_content = file_get_contents("filename.txt");
```
### Writing to a File
```php
file_put_contents("filename.txt", "Hello, World!");
```
## Error Handling
### Try-Catch Block
```php
try {
// code that may throw an exception
} catch (Exception $e) {
// handle the exception
echo "Error: " . $e->getMessage();
}
```
## Classes and Objects
### Class Declaration
```php
class MyClass {
// properties and methods
}
```
### Object Instantiation
```php
$object = new MyClass();
```
## Sessions and Cookies
### Sessions
```php
session_start();
$_SESSION['username'] = 'John';
```
### Cookies
```php
setcookie('user', 'Jane', time() + 3600, '/');
```
## Database Connectivity
### MySQLi Connection
```php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
```
### MySQLi Query
```php
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
```
## Regular Expressions
### Pattern Matching
```php
$pattern = "/[0-9]+/";
$string = "There are 123 apples";
preg_match($pattern, $string, $matches);
```
```
# PHP Extended Examples
## Variables
### Variable Scope
```php
<?php
$global_variable = "I am global";
function myFunction() {
$local_variable = "I am local";
echo $local_variable; // Accessible within the function
echo $global_variable; // Accessing a global variable requires the global keyword
}
myFunction();
echo $global_variable; // Accessible outside the function
// echo $local_variable; // This will throw an error since $local_variable is not in scope
?>
```
## Control Structures
### Foreach Loop with Arrays
```php
<?php
$colors = array("Red", "Green", "Blue");
foreach ($colors as $color) {
echo $color . "\n";
}
?>
```
### Switch Statement with Fall-Through
```php
<?php
$day = "Monday";
switch ($day) {
case "Monday":
case "Tuesday":
echo "It's a weekday.";
break;
case "Saturday":
case "Sunday":
echo "It's the weekend.";
break;
default:
echo "Not a valid day.";
}
?>
```
## Functions
### Default Parameter Values
```php
<?php
function greet($name = "Guest") {
echo "Hello, " . $name . "!";
}
greet(); // Outputs: Hello, Guest!
greet("John"); // Outputs: Hello, John!
?>
```
### Variable Number of Arguments
```php
<?php
function sum(...$numbers) {
$result = 0;
foreach ($numbers as $number) {
$result += $number;
}
return $result;
}
echo sum(1, 2, 3, 4); // Outputs: 10
?>
```
## Arrays
### Array Functions
```php
<?php
$numbers = array(1, 2, 3, 4, 5);
// Count elements in an array
echo count($numbers); // Outputs: 5
// Find the sum of array elements
echo array_sum($numbers); // Outputs: 15
// Merge two arrays
$moreNumbers = array(6, 7, 8);
$combined = array_merge($numbers, $moreNumbers);
print_r($combined); // Outputs: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 )
?>
```
## Strings
### Regular Expression Match and Replace
```php
<?php
$string = "The quick brown fox jumps over the lazy dog";
// Check if the string contains the word "fox"
if (preg_match("/fox/", $string)) {
echo "Found a fox!";
}
// Replace "fox" with "cat"
$newString = preg_replace("/fox/", "cat", $string);
echo $newString; // Outputs: The quick brown cat jumps over the lazy dog
?>
```
## File Handling
### Reading and Writing to Files
```php
<?php
// Reading from a file
$file_content = file_get_contents("example.txt");
echo $file_content;
// Writing to a file
$new_content = "This is some new content.";
file_put_contents("example.txt", $new_content);
?>
```
## Classes and Objects
### Class Inheritance
```php
<?php
class Animal {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function makeSound() {
echo "Generic animal sound\n";
}
}
class Dog extends Animal {
public function makeSound() {
echo "Woof!\n";
}
}
$dog = new Dog("Buddy");
echo $dog->name; // Outputs: Buddy
$dog->makeSound(); // Outputs: Woof!
?>
```
## Database Connectivity
### MySQLi Prepared Statements
```php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Prepared statement
$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $conn->prepare($sql);
$username = "john_doe";
$stmt->bind_param("s", $username);
$stmt->execute();
// Fetch result
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
print_r($row);
}
// Close connection
$stmt->close();
$conn->close();
?>
```
```

View File

@ -1,8 +1,13 @@
# cheetsheetz # CheetSheetz
Collection of various technical "cheat sheets". Collection of various technical "cheat sheets".
[Markdown](https://git.namenode.xyz/CSnap/cheetsheetz/src/branch/main/markdown.md) [Markdown](https://git.namenode.xyz/CSnap/cheetsheetz/src/branch/main/markdown.md)
[Perl](https://git.namenode.xyz/CSnap/cheetsheetz/src/branch/main/perl.md)
[PHP]((https://git.namenode.xyz/CSnap/cheetsheetz/src/branch/main/PHP.md)
[Python](https://git.namenode.xyz/CSnap/cheetsheetz/src/branch/main/python.md) [Python](https://git.namenode.xyz/CSnap/cheetsheetz/src/branch/main/python.md)
[LEMP Guide](https://git.namenode.xyz/CSnap/cheetsheetz/src/branch/main/LEMP.md) [LEMP Guide](https://git.namenode.xyz/CSnap/cheetsheetz/src/branch/main/LEMP.md)

280
perl.md Normal file
View File

@ -0,0 +1,280 @@
# Perl Cheat Sheet
## Basics
### Comments
```perl
# This is a comment
```
### Print
```perl
print "Hello, World!\n";
```
### Variables
```perl
$scalar_variable = 42;
@array_variable = (1, 2, 3);
%hash_variable = ('key' => 'value');
```
## Control Structures
### if-else
```perl
if ($condition) {
# Code to execute if condition is true
} else {
# Code to execute if condition is false
}
```
### foreach
```perl
foreach $item (@array) {
# Code to execute for each item in the array
}
```
### while
```perl
while ($condition) {
# Code to execute while condition is true
}
```
## Subroutines
```perl
sub greet {
my $name = shift;
print "Hello, $name!\n";
}
greet("Alice");
```
## Regular Expressions
### Matching
```perl
if ($string =~ /pattern/) {
# Code to execute if pattern is found in $string
}
```
### Substitution
```perl
$string =~ s/find/replace/;
```
## File Handling
### Open and Read
```perl
open(my $file, '<', 'filename.txt') or die "Can't open file: $!";
while (<$file>) {
chomp;
print "$_\n";
}
close($file);
```
### Open and Write
```perl
open(my $file, '>', 'output.txt') or die "Can't open file: $!";
print $file "Hello, File!\n";
close($file);
```
## Modules
### Using Modules
```perl
use Module::Name;
```
### Exporting Functions
```perl
use Module::Name qw(function1 function2);
```
## References
### Scalar Reference
```perl
$scalar_ref = \$scalar_variable;
```
### Array Reference
```perl
$array_ref = \@array_variable;
```
### Hash Reference
```perl
$hash_ref = \%hash_variable;
```
# Advanced Perl Cheat Sheet
## Basics
### Comments
```perl
# This is a comment
```
### Print
```perl
print "Hello, World!\n";
```
### Variables
```perl
$scalar_variable = 42;
@array_variable = (1, 2, 3);
%hash_variable = ('key' => 'value');
```
### Data Types
```perl
$string = "Perl";
$number = 42;
$float = 3.14;
```
## Control Structures
### if-else
```perl
if ($condition) {
# Code to execute if condition is true
} elsif ($another_condition) {
# Code to execute if another condition is true
} else {
# Code to execute if all conditions are false
}
```
### foreach
```perl
foreach $item (@array) {
# Code to execute for each item in the array
}
```
### while
```perl
while ($condition) {
# Code to execute while condition is true
}
```
## Subroutines
```perl
sub greet {
my $name = shift;
print "Hello, $name!\n";
}
greet("Alice");
```
### Returning Values
```perl
sub add {
my ($num1, $num2) = @_;
return $num1 + $num2;
}
my $result = add(3, 4);
print "Sum: $result\n";
```
## Regular Expressions
### Matching
```perl
if ($string =~ /pattern/) {
# Code to execute if pattern is found in $string
}
```
### Substitution
```perl
$string =~ s/find/replace/;
```
## File Handling
### Open and Read
```perl
open(my $file, '<', 'filename.txt') or die "Can't open file: $!";
while (<$file>) {
chomp;
print "$_\n";
}
close($file);
```
### Open and Write
```perl
open(my $file, '>', 'output.txt') or die "Can't open file: $!";
print $file "Hello, File!\n";
close($file);
```
## Modules
### Using Modules
```perl
use Module::Name;
```
### Exporting Functions
```perl
use Module::Name qw(function1 function2);
```
## References
### Scalar Reference
```perl
$scalar_ref = \$scalar_variable;
```
### Array Reference
```perl
$array_ref = \@array_variable;
```
### Hash Reference
```perl
$hash_ref = \%hash_variable;
```
## Structuring a Perl Script for Bash
### Create a Perl Script
```perl
#!/usr/bin/perl
use strict;
use warnings;
# Perl script code here
print "Hello from Perl!\n";
```
### Make it Executable
```bash
chmod +x script.pl
```
### Run from Bash
```bash
./script.pl
```