php code snippets

PHP Script to download image from remote url
<?php
    $file_url = "https://file_url.jpeg"; // Replace your remote image url here
    $file_name = basename($file_url);
    header('Content-Type: application/octet-stream');
    header("Content-Transfer-Encoding: Binary");
    header("Content-disposition: attachment; filename="".$file_name.""");
    readfile($file_url);
    exit;
?>
Uppercase first character of each word of a String in PHP
<?php
  $str = "hello world";
  
  $res = ucwords($str);
  
  echo $res;
?>
Uppercase first character of a String in PHP
<?php
  echo ucfirst("we are programmers");
  // -> We are programmers
?>
Lowercase first character of a String in PHP
<?php
  echo lcfirst("Foo bar");

  // -> foo bar
?>
Convert string to uppercase in PHP
<?php
  echo strtoupper("We are ProgRammers");
  // -> WE ARE PROGRAMMERS
?>
Loop through Array of Objects in PHP
<?php
  $students = [
    ["id" => 1, "name" => "John", "department" => "Science" ],
    ["id" => 2, "name" => "Sonia", "department" => "Arts" ],
    ["id" => 3, "name" => "Tony", "department" => "Science" ]
  ];
  
  foreach($students as $key=>$value) {
    echo "Id: {$value['id']}, Name: {$value['name']}";
    echo $value['department'];
  }
?>
How to Use PHP to Get the Client IP Address
<?php
	// create a function to get the client IP
  function get_ip_address() {
      $client_ip = '';
      if (getenv('HTTP_CLIENT_IP'))
          $client_ip = getenv('HTTP_CLIENT_IP');
      else if(getenv('HTTP_X_FORWARDED_FOR'))
          $client_ip = getenv('HTTP_X_FORWARDED_FOR');
      else if(getenv('HTTP_X_FORWARDED'))
          $client_ip = getenv('HTTP_X_FORWARDED');
      else if(getenv('HTTP_FORWARDED_FOR'))
          $client_ip = getenv('HTTP_FORWARDED_FOR');
      else if(getenv('HTTP_FORWARDED'))
         $client_ip = getenv('HTTP_FORWARDED');
      else if(getenv('REMOTE_ADDR'))
          $client_ip = getenv('REMOTE_ADDR');
      else
          $client_ip = 'UNKNOWN';
      return $client_ip;
  }
  
  // print ip address
  echo get_ip_address();
?>
Get random value from an array in PHP
<?php
	$my_arr = ["James", "Stark", "Suart", "Rajesh", "Troy"];
	
	$rand_index = array_rand($my_arr, 1);
	
	echo $my_arr[$rand_index];
?>
Assign a Javascript variable to PHP variable
<script> document.cookie = "js_var_value = " + localStorage.value </script>
<?php
    $php_var_val= $_COOKIE['js_var_value'];
    echo $php_var_val;
?>
Check if string contains a substring using PHP
<?php
    if (strpos("Hello World", "Wor") != false) {
        echo "Substring found";
    } else {
        echo "Substring not found";
    }
?>
PHP program to get the values of checkboxes on Form Submit
<?php
    $values = $_POST['checbox_name'];

    foreach ($values as $val){ 
        echo $val;
    }
?>
Convert String to an Integer in PHP
<?php
  // Define a string
	$my_str = "30";
	
	// Convert to integer value
	$val = (int)$my_str;
	
	echo $val;
?>
PHP program to find the number of days between two dates
<?php
    // If you are using PHP 5.3 or above
	$date_1 = new DateTime("2021-09-20");
    $date_2 = new DateTime("2021-10-22");

    $num_of_days = $date_1->diff($date_2)->format("%a");

    echo $num_of_days;
?>
Print or echo new line using PHP
<?php
    echo 'Data 1 is here' . PHP_EOL;
    echo 'Data 2 is here' . PHP_EOL;
?>
Display errors if not shown in PHP script
<?php
    // Add this on the top of your PHP script
    ini_set('display_errors', 1);
    error_reporting(E_ALL);
?>
Validate IP address using filter_var() method PHP
<?php
    $ip_address = "168.0.0.1";

    if (filter_var($ip_address, FILTER_VALIDATE_IP) == true) {
        echo("Valid IP");
    } else {
        echo("Invalid Ip");
    }
?>
Validate a number using filter_var() method in PHP
<?php
    $value = 500;

    if (!filter_var($value, FILTER_VALIDATE_INT) === false) {
        echo("Value is valid");
    } else {
        echo("Value is invalid");
    }

    // -> Value is valid
