𝙐𝙣𝙧𝙚𝙖𝙡 𝘾𝙤𝙙𝙚𝙧
1.64K subscribers
6 photos
7 files
34 links
A place for coders ;)
Download Telegram
#php
List Assignment in PHP

$string = "John|25";
[$name, $age] = explode("|", $string);
echo $name; // Output: John

PHP version >= 7.1

(If you are using older version then use list() construct )

$string = "John|25";
list($name, $age) = explode("|", $string);
echo $name; // Output: John
#php
Replace String In PHP

$string = "hola this is what what";

$newString = str_replace("what", "why why", $string);
echo $newString; // Output: "hola this is why why why why"
👍2
#php

Get length in PHP

1. Use strlen only with string

$string = "Hello";
$length = strlen($string);
echo $length; // Output: 5

2. Use count() when the value returns array or object

$array = [1, 2, 3, 4, 5];
$count = count($array);
echo $count; // Output: 5
#php
Trim string in PHP
using substr() function

$q = "hello this world";
$trimmed = substr($q, strpos($q, "this"));
echo $trimmed; // Output: "this world"
#php
Check a String either exist or not in Array
Using in_array() which return Boolean


function is_in_list($string, $array) {
return in_array($string, $array);
}

// Usage example:
$myArray = ["apple", "banana", "orange"];
$result = is_in_list("banana", $myArray);
echo $result ? "String exists in the array" : "String does not exist in the array";
#php

Make Json Prettify in PHP

json_encode is a function to convert an array into json

JSON_PRETTY_PRINT is used to make json prettify

$data = array(
'name' => 'John Doe',
'age' => 30,
'email' => 'johndoe@example.com'
);

$json = json_encode($data, JSON_PRETTY_PRINT);
echo $json;
#php
Usage of Array Filter in Php

$numbers = [1, 2, 3, 4, 5];

$filtered = array_filter($numbers, function($value) {
return $value % 2 == 0; // Filter even numbers
});

print_r($filtered);
#php #htaccess

Prevent direct access files using .htaccess

<Files "*.txt">
Order deny,allow
Deny from all
</Files>
#php #curl

Handle requests using Curl

class Request {
private $config = [];

public function __construct($config = []) {
$this->config = $config;
}

public function get($url) {
return $this->sendRequest($url, 'GET');
}

public function post($url, $headers = [], $payload = [], $store_cookies = true) {
return $this->sendRequest($url, 'POST', $headers, $payload, $store_cookies);
}

public function custom($url, $method, $headers = [], $payload = []) {
return $this->sendRequest($url, $method, $headers, $payload);
}

private function sendRequest($url, $method, $headers = [], $payload = [], $store_cookies = false) {
$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

// Add additional configuration options
foreach ($this->config as $option => $value) {
curl_setopt($curl, $option, $value);
}

if ($store_cookies) {
$cookieFile = tempnam(sys_get_temp_dir(), 'cookies');
curl_setopt($curl, CURLOPT_COOKIEFILE, $cookieFile);
curl_setopt($curl, CURLOPT_COOKIEJAR, $cookieFile);
}

if ($method === 'POST') {
curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
}

$response = curl_exec($curl);
$error = curl_error($curl);

curl_close($curl);

if ($error) {
throw new Exception("Request failed: " . $error);
}

return $response;
}
}

// Usage example:
$request = new Request(["timeout" => 300]);

$response = $request->get($url);
echo $response;

$response = $request->post($url, $headers, $payload, true);
echo $response;

$response = $request->custom($url, $method, $headers, $payload);
echo $response;


Remember notes: private is a keyword.

private $config;
private function uneeq(){
}

Whenever you use private keyword the the variables, functions will become private and you can't use these outside of the class.
👍1
#php

How to create class and define its keywords in Php

class Example {
private $privateProperty;
protected $protectedProperty;
public $publicProperty;

private function privateMethod() {
// Private method implementation
}

protected function protectedMethod() {
// Protected method implementation
}

public function publicMethod() {
// Public method implementation
}
}

