<?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;
?>
<?php
$str = "hello world";
$res = ucwords($str);
echo $res;
?>
<?php
echo ucfirst("we are programmers");
// -> We are programmers
?>
<?php
echo lcfirst("Foo bar");
// -> foo bar
?>
<?php
echo strtoupper("We are ProgRammers");
// -> WE ARE PROGRAMMERS
?>
<?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'];
}
?>
<?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();
?>
<?php
$my_arr = ["James", "Stark", "Suart", "Rajesh", "Troy"];
$rand_index = array_rand($my_arr, 1);
echo $my_arr[$rand_index];
?>
<script> document.cookie = "js_var_value = " + localStorage.value </script>
<?php
$php_var_val= $_COOKIE['js_var_value'];
echo $php_var_val;
?>
<?php
if (strpos("Hello World", "Wor") != false) {
echo "Substring found";
} else {
echo "Substring not found";
}
?>
<?php
$values = $_POST['checbox_name'];
foreach ($values as $val){
echo $val;
}
?>
<?php
// Define a string
$my_str = "30";
// Convert to integer value
$val = (int)$my_str;
echo $val;
?>
<?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;
?>
<?php
echo 'Data 1 is here' . PHP_EOL;
echo 'Data 2 is here' . PHP_EOL;
?>
<?php
// Add this on the top of your PHP script
ini_set('display_errors', 1);
error_reporting(E_ALL);
?>
<?php
$ip_address = "168.0.0.1";
if (filter_var($ip_address, FILTER_VALIDATE_IP) == true) {
echo("Valid IP");
} else {
echo("Invalid Ip");
}
?>
<?php
$value = 500;
if (!filter_var($value, FILTER_VALIDATE_INT) === false) {
echo("Value is valid");
} else {
echo("Value is invalid");
}
// -> Value is valid
?>
<?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);
?>
<?php
$name = "world";
echo "Hello $name";
//-> Hello World
$arr = [
'name' => 'John'
];
echo "My Name is '{$arr["name"]}'";
//-> My Name is 'John'
?>
<?php
$str1 = "We are ";
$str2 = "Devsheet ";
$str3 = "Programmers";
$result1 = $str1 . $str2;
//-> We are Devsheet
$result2 = $str1 . $str2 . $str3;
//-> We are Devsheet Programmers
?>
<?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;
?>
<?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.";
}
?>
<?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
?>
<?php
$txtStr = "hello world";
echo ucfirst($txtStr);
//prints - Hello world
?>
<?php
$date_str = "10-01-2021";
$full_date= strtotime($date_str);
echo date('d F Y', $full_date);
//PRINT- 10 January 2021
?>
<?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();
?>
<?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
?>
<?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";
?>
<?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);
?>
<?php
//IN CHUNKS OF 2
$subjects = array("Math","Physics","Chemistry","English");
print_r(array_chunk($subjects,2));
?>
<?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"
];
?>
<?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";
}
?>
<?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}";
}
?>
<?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
?>
<?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);
?>
<?php
echo fmod(15, 5); //output - 0
echo fmod(15, 4); //output - 3
?>
<?php
$subjects = ["Math", "Physics", "Chemistry"];
unset($array[1]); //Remove Single Item(Physics) from array
array_splice($subjects, 1, 2); //Remove multiple items form array
?>
<?php
// create an array
$my_array = ["apple", "banana"];
// add new item "orange" to array
array_push($my_array, "orange");
print_r($my_array);
?>
<?php
function greeting($username) {
echo "Hello : " . $username;
}
greeting("John");
?>
<?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"];
}
?>
<?php
$type = "2";
switch($type) {
case "1":
echo "case 1";
break;
case "2":
echo "case 2";
break;
default:
break;
}
?>
<?php
$x = 10;
if ($x > 10) {
echo "Greater than 10";
} else if ($x < 10) {
echo "Less than 10";
} else {
echo "Equals to 10";
}
?>
<?php
define(const_name, const_value); //SYNTAX
define("month", "september");
?>
<?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
?>
<?php
$filePath = 'path/to/file';
unlink($filePath); //THIS FUNCTION DELETES THE FILE
?>
<?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
?>
<?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";
}
?>
<?php
$arr = ["1", "2", "3"];
echo count($arr);
?>
<?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);
?>
<?php
$file_path = "/path/to/file";
$file_content = file_get_contents($file_path);
echo $file_content;
?>
<?php
$filePath = "/path/to/file";
if (file_exists($filePath)) {
echo "file exists at the location";
} else {
echo "file does not exist";
}
?>
<?php
$last_id = $conn->insert_id;
?>
<?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);
}
?>
<?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>";
}
<?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();
}
<?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]);
}
}
<?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>
<?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
<?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');
<?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>";
}
}
?>
<?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
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]);
}
}
<?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;
}
}
<?php
header("Location: page_name.php"); //You can pass relative url of page or full url of page
exit();
?>
<?php
$globalVal = "I am a global variable";
function printVal() {
global $globalVal;
echo $globalVal;
}
printVal();
?>
<?php
$url = "https://remote-url-path/filename.jpg";
echo basename($url);
?>
<?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;
?>
<?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();
?>
<?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;
}
?>
$str = "Line number 1
Line number 2";
$str_parts = preg_split("/\r\n|\r|\n/", $str);
$fruits = array("banana", "apple", "orange");
echo count($fruits);
<?php
for ($i = 0; $i <= 3; $i++) {
echo "Loop counter is : " . $i;
}
?>
echo $_SERVER['QUERY_STRING'];
<?php
$str = "Make the world a better place";
$parts = explode(' ', $str);
?>
<?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];
}
?>
<?php
header("Access-Control-Allow-Origin: *");
?>
<?php
$status_code = 201;
http_response_code($status_code);
?>
<?php
$fullname = trim($_POST['name']);
$fullname = htmlspecialchars($fullname);
$fullname = $conn->real_escape_string($fullname);
?>
<?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);
?>
<?php
echo "welcome developer";
?>
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
<?php
$html_code = '<p>Hello world</p>'
echo strip_tags($html_code);
?>
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/
<?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);
?>
<?php
echo nl2br("First line.\nSecond line.\nThird Line");
?>
<?php
$str_len = strlen("foobar");
echo $str_len;
// -> 6
?>
<?php
if (empty($str)) {
echo "String is empty";
} else {
echo "String is not empty"
}
?>
<?php
echo strtolower("WORLD IS BEAUTIFUL");
?>