?>
Send POST request without using curl using PHP 5+
<?php
    $api_url = 'https://domain.com/endpoint';
    $post_data = [
        'name' => 'Rick', 
        'city' => 'Atlanta'
    ];

    // We are using 'http' key 
    $request_options = [
        'http' => [
            'header'  => "Content-type: application/x-www-form-urlencoded
",
            'method'  => 'POST',
            'content' => http_build_query($post_data)
        ]
    ];
    $stream_context  = stream_context_create($request_options);
    $response = file_get_contents($api_url, false, $stream_context);
    if ($response === FALSE) {
        // Code to handle error here
    }

    var_dump($response);
?>
String interpolation and formation in PHP
<?php
    $name = "world";
    echo "Hello $name";
    //-> Hello World

    $arr = [
        'name' => 'John'  
    ];
    echo "My Name is '{$arr["name"]}'";
    //-> My Name is 'John'
?>
Join or concatenate two or multiple strings in PHP
<?php
  $str1 = "We are ";
  $str2 = "Devsheet ";
  $str3 = "Programmers";
  
  $result1 = $str1 . $str2;
  //-> We are Devsheet 
  
  $result2 = $str1 . $str2 . $str3;
  //-> We are Devsheet Programmers
?>
PHP program to generate a token that is cryptographically secured
<?php
    $token = bin2hex(openssl_random_pseudo_bytes(20));
    echo "$token";

    // If you are using PHP 7 - You can also use
    $token = bin2hex(random_bytes(20));
    echo $token;
?>
Check if a folder already created using PHP
<?php
    $newdirname = $_POST["new_dir_name"];
    $dir_path = "path/to/" . $newdirname . "/";

    if (!file_exists($dir_path)) {
        mkdir($dir_path, 0777);
        echo "The directory creted successfully.";
        exit;
    } else {
        echo "The directory already exists.";
    }    
?>
Convert Mysql date to Google sitemap date format PHP
<?php
    //MYSQL DATE FORMAT
    $updated_date = '2021-01-28 11:52:19';

    $new_datetime = new DateTime($updated_date);
    $final_date = $new_datetime->format('Y-m-d\TH:i:sP');

    echo $final_date; //2021-01-28T11:52:19+01:00
?>
Capitalize text PHP
<?php
    $txtStr = "hello world";
    echo ucfirst($txtStr);
    //prints - Hello world
?>
Convert String date to DATE MONTH-NAME YEAR format php
<?php
    $date_str = "10-01-2021";
    $full_date= strtotime($date_str); 
    echo date('d F Y', $full_date); 
    //PRINT- 10 January 2021
?>
Create constructor in PHP OOP
<?php
    class Student {
        public $name;
        public $email;

        function __construct($name, $email) {
            $this->name = $name;
            $this->email = $email;
        }

        function get_student_info() {
            return "name: " . $this->name . ', email: '. $this->email;
        }
    }

    $student = new Student("John", "[email protected]");
    $student_info = $student->get_student_info();
?>
Get first n words from a paragraph in PHP
<?php
    function get_n_words($paragraph, $word_counts) {
        preg_match("/(?:w+(?:W+|$)){0,$word_counts}/", $paragraph, $matches);
        return $matches[0];
    }

    get_n_words("This is a long paragraph", 2); //TO SELECT FIRST 2 WORDS
    get_n_words("This is a long paragraph", 10); //TO SELECT FIRST 10 WORDS
?>
Get current directory in PHP
<?php
    echo getcwd();
?>
Firebase push notification curl request in PHP
<?php
    $conn = common::createConnection();

    $title = $_POST['title'];
    $body = $_POST['body'];
    $image = $_POST['image'];
    $link = $_POST['link'];
    
    $data = [
        "notification" => [
            "body"  => $body,
            "title" => $title,
            "image" => $image
        ],
        "priority" =>  "high",
        "data" => [
            "click_action"  =>  "FLUTTER_NOTIFICATION_CLICK",
            "id"            =>  "1",
            "status"        =>  "done",
            "info"          =>  [
                "title"  => $title,
                "link"   => $link,
                "image"  => $image
            ]
        ],
        "to" => "<YOUR_FIREBASE_TOKEN>"
    ];

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_POST, 1);

    $headers = array();
    $headers[] = 'Content-Type: application/json';
    $headers[] = 'Authorization: key=<YOUR-AUTH-KEY>';
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $result = curl_exec($ch);
    curl_close ($ch);
    
    echo "request sent";
?>
Get values array by key name using array_column() PHP
<?php
    $employees = array(
        array(
            'emp_name' => 'Rick Grimes',
            'designation' => 'developer'
        ),
        array(
            'emp_name' => 'John Wick',
            'designation' => 'manager'
        )
    );

    $designations = array_column($employees, 'designation');
    print_r($designations);