// Usage example
$example = new Example();

// Accessing public property and method
$example->publicProperty = 'Public Property';
echo $example->publicProperty; // Output: Public Property
$example->publicMethod(); // Output: Public Method

// Trying to access private and protected members (results in an error)
$example->privateProperty = 'Private Property'; // Error: Cannot access private property
$example->protectedProperty = 'Protected Property'; // Error: Cannot access protected property
$example->privateMethod(); // Error: Cannot access private methods
$example->protectedMethod(); // Error: Cannot access protected method


Remember notes: public members have no access restrictions and can be accessed from anywhere.

protected members are accessible within the class where they are defined and also within its subclasses.

private: When a member is declared as private, it can only be accessed within the class where it is defined
1👍1
#php

How to handle error with exception in PHP

try {
// Code that may throw an exception or trigger an error

// Example 1: Throwing a custom exception
if ($someCondition) {
throw new Exception("Custom exception message");
}

// Example 2: Triggering a specific error
if ($anotherCondition) {
trigger_error("Custom error message", E_USER_ERROR);
}

// Example 3: Catching and handling specific exception types
if ($yetAnotherCondition) {
throw new InvalidArgumentException("Invalid argument");
}

// Other code statements...

} catch (Exception $e) {
// Handle generic exceptions
echo "Caught exception: " . $e->getMessage();
} catch (Error $e) {
// Handle errors
echo "Caught error: " . $e->getMessage();
} catch (InvalidArgumentException $e) {
// Handle specific exception types
echo "Caught invalid argument exception: " . $e->getMessage();
}

Important notes:
Try catch is the way to capture error in most of programming language:

try{

//Your code

}catch(Exception $e){
// Error will store in $e if your code has error
}
#php
Create custom header property

$customProperty = $_SERVER['HTTP_X_CUSTOM_PROPERTY'];

// Verify the custom property
if ($customProperty === 'your_expected_value') {
// Request is verified
echo 'Request verified.';
} else {
// Request is not verified
http_response_code(401);
echo 'Request not verified.';
}
#php #ci4

Example code to validate rules for form submission in Codeigniter

$validation = \Config\Services::validation();

// Set the validation rules
$validation->setRules([
'username' => 'required|min_length[5]',
'email' => 'required|valid_email',
'password' => 'required|min_length[8]',
]);

// Run the validation
if (!$validation->withRequest($this->request)->run()) {
// Validation failed, redirect back with errors
return redirect()->back()->withInput()->with('errors', $validation->getErrors());
}
#bestPractice #php #js #py
Join an array into String in (PHP, JS, PY)

Bad practice:
//python
print("a" + " " + "b)

//php
echo "a"." ".b";

Best Practice:
// js
console.log(["a", "b"].join(" "));

//python
print(" ".join(["a", "b"])

//php
echo implode(" ", ["a", "b"]);
How to merge 2 or many json dict into One in (Python, PHP, JS)

#js
var b = { success:true }
var c = { message: "something", ...b }
console.log(c)


Usage: Use "var" keyword to re assign the variable and use spread method to merge "...json object "

#php
$b = [ "success"=> true ];
$c = ["biswa":"string"];
array_merge($b, $c)

Usage: array_merge used to merge arrays into one array and we need use json_decode and json_encode to make a json obj

#py

Best way to merge in python is using unpacking operator **dict_name here is example:

b = { "success":True }
c = { "hell":None}
print({**b, **c})
😱7😢5🤮4💩4😁3🤬3👎2🤔2👍1🔥1🤯1
Create Pretty URL with any PHP file

create a rule for .htaccess
RewriteEngine On
RewriteRule ^post/([a-zA-Z0-9_-]+)/?$ post.php?id=$1 [L,QSA]


Now you can access:
 /post.php?id=123


To
/post/123/

To access its ID parameter, use $_GET['id']

coded By @BiswaX

#PHP #HTACCESS
👍8🔥2