# PHP BASICS

[PHP Crash Course](https://www.youtube.com/watch?v=BUCiSSyIGGU)\
[PHP Code Structure Reference Repo](https://github.com/bradtraversy/php-crash/tree/main)

### **Basic PHP Syntax**

#### 1. **PHP Tags**

PHP code is enclosed within `<?php` and `?>` tags.

```php
<?php
// PHP code goes here
?>
```

#### 2. **Comments**

* Single-line comments: `//` or `#`
* Multi-line comments: `/* ... */`

```php
<?php
// This is a single-line comment
# This is also a single-line comment

/*
This is a
multi-line comment
*/
?>
```

#### 3. **Variables**

* Variables start with a `$` sign.
* Variable names are case-sensitive.
* No need to declare variable types (PHP is loosely typed).

```php
<?php
$name = "John";
$age = 25;
?>
```

#### 4. **Echo/Print**

* `echo` and `print` are used to output data.

```php
<?php
echo "Hello, World!";
print "Hello, World!";
?>
```

#### 5. **Data Types**

PHP supports:

* Strings (`"Hello"`)
* Integers (`10`)
* Floats (`3.14`)
* Booleans (`true` or `false`)
* Arrays (`[1, 2, 3]`)
* Objects
* NULL

```php
<?php
$string = "Hello";
$int = 42;
$float = 3.14;
$bool = true;
$array = [1, 2, 3];
$null = null;
?>
```

#### 6. **Concatenation**

Use `.` to concatenate strings.

```php
<?php
$name = "John";
echo "Hello, " . $name;
?>
```

#### 7. **Conditionals**

* `if`, `else`, `elseif`

```php
<?php
$age = 18;
if ($age >= 18) {
    echo "You are an adult.";
} else {
    echo "You are a minor.";
}
?>
```

#### 8. **Loops**

* `for`, `while`, `foreach`

```php
<?php
// For loop
for ($i = 0; $i < 5; $i++) {
    echo $i;
}

// While loop
$i = 0;
while ($i < 5) {
    echo $i;
    $i++;
}

// Foreach loop (for arrays)
$colors = ["red", "green", "blue"];
foreach ($colors as $color) {
    echo $color;
}
?>
```

#### 9. **Functions**

* Define functions using `function`.

```php
<?php
function greet($name) {
    return "Hello, " . $name;
}
echo greet("John");
?>
```

***

### **Most Used PHP Methods**

#### 1. **String Functions**

* `strlen()`: Get string length.
* `str_replace()`: Replace text in a string.
* `strpos()`: Find the position of a substring.
* `substr()`: Get a portion of a string.
* `strtolower()` / `strtoupper()`: Convert to lowercase/uppercase.

```php
<?php
$text = "Hello, World!";
echo strlen($text); // 13
echo str_replace("World", "PHP", $text); // Hello, PHP!
echo strpos($text, "World"); // 7
echo substr($text, 0, 5); // Hello
echo strtolower($text); // hello, world!
?>
```

#### 2. **Array Functions**

* `count()`: Get the number of elements in an array.
* `array_push()`: Add an element to the end of an array.
* `array_pop()`: Remove the last element of an array.
* `array_merge()`: Merge two or more arrays.
* `in_array()`: Check if a value exists in an array.

```php
<?php
$fruits = ["apple", "banana"];
echo count($fruits); // 2
array_push($fruits, "orange");
print_r($fruits); // ["apple", "banana", "orange"]
echo in_array("banana", $fruits); // true
?>
```

#### 3. **File Handling**

* `file_get_contents()`: Read a file into a string.
* `file_put_contents()`: Write data to a file.
* `fopen()`, `fread()`, `fwrite()`, `fclose()`: Advanced file handling.

```php
<?php
$fileContent = file_get_contents("example.txt");
file_put_contents("example.txt", "New content");
?>
```

#### 4. **Superglobals**

* `$_GET`: Data from URL parameters.
* `$_POST`: Data from form submissions.
* `$_SESSION`: Session variables.
* `$_COOKIE`: Cookies.
* `$_SERVER`: Server and execution environment information.

```php
<?php
// Example: Get data from a form
$username = $_POST['username'];
?>
```

#### 5. **Date and Time**

* `date()`: Format a date/time string.
* `time()`: Get the current Unix timestamp.

```php
<?php
echo date("Y-m-d H:i:s"); // 2023-10-05 12:34:56
echo time(); // Current timestamp
?>
```

#### 6. **Database Interaction (MySQLi)**

* `mysqli_connect()`: Connect to a MySQL database.
* `mysqli_query()`: Execute a query.
* `mysqli_fetch_assoc()`: Fetch a result row as an associative array.

```php
<?php
$conn = mysqli_connect("localhost", "user", "password", "database");
$result = mysqli_query($conn, "SELECT * FROM users");
while ($row = mysqli_fetch_assoc($result)) {
    echo $row['username'];
}
mysqli_close($conn);
?>
```

### &#x20;


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://n0m4dsec.gitbook.io/sec-book/additional-topics/php-basics.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