?>
Split array into chunks using array_chunk() PHP
<?php
    //IN CHUNKS OF 2
    $subjects = array("Math","Physics","Chemistry","English");
    print_r(array_chunk($subjects,2));
?>
Define array PHP
<?php
    //DEFINE INDEXED ARRAY METHOD 1
    $array = array("Math", "Physics", "Checmistry");

    //DEFINE INDEXED ARRAY METHOD 2
    $array = ["Math", "Physics", "Checmistry"];

    //DEFINE ASSOCIATIVE ARRAY METHOD 1
    $array = array(
        "name" => "John",
        "profession" => "Programmer",
        "lang" => "PHP"
    );

    //DEFINE ASSOCIATIVE ARRAY METHOD 2
    $array = [
        "name" => "John",
        "profession" => "Programmer",
        "lang" => "PHP"
    ];
?>
Check if value exist in array using in_array() PHP
<?php
    $subjects = ["Math", "Physics", "Chemistry", "English", 50];
    
    //WITHOUT TYPE CHECK
    if (in_array("Chemistry", $subjects)) {
        echo "value exists";
    } else {
        echo "value does not exist";
    }

    //WITH TYPE CHECK - will check for string type 50
    if (in_array("50", $subjects, TRUE)) {
        echo "value exists";
    } else {
        echo "value does not exist";
    }
?>
Send mail in PHP using PHPMailer
<?php
    //SEND EMAIL VIA PHPMAILER PACKAGE
    // INSTALLATION - composer require phpmailer/phpmailer

    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\SMTP;
    use PHPMailer\PHPMailer\Exception;
    
    // Load Composer's autoloader
    require 'vendor/autoload.php';
    
    // CREATE MAILER INSTANT and PASS `true` TO ENABLE EXCEPTIONS
    $mail = new PHPMailer(true);
    
    try {
        //SERVER SETTINGS
        $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      // ENABLE DEBUG
        $mail->isSMTP();                                            // SEND MAIL USING SMTP
        $mail->Host       = 'smtp.server.com';                      // SMTP HOST NAME
        $mail->SMTPAuth   = true;                                   // ENABLE SMTP AUTHENTICATION
        $mail->Username   = '[email protected]';                      // SMTP USERNAME
        $mail->Password   = 'password';                             // SMTP PASSOWRD
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         // ENABLE TLS encryption;
        $mail->Port       = 587;                                    // TCP PORT
    
        //RECIPIENTS
        $mail->setFrom('[email protected]');
        $mail->addAddress('[email protected]', "name");               //NAME IS OPTIONAL
        $mail->addReplyTo('[email protected]', 'Information');
        $mail->addCC('[email protected]');
        $mail->addBCC('[email protected]');
    
        // ATTACHMENT
        $mail->addAttachment('path/to/file.zip');                   // Add attachments
        $mail->addAttachment('path/to/file.zip', 'file_name.jpg');  // file_name is optional
    
        // MAIL CONTENT
        $mail->isHTML(true);                                        // Set email format to HTML
        $mail->Subject = 'Here is the subject';
        $mail->Body    = '<div>Your HTML message <b>body</b> will be here</div>';
        $mail->AltBody = 'Place here plain text for no-HTML support mail clients';
    
        $mail->send();
        echo 'Mail sent successfully';
    } catch (Exception $e) {
        echo "Error while sending mail: {$mail->ErrorInfo}";
    }
?>
Date time in PHP
<?php
    //If we assume year - 2020, month - March, date - 10
    $format_date = date("Y-m-d H:i:s");                   // 2020-03-10 17:16:18 (MySQL DATETIME format)
    $format_date = date("F j, Y, g:i a");                 // March 10, 2020, 5:16 pm
    $format_date = date("m.d.y");                         // 03.10.20
    $format_date = date("j, n, Y");                       // 10, 3, 2020
    $format_date = date("Ymd");                           // 20200310
    $format_date = date('h-i-s, j-m-y, it is w Day');     // 05-16-18, 10-03-20, 1631 1618 6 Satpm01
    $format_date = date('\i\t \i\s \t\h\e jS \d\a\y.');   // it is the 10th day.
    $format_date = date("D M j G:i:s T Y");               // Sat Mar 10 17:16:18 MST 2001
    $format_date = date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:18 m is month
    $format_date = date("H:i:s");                         // 17:16:18
?>
Generate unique id PHP
<?php
    //Using uniqid()
    $uid = uniqid();
    echo $uid;

    //Using random_bytes and bin2hex
    $ran_bytes = random_bytes(15);
    $uid = bin2hex($ran_bytes);
    echo $uid;

    //USING md5
    $str = "uname";
    $uid = md5($str);
