ππ£π§πππ‘ πΎπ€πππ§
Open in Telegram
1 876
Subscribers
No data24 hours
-37 days
-4230 days
Posts Archive
#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());
}
#basic
Commonly used operators in programming
Arithmetic Operators:
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (Remainder)
++ Increment
-- Decrement
Assignment Operators:
= Assignment
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
Comparison Operators:
== Equal to
!= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
Logical Operators:
&& Logical AND
|| Logical OR
! Logical NOT
Conditional (Ternary) Operator:
? Conditional expression
Delimiters:
() Parentheses
{} curly brackets
[] square brackets
<> Angle brackets
Comments:
// Single-line comment
/* */ Multi-line comment#js
Json Beautify Using Stringify
const data = { key1: 'value1', key2: 'value2' };
const jsonString = JSON.stringify(data, null, 2);
console.log(jsonString);
#mysql
Change Table property name using Mysql Command Line
ALTER TABLE
table_name CHANGE change_from change_to data_type CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL;
change_from = The property name change which want to update
change_to = The Property name which want to update with change_from
data_type = TEXT, varchar, INT
table_name = Table name of the DB#http
HTTP status codes along with their corresponding names:
100 Continue
101 Switching Protocols
102 Processing
200 OK
201 Created
202 Accepted
204 No Content
206 Partial Content
300 Multiple Choices
301 Moved Permanently
302 Found
304 Not Modified
307 Temporary Redirect
308 Permanent Redirect
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
405 Method Not Allowed
409 Conflict
410 Gone
429 Too Many Requests
500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable
504 Gateway Timeout
505 HTTP Version Not Supported
Docs: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#successful_responses
#py #flask
How to check headers property using flask
from flask import request
# check dict
uneeq_header = request.headers.get("uneeq",None)
if not uneeq_header:
print("uneeq property doesn't seems to be verified")
#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.';
}
#css
How to create gradient border along with border radius
.box{
--bg-color:#232425;
background:linear-gradient(var(--bg-color),var(--bg-color)) padding-box,linear-gradient(cyan, lightblue) border-box;
border:solid 1px transparent;
border-radius: 4px;
padding:10px 15px;
font-size:26px;
color:#fff;
width:150px;
text-align:center;
font-family:sans-serif;
}
HTML Code:
<div class="box">Gradient Border</div>
Important notes: --bg-color is variable to store the color hex, we are using padding-box and border-box to create border radius#css
How to create custom scroll bar using CSS
/* For WebKit based browsers */
::-webkit-scrollbar {
width: 3px; /* width of the scrollbar */
}
::-webkit-scrollbar-track {
background: #f1f1f1; /* color of the track */
}
::-webkit-scrollbar-thumb {
background: #303030; /* color of the thumb */
border-radius: 0; /* no border radius */
width: 3px; /* width of the thumb */
}
Important notes: "-webkit" based browsers requires such as chrome to work this code.
#python
How to handle error with exception in python
Python has try and except keywords it is similar as try catch and used to handle error.
Example code:
try:
# Code that may raise an exception or trigger an error
# Example 1: Raising a custom exception
if some_condition:
raise Exception("Custom exception message")
# Example 2: Triggering a specific error
if another_condition:
raise ValueError("Custom error message")
# Example 3: Catching and handling specific exception types
if yet_another_condition:
raise IndexError("Invalid index")
# Other code statements...
except Exception as e:
# Handle generic exceptions
print("Caught exception:", str(e))
except ValueError as ve:
# Handle specific exception types
print("Caught ValueError:", str(ve))
except IndexError as ie:
# Handle specific exception types
print("Caught IndexError:", str(ie))
#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
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
#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.
#js
Request module to handle requests in js
class Request {
static async post(url, payload = {}, headers = {}) {
try {
const response = await fetch(url, {
method: "POST",
headers,
body: JSON.stringify(payload)
});
if (!response.ok) {
throw new Error(
Request failed with status ${response.status});
}
return response;
} catch (error) {
throw new Error("Request failed due to a network error");
}
}
static async get(url, headers = {}) {
try {
const response = await fetch(url, {
method: "GET",
headers
});
if (!response.ok) {
throw new Error(Request failed with status ${response.status});
}
return response;
} catch (error) {
throw new Error("Request failed due to a network error");
}
}
}
// Usage example:
const url = "https://api.example.com/data";
const payload = { name: "John", age: 30 };
const headers = { "Authorization": "Bearer token" };
// POST request
Request.post(url, payload, headers)
.then(response => {
console.log(response.json());
})
.catch(error => {
console.error(error);
});
// GET request
Request.get(url, headers)
.then(response => {
console.log(response.json());
})
.catch(error => {
console.error(error);
});
Remember: if data does not return json response you need to set response.text() rather than response.json()#js
Make post and get request with headers in Plain js
async function request(url, method, dataType = "text", payload = {}, headers = {}) {
try {
const response = await fetch(url, {
method,
headers,
body: JSON.stringify(payload)
});
if (!response.ok) {
throw new Error(
Request failed with status ${response.status});
}
if (dataType === "json") {
return await response.json();
} else {
return await response.text();
}
} catch (error) {
throw new Error("Request failed due to a network error");
}
}
// Usage example:
try {
const response = await request("https://api.example.com/data", "get", "json", {}, { "Authorization": "Bearer token" });
console.log(response);
} catch (error) {
console.error(error);
}
Using asynchronous we need async event to prevent pending promise.#js
Prototype Function to validate number
String.prototype.isdigit = () =>{
return /^\d+$/.test(this);
};
// Usage:
var string = "56";
console.log(string.isdigit()); // Output: true
var string2 = "hello123";
console.log(string2.isdigit()); // Output: false
#scss
Usage of @mixin and its function in scss
@mixin button($background-color, $text-color) {
background-color: $background-color;
color: $text-color;
padding: 10px 20px;
border-radius: 5px;
}
.button-primary {
@include button(#ff0000, #ffffff);
}
.button-secondary {
@include button(#333, #ffffff);
}
#css
Gradient color text in Css
Css:
h1.logo {
background: linear-gradient(to right, #ff00ff, #00ffff);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
Html:
<h1 class="logo"> Hello </h1>
#php #htaccess
Prevent direct access files using .htaccess
<Files "*.txt">
Order deny,allow
Deny from all
</Files>
#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);