?>
mod or remainder using fmod() PHP
<?php
    echo fmod(15, 5); //output - 0
    echo fmod(15, 4); //output - 3
?>
Delete item from array PHP
<?php
    $subjects = ["Math", "Physics", "Chemistry"];
    unset($array[1]); //Remove Single Item(Physics) from array

    array_splice($subjects, 1, 2); //Remove multiple items form array
?>
Add item to array PHP
<?php
    // create an array
    $my_array = ["apple", "banana"];

    // add new item "orange" to array
    array_push($my_array, "orange");

    print_r($my_array);
?>
Create function in PHP
<?php
    function greeting($username) {
        echo "Hello : " . $username;
    }

    greeting("John");
?>
foreach loop php
<?php
    $fruits = ["apple", "banana", "orange"];
    foreach($fruits as $key => $value) {
        echo $key . " : " . $value; 
        //$key will be 0, 1, 2 and $value apple, banana, orange
    }

    $fruit = [
        "name" => "apple",
        "qty"  => 50,
        "type" => "seasonal"
    ];
    foreach($fruit as $key => $value) {
        echo $key . " : " . $value; 
        //$key will be name, qty, type and $value apple, 50 and seasonal
    }

    $fruits = [
        [
            "name" => "apple",
            "qty"  => 10,
            "type" => "seasonal"
        ],
        [
            "name" => "banana",
            "qty"  => 20,
            "type" => "seasonal"
        ]
    ];
    foreach($fruits as $key => $value) {
        echo $value["name"];
    }
?>
Switch case in PHP
<?php
    $type = "2";
    switch($type) {
        case "1":
            echo "case 1";
            break;
        case "2":
            echo "case 2";
            break;
        default:
            break;
    }
?>
Conditions or if else statement in PHP
<?php
    $x = 10;
    if ($x > 10) {
        echo "Greater than 10";
    } else if ($x < 10) {
        echo "Less than 10";
    } else {
        echo "Equals to 10";
    }
?>
Define constant in PHP
<?php
    define(const_name, const_value); //SYNTAX
    define("month", "september");
?>
Variable and data type in PHP
<?php
    $var_name = "hello world"; //DEFINE A VARIABLE
    $string_type = "I am a string"; //STRING DATA TYPE
    $int_type = 10; //INT DATA TYPE
    $double_type = 1.5; //DOUBLE DATA TYPE
    $array = array("name" => "John"); //ARRAY DATA TYPE
    $array = ["name" => "John"]; //ANOTHER WAY TO DEFINE ARRAY DATA TYPE
    $bool_type = true; //BOOL DATA TYPE
    $null_type = null; //NULL DATA TYPE
?>
Delete a file in PHP
<?php
    $filePath = 'path/to/file';
    unlink($filePath); //THIS FUNCTION DELETES THE FILE
?>
Write data to file using PHP
<?php
    $filePath = 'path/to/file/';
    $fileData = 'Hello world';
    file_put_contents($filePath, $fileData); // WRITE FRESH DATA TO FILE
    file_put_contents($filePath, $fileData, FILE_APPEND | LOCK_EX); //APPEND DATA AT THE END WITHOUT DELETING PREVIOUS DATA
?>
Check if item exist in array using PHP
<?php
    $arr = ["car", "bike", "plane"];
    $item = "plane";

    if ( in_array($item, $arr) ) {
        echo "Item exist in the given array";
    } else {
        echo "Item does not exist in the array";
    }
?>
Get array length in PHP
<?php
    $arr = ["1", "2", "3"];
    echo count($arr);
?>
Create new file and write data to it using PHP
<?php
    $new_file = fopen("filename.json", "w") or die("File can not be opened");
    $data = '{"firstname": "Hello", "lastname": "World"}';
    fwrite($new_file, $data);
    fclose($new_file);
?>
Read file content using PHP
<?php
    $file_path = "/path/to/file";
    $file_content = file_get_contents($file_path);
    echo $file_content;
?>
Check if file exist in PHP
<?php
    $filePath = "/path/to/file";
    if (file_exists($filePath)) {
        echo "file exists at the location";
    } else {
        echo "file does not exist";
    }
?>
Get last insert id in db using PHP
<?php
    $last_id = $conn->insert_id;
?>
login OOP MVC PDO
<?php
//loginController.class.php

class loginController extends Model{

    public function indexUser($username, $password){
        $username = $_POST['username'];
        $password = $_POST['password'];

        if(!empty($username) AND !empty($password)){
            $user = new Model();

            $credentialsAreValid = $user->CheckCredentials($username, $password);

            if($credentialsAreValid){

                $_SESSION['username'] = $username;
                echo "<script>alert('You are logged in )</script>";
                echo "<script>window.open('admin_home.php','_self')</script>";
                
            }
        }          
    }
}
?>
<?php
//model.class.php

class Model extends Dbh {

    protected function CheckCredentials($username, $password) {
    
        $sql = "SELECT * FROM admin_users WHERE username = ? && password = ?";
        $stmt = $this->connect()->prepare($sql);
        $stmt->bindvalue(1, $username);
        $stmt->bindvalue(2, $password);
        $result = $stmt->execute();
        
        $results = $stmt->fetchAll();        
        return $results;

    }

}

?>
<?php

                  if(!isset($_SESSION['username']) AND !isset($_GET['login'])){

                    echo "<a href='?login'>Admin Login</a>";
                    
                  }elseif(!isset($_SESSION['username']) && isset($_GET['login'])){
                      
                    echo "<form action=" . $_SERVER['PHP_SELF'] . " method='post'>";
                    echo "<input type='text' name='username' placeholder='Username'>";
                    echo "<input type='text' name='password' placeholder='Password'>";
                    echo "<input type='submit' name='submit_admin' placeholder='Admin Login'>";
                    echo "</form>";

                  }else{  
                   
                    echo "Hi " . $_SESSION['username'] . " Welcome back.";
                    echo "<a href='logout.php'>Log Out</a>";
                  
                  }

                  if(isset($_POST['submit_admin'])){
                    $username = $_POST['username'];
                    $password = $_POST['password'];
    
                    $user = new loginController();
                    $user->indexUser($username,$password);

                  }
                  
                ?>
Multidimentional array
<?php
$cars = array(
            'model' => array(
                        1 => 'BMW',
                        2 => 'AUDI',
                        3 => 'Bentley'
                    ),
            'colour' => array(
                        'BMW' => 'Red',
                        'Audi' => 'Black',
                        'Bently' => 'Blue'
                    ),
            'doors' => array(
                        'BMW' => 4,
                        'Audi' => 5,
                        'Bently' => 2
                    ),
        ); 

        print_r($cars);
     
        //echo 'I love my ' . $cars['model'][1] . ' but the it is ' . $cars['colour']['BMW'] 
              //. ' and only a ' . $cars['doors']['BMW'] . ' door.';


        $keys = array_keys($cars);
        for($i = 0; $i < count($cars); $i++) {
            echo $keys[$i] . "{<br>";
            foreach($cars[$keys[$i]] as $key => $value) {
                echo $key . " : " . $value . "<br>";
            }
            echo "}<br>";
        }
DELETE using bindValue
<?php
protected function deleteUser($firstname, $lastname){
    $sql = 'DELETE FROM users WHERE firstname = :firstname && lastname = :lastname';
    $stmt = $this->connect()->prepare($sql);
    $stmt->bindvalue(':firstname', $firstname, PDO::PARAM_STR);
    $stmt->bindvalue(':lastname', $lastname, PDO::PARAM_STR);
    $stmt->execute();
}
INSERT mvc OOP
<?php
//index.php
        if(isset($_POST['submit'])){
            
            $firstname = $_POST['firstname'];
            $lastname  = $_POST['lastname'];
            $email     = $_POST['email'];
            
            $obj = new Control(); // assign the object for controller class
            $obj->insert($firstname,$lastname,$email); // Pass the data in insert function
            //header("location: classes/control.class.php");
            echo "<script>alert('Inserted')</script>";
            echo "<script>window.open('index.php','_self')</script>";
        }

    ?>

    <?php
    //control.class.php
    class Control extends Model {

        public function insert($firstname,$lastname,$email) {

                $obj = new model();
                $obj->createUser($firstname,$lastname,$email);
        }

    }
    ?>
<?php
//model.class.php
    class Model extends Dbh{
        protected function createUser($firstname,$lastname,$email) {

            $sql = 'INSERT INTO users (firstname,lastname,email) VALUES (?,?,?)';
            $stmt = $this->connect()->prepare($sql);
            $stmt->execute([$firstname,$lastname,$email]);
        }
    }
MVC
<?php
/*
 *  The Model is the only class that interacts with the DB
 *  This class deals with all querys with the DB
 *  Extends to the Dbh class as obviously interacts with the DB
 *  class should be protected
 *  Only view and controller classes that extend to it can grab information
 * even when updating/inserting/deleting DB which is handles in the contr we still query in the model because it is only the modal that interacts with the DB
 */
//This is model.class.php
 class Model extends Dbh {

    protected function getUser($firstname) {
        $sql = 'SELECT * FROM users WHERE firstname = ?';
        $stmt = $this->connect()->prepare($sql);
        $stmt->execute([$firstname]);

        $results = $stmt->fetchAll();

        return $results;
    }

    protected function setUser($firstname, $lastname, $email) {
        $sql = 'INSERT INTO users (firstname, lastname, email) Values (?,?,?) ';
        $stmt = $this->connect()->prepare($sql);
        $stmt->execute([$firstname, $lastname, $email]);
    }

    protected function deleteUser($firstname, $lastname) {
        $sql = 'DELETE FROM users WHERE firstname = ? && lastname = ?';
        $stmt = $this->connect()->prepare($sql);
        $stmt->execute([$firstname, $lastname]);
    }

    protected function updateUser($email) {
        $sql = 'UPDATE users SET email = ? WHERE id = 8';
        $stmt = $this->connect()->prepare($sql);
        $stmt->execute([$email]);
    }

 }
?>
 <?php
/*
 * Must connect to DB so inportant to extends DBH class
 * Fetches Info from the Model 
 * 
 */
//This is view.class.php
class View extends Model {

    public function showUser($firstname){
        $results = $this->getUser($firstname);

        echo 'My name is ' . $results[0]['firstname'] . ' ' . $results[0]['lastname'];
        
    }

}
?>
<?php

/*
 * Updating, inserting, creating tables etc into database
 * 
 */
//This is controller.class.php
 class Controller extends Model {

    public function createUser($firstname, $lastname, $email) {
        $this->setUser($firstname, $lastname, $email);
    }

    public function araseUser($firstname, $lastname) {
        $this->deleteUser($firstname, $lastname);
    }

    public function editUser($email) {
        $this->updateUser($email);
    }
 }

?>
 <?php
include 'includes/autoload.inc.php';
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>MVC</title>
    </head>
    <body>
    <?php
    //$testObj = new Test();
    //$testObj->inserUser('John', 'Doe', '[email protected]');
    //$testObj->updateUser('[email protected]');

    //$showUser = new View();
    //$showUser->showUser('John','Lark');

    //$createUser = new Controller();
    //$createUser->createUser('Dean','Lark','[email protected]');

    //$deluser = new Controller();
    //$deluser->araseUser('Dean','Lark');

    //$updateUser = new Controller();
    //$updateUser->editUser('[email protected]');
    ?>
    </body>
</html>
UPDATE DB using OOP class
<?php
//Update DB
    public function updateUser($email) {
        $sql = 'UPDATE users SET email = ? WHERE id = 1';
        $stmt = $this->connect()->prepare($sql);
        $stmt->execute([$email]);
    }
Delete from DB OOP
//delete from DB
<?php
    public function deleteUser($firstname, $lastname){
        $sql = 'DELETE FROM users WHERE firstname = ? && lastname = ?';
        $stmt = $this->connect()->prepare($sql);
        $stmt->execute([$firstname, $lastname]);
    }

//in index.php
$deleteUser = new test();
$deleteUser->deleteUser('John','Doe');
Register for news feed
<?php
include "connect.php";
if(isset($_POST["subscribe"])){
  
  $fullname = $_POST["fullname"];
  $email = $_POST["email"];

  //Check that all feilds are filled in
  if(!empty($name) || empty($email)){
    echo "You have to fill out all fields";
  }

  //Check That full name string length
  if(strlen($fullname) <4) {
    echo "Your full name must be more than 4 charactors and less than 30.";
  }

  //Check that the names in database are not the same
  //Code must go here

  $query = "INSERT INTO subscriptions (fullname, email) VALUES ('$fullname', '$email')";
  $run = mysqli_query($conn, $query);
  if($run){
    echo "<script>alert('You have successfully subscribed')</script>";
  }

}
?>
spl_autoload_register();
<?php

spl_autoload_register('myAutoload');

function myAutoload($placeholder) {
    $url = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

    if(strpos($url, 'includes') !== false){
        $path = '../classes/';
    }else{
        $path = 'classes/';
    }

    $extention = '.class.php';

    require_once $path . $placeholder . $extention;
}
PHP OOP insert, select from DB
<?php

class Test extends Dbn {
    
    //without prepared statements 
    public function getUsers() {
        $sql = "SELECT * FROM users";
        $stmt = $this->connect()->query($sql);
        while($row = $stmt->fetch()) {
            echo $row['firstname'];
        }
    }

    //with prepared statements 
    public function getUsersStmt($firstname, $lastname) {
        $sql = "SELECT * FROM users WHERE firstname = ? && lastname = ?";
        $stmt = $this->connect()->prepare($sql);
        $stmt->execute([$firstname, $lastname]);
        $names = $stmt->fetchAll();

        foreach ($names AS $name) {
            echo $name['firstname'] . " " . $name['lastname'];
        }
    }

    //Insert prepared statements 
    public function inserUser($firstname, $lastname, $email) {
        $sql = "INSERT INTO users (firstname, lastname, email) values (?,?,?)";
        $stmt = $this->connect()->prepare($sql);
        $stmt->execute([$firstname, $lastname, $email]);
        
    }
    
}
Connect to DB using PDO
<?php 

class Dbn {
    private $host = 'localhost';
    private $user = 'root';
    private $pass = '';
    private $dbName = 'DLcleaners';

    protected function connect() {
        $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbName;
        $pdo = new PDO($dsn, $this->user, $this->pass);
        $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        return $pdo;
    }
}
Go to another page in PHP
<?php
    header("Location: page_name.php"); //You can pass relative url of page or full url of page
    exit();
?>
Access global variable inside a function PHP
<?php
    $globalVal = "I am a global variable";

    function printVal() {
        global $globalVal;

        echo $globalVal;
    }

    printVal();
?>
Get file name form url in PHP
<?php
    $url = "https://remote-url-path/filename.jpg";
    echo basename($url);
?>
Download file from remote url to user desktop in PHP
<?php
    $file_url = $_GET['file_url'];
    $file_name = basename($file_url);
    header('Content-Type: application/octet-stream');
    header("Content-Transfer-Encoding: Binary");
    header("Content-disposition: attachment; filename=\"".$file_name."\"");
    readfile($file_url);
    exit;
?>
Connect Mysql and PHP using mysqli
<?php
    class connection {
        public static function createConnection() {
            $servername = "localhost";
            $username = "mysqlUsername";
            $password = "mysqlPassword";
            $dbname = "dbName";

            $conn = new mysqli($servername, $username, $password, $dbname);
            if ($conn->connect_error) {
                die("Connection failed: " . $conn->connect_error);
                return "connection failed";
            } else {
                return $conn;
            }
        }
    }

    //TO CREATE CONNECTION CALL
    $conn = connection::createConnection();
?>
Editorjs blocks - JSON to HTML PHP
<?php
    function jsonToHtml($jsonStr) {
        $obj = json_decode($jsonStr);

        $html = '';
        foreach ($obj->blocks as $block) {
            switch ($block->type) {
                case 'paragraph':
                    $html .= '<p>' . $block->data->text . '</p>';
                    break;
                
                case 'header':
                    $html .= '<h'. $block->data->level .'>' . $block->data->text . '</h'. $block->data->level .'>';
                    break;

                case 'raw':
                    $html .= $block->data->html;
                    break;

                case 'list':
                    $lsType = ($block->data->style == 'ordered') ? 'ol' : 'ul';
                    $html .= '<' . $lsType . '>';
                    foreach($block->data->items as $item) {
                        $html .= '<li>' . $item . '</li>';
                    }
                    $html .= '</' . $lsType . '>';
                    break;
                
                case 'code':
                    $html .= '<pre><code class="language-'. $block->data->lang .'">'. $block->data->code .'</code></pre>';
                    break;
                
                case 'image':
                    $html .= '<div class="img_pnl"><img src="'. $block->data->file->url .'" /></div>';
                    break;
                
                default:
                    break;
            }
        }
        
        return $html;
    }
?>
Split string by new line PHP
$str = "Line number 1
Line number 2";

$str_parts = preg_split("/\r\n|\r|\n/", $str);
Length of array PHP
$fruits = array("banana", "apple", "orange");
echo count($fruits);
For loop php
<?php
    for ($i = 0; $i <= 3; $i++) {
        echo "Loop counter is : " . $i;
    }
?>
Get link parameters from link
echo $_SERVER['QUERY_STRING'];
Split string in PHP
<?php
    $str = "Make the world a better place";
    $parts = explode(' ', $str);
?>
Select first n words of a sentence in PHP
<?php
    $n = 10; //HOW MANY WORDS YOU WANT
    $first_n_words = implode(' ', array_slice(explode(' ', $sentence), 0, $n));

    //TO ADD SUPPORT FOR WROD BREAK AND COMMAS
    function get_n_words($sentence, $count = $n) {
        preg_match("/(?:\w+(?:\W+|$)){0,$count}/", $sentence, $matches);
        return $matches[0];
    }
?>
Allow CORS in PHP
<?php
    header("Access-Control-Allow-Origin: *");
?>
Set HTTP response code in php
<?php
    $status_code = 201;
    http_response_code($status_code);
?>
Encode html special characters and real escape string in php
<?php
    $fullname = trim($_POST['name']);
    $fullname = htmlspecialchars($fullname);
    $fullname = $conn->real_escape_string($fullname);
?>
Web crawler in PHP
<?php 
$start = "http://localhost/se_india/test.html";
$pdo = new PDO('mysql:host=127.0.0.1;dbname=seindia','root','');
$already_crawled = array();
$crawling = array();
function get_details($url){
    $options = array('http'=>array('method'=>"GET",'headers'=>"User-Agent: Botman/0.1\n"));
    $context = stream_context_create($options);
    $doc =  new DOMDocument();
    @$doc ->loadHTML(@file_get_contents($url,false,$context));
    $title = $doc->getElementsByTagName("title");
    $title = $title ->item(0)->nodeValue;
    $description ="";
    $keywords="";
    $metas = $doc ->getElementsByTagName("meta");
    for ($i = 0; $i<$metas->length;$i++){
        $meta =$metas->item($i);
        if(strtolower($meta->getAttribute("name"))=="description")
            $description = $meta->getAttribute("content");
        if(strtolower($meta->getAttribute("name"))=="keywords")
            $keywords = $meta->getAttribute("content");
    }
    return '{ " Title " : " ' .str_replace( " \n " , "" , $title ).' "," Description " : " ' .str_replace( " \n " , "" , $description ).' "," Keywords " : " ' .str_replace( " \n " , "" , $keywords ).' ","URL":" ' .$url. ' "}';
}
function  follow_links($url){
    global $already_crawled;
    global $crawling;
    $options = array('http'=>array('method'=>"GET",'headers'=>"User-Agent: Botman/0.1\n"));
    $context = stream_context_create($options);
    $doc =  new DOMDocument();
    @$doc ->loadHTML(@file_get_contents($url,false,$context));
    $linklist = $doc->getElementsByTagName("a");
    foreach ($linklist as $link){
        $l =  $link->getAttribute("href");
        if (substr($l,0,1)=="/"&&substr($i,0,2)=="//"){
                $l = parse_url($url)["scheme"]. " :// ". parse_url($url)["host"].$l;
        }else if(substr($l,0,2) == "//"){
                $l = parse_url($url)["scheme"].":".$l;
        }else if(substr($l,0,2)=="./"){
                $l = parse_url($url)["scheme"]."://".parse_url($url)["host"].dirname(parse_url($url)["path"]).substr($l,1);
        }else if (substr($l,0,1)=="#"){
                $l = parse_url($url)["scheme"]."://".parse_url($url)["host"].parse_url($url)["path"].$l;
        }else if(substr($l,0,3)=="../"){
                $l = parse_url($url)["scheme"]."://".parse_url($url)["host"]."/".$l;
        }else if (substr($l,0,11)=="javascript:"){
            continue;
        }else if (substr($l,0,1)=="https" && substr($l,0,1)=="http"){
            $l = parse_url($url)["scheme"]."://".parse_url($url)["host"]."/".$l;
        }
        if(!in_array($l,$already_crawled)){
            $already_crawled[] = $l;
            $crawling[]=$l;
            $details = json_decode(get_details($l));
            print_r($details)."\n";
            // echo get_details($l)."\n";
        }
    }
    array_shift($crawling);
    foreach($crawling as $site){
        follow_links($site);
    }
}
follow_links($start);
?>
BackEndCode
<?php
echo "welcome developer";
?>
Get and set cookie in PHP
setcookie(name, value, expire, path, domain, secure, httponly);

setcookie("CookieName", "CookieValue", 2147483647, "/"); //SET COOKIE THAT EXPIRES IN 2038

print($_COOKIE["CookieName"]); //USER FOR GETTING COOKIE
Convert HTML code to plain text in PHP
<?php
    $html_code = '<p>Hello world</p>'
    echo strip_tags($html_code);
?>
Install composer for php
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('sha384', 'composer-setup.php') === 'a5c698ffe4b8e849a443b120cd5ba38043260d5c4023dbf93e1558871f1f07f58274fc6f4c93bcfd858c6bd0775cd8d1') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"

//IF Getting ERROR Please refer
https://getcomposer.org/download/
Return JSON from a PHP script
<?php
    // set header
    header('Content-Type: application/json'); 

    // create a php array
    $myarr = [
        [ "id" => 1, "name" => "Math" ],
        [ "id" => 1, "name" => "physics" ],
        [ "id" => 1, "name" => "Chemistry" ]
    ];

    // convert to json and print
    echo json_encode($myarr);
?>
nl2br() function in PHP
<?php
   echo nl2br("First line.\nSecond line.\nThird Line");
?>
Calculate length of a string using strlen() function in php
<?php
   $str_len = strlen("foobar");

   echo $str_len;
   
   // -> 6
?>
Check empty string in PHP
<?php
   if (empty($str)) {
      echo "String is empty";
   } else {
      echo "String is not empty"
   }
?>
Convert characters to lowercase using strtolower() function in PHP
<?php
   echo strtolower("WORLD IS BEAUTIFUL");
?>