rajesh, Author at PHPFOREVER https://phpforever.com/author/rajesh/ PHP LARAVEL CODEIGNITER DATABASE JAVASCRIPT Sun, 25 Aug 2024 07:22:59 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.1 https://phpforever.com/wp-content/uploads/2020/06/cropped-PHP4EVER1-1-32x32.png rajesh, Author at PHPFOREVER https://phpforever.com/author/rajesh/ 32 32 Exploring PHP 8.3: Unveiling New Features For Enhanced Performance And Developer Productivity. https://phpforever.com/php/php-8-3-new-features/ Sun, 25 Aug 2024 07:20:22 +0000 https://phpforever.com/?p=4193 PHP 8.3 introduces several new features and improvements to enhance performance and the developer experience. Dive into the latest PHP 8.3 release and discover the new features set to revolutionize how developers build applications. From read-only properties to disjoint unions, learn how these enhancements can help you write more efficient and maintainable code while boosting …

The post Exploring PHP 8.3: Unveiling New Features For Enhanced Performance And Developer Productivity. appeared first on PHPFOREVER.

]]>
PHP 8.3 introduces several new features and improvements to enhance performance and the developer experience. Dive into the latest PHP 8.3 release and discover the new features set to revolutionize how developers build applications. From read-only properties to disjoint unions, learn how these enhancements can help you write more efficient and maintainable code while boosting overall performance.

Here are some of the most significant updates:

1. Readonly Properties for Classes.

  • Feature: PHP 8.3 introduces read-only properties that can only be assigned once, typically in the constructor.
  • Benefit: This enforces immutability for properties, which can help prevent accidental modifications and make the code easier to reason about.
  • Example
class User {
    public readonly string $name;

    public function __construct(string $name) {
        $this->name = $name;
    }
}

$user = new User("Alice");
// $user->name = "Bob"; // This will throw an error

  • Performance Impact: Immutable objects can lead to performance benefits by reducing the need for defensive copying and allowing for better optimization by the engine.

2. Disjoint Unions

  • Feature: PHP 8.3 introduces disjoint unions, allowing developers to declare that a property or return type can be of one type or another, but not a common subtype.
  • Benefit: This adds more precision in type declarations, improving type safety and reducing potential bugs.
  • Example
function process(mixed $input): int|string {
if (is_int($input)) {
return $input * 2;
}
if (is_string($input)) {
return strtoupper($input);
}
throw new InvalidArgumentException();
}

3. json_validate() Function

  • Feature: A new json_validate() function is introduced, which allows developers to check if a string contains valid JSON without decoding it.
  • Benefit: This is useful for validating large JSON strings without the overhead of decoding them.
  • Example
$jsonString = '{"name": "Alice", "age": 25}';
if (json_validate($jsonString)) {
echo "Valid JSON!";
} else {
echo "Invalid JSON!";
}

4. Typed Class Constants

  • Feature: PHP 8.3 allows class constants to have types, just like class properties.
  • Benefit: This feature enforces type safety for constants, reducing bugs caused by incorrect types.
  • Example
class Config {
public const int MAX_USERS = 100;
}

5. Improved Performance

  • JIT Improvements: PHP 8.3 includes enhancements to the Just-In-Time (JIT) compiler introduced in PHP 8.0. These improvements lead to faster execution of some workloads, especially those that are CPU-intensive.
  • Faster Hash Table Operations: Internal improvements have been made to how hash tables (the underlying structure for arrays and many other data structures) are handled, resulting in faster array operations and reduced memory usage.

6. Enhanced Error Reporting

  • Feature: Error reporting has been improved with more precise messages and additional context, helping developers diagnose issues faster.
  • Benefit: Better error messages lead to quicker debugging and a smoother development experience.

7. New Random\Engine  Class

  • Feature: PHP 8.3 introduces the Random\Engine class, which provides a standard way to generate random numbers using different engines.
  • Benefit: This adds more control over random number generation and allows for better customization, especially in cryptographic or statistical applications.
  • Example:
$engine = new Random\Engine\Mt19937();
$random = new Random\Randomizer($engine);
echo $random->getInt(1, 100); // Random number between 1 and 100

Conclusion

PHP 8.3 brings a mix of new features, performance improvements, and developer experience enhancements. These changes help developers write more robust, efficient, and maintainable code, while also taking advantage of performance optimizations under the hood. The introduction of readonly properties, disjoint unions, and typed class constants, along with improvements in JIT and error reporting, are particularly impactful in making PHP a more powerful and developer-friendly language.

The post Exploring PHP 8.3: Unveiling New Features For Enhanced Performance And Developer Productivity. appeared first on PHPFOREVER.

]]>
Top 10 JavaScript Array Functions. https://phpforever.com/javascript/top-ten-javascript-array-functions/ Wed, 14 Aug 2024 13:17:53 +0000 https://phpforever.com/?p=4171 Unlocking the Power of JavaScript: The Top 10 Array Functions You Need to Know. JavaScript, the language that breathes life into web pages, has a powerful array of functions that can transform your code into elegant, efficient, and concise masterpieces. Whether you’re a seasoned developer or just starting, mastering these functions will elevate your coding …

The post Top 10 JavaScript Array Functions. appeared first on PHPFOREVER.

]]>
Unlocking the Power of JavaScript: The Top 10 Array Functions You Need to Know.

JavaScript, the language that breathes life into web pages, has a powerful array of functions that can transform your code into elegant, efficient, and concise masterpieces. Whether you’re a seasoned developer or just starting, mastering these functions will elevate your coding skills and streamline your workflow.

In this blog post, we dive into the top 10 JavaScript array functions every developer should have in their toolkit. From transforming data with map() and filter() to perform complex operations reduce(), we’ll explore each function with examples and best practices. Join us on this journey as we unlock the potential of JavaScript arrays and take your coding abilities to the next level.

Here are the top 10 JavaScript array functions that are widely used due to their efficiency and versatility:

1. map():

  • Purpose: Creates a new array by applying a callback function to each element of the original array.
  • Example:
const numbers = [2, 3, 4, 5];
const squared = numbers.map(x => x * x);
console.log(squared);
// Output [4, 9, 16,25]

2. filter():

  • Purpose: Creates a new array with all elements that pass the test implemented by the provided callback function.
  • Example:
const numbers = [2, 3, 4, 5]; 
const evens = numbers.filter(x => x % 2 === 0);
console.log(squared);
// Output [2,4]

3.reduce():

  • Purpose: Executes a reducer function on each element of the array, resulting in a single output value.It integrate a whole array into a single value using a callback function.
  • Example:
const numbers = [2, 3, 4, 5]; 
const sum = numbers.reduce((total, num) => total + num, 0); 
console.log(sum); 
// Output 15

4.forEach():

  • Purpose: Executes a provided function once for each array element.
  • Example:
const numbers = [2, 3, 4, 5]; 
numbers.forEach(x => console.log(x));

5.find():

  • Purpose: Returns the value of the first element in the array that satisfies the provided testing function.
  • Example:
const numbers = [2, 3, 4, 5]; 
const firstEven = numbers.find(x => x % 2 === 0);
console.log(firstEven);
output: 2

6.some():

  • Purpose: Tests whether at least one element in the array passes the test implemented by the provided callback function. 
  • Example:
const numbers = [2, 3, 4, 5];
const hasEven = numbers.some(x => x % 2 === 0);
console.log(hasEven); output: true

7.every():

  • Purpose: Tests whether all elements in the array pass the test implemented by the provided function.
  • Example:
const numbers = [2, 3, 4, 5]; 
const allEven = numbers.every(x => x % 2 === 0);
console.log(allEven); output: false

8.includes():

  • Purpose: Determines whether an array includes a certain value among its entries, returning true or false as appropriate.
  • Example:
const numbers = [2, 3, 4, 5]; 
const hasNumber = numbers.includes(5);
console.log(hasNumber); output: false

9.push():

  • Purpose: Adds one or more elements to the end of an array and returns the new length of the array.
  • Example:
const numbers = [2, 3, 4, 5]; 
numbers.push(6);
console.log(hasNumber); output: [2, 3, 4, 5,6];

10.slice():

  • Purpose: Returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included).
  • Example:
const numbers = [2, 3, 4, 5]; 
const subArray = numbers.slice(1, 3); 

These functions are fundamental tools in JavaScript programming, enabling you to manipulate and traverse arrays effectively.

JavaScript Program To Check Whether a String is Palindrome or Not.      Binary Gap In Javascript.

The post Top 10 JavaScript Array Functions. appeared first on PHPFOREVER.

]]>
Fixing PHP Session Issues: Troubleshooting and Solutions. https://phpforever.com/php/fixing-php-session-issues-troubleshooting-and-solutions/ Sat, 10 Aug 2024 12:59:10 +0000 https://phpforever.com/?p=4159 PHP sessions are essential for maintaining state and user data across multiple pages in web applications. However, they can sometimes be tricky to manage. Drawing from my own experiences, I’ll share some troubleshooting steps and solutions to common PHP session issues. 1. Session Not Starting Properly Symptoms Sessions are not being created. $_SESSION variables are …

The post Fixing PHP Session Issues: Troubleshooting and Solutions. appeared first on PHPFOREVER.

]]>
PHP sessions are essential for maintaining state and user data across multiple pages in web applications. However, they can sometimes be tricky to manage. Drawing from my own experiences, I’ll share some troubleshooting steps and solutions to common PHP session issues.

1. Session Not Starting Properly

Symptoms
  • Sessions are not being created.
  • $_SESSION variables are not being saved.
Troubleshooting Steps
  1. Check session_start(): Ensure session_start() is called at the beginning of your script before any output is sent to the browser. This is a common oversight, and I’ve personally spent hours debugging a session issue only to find it was due to a missing session_start().
<?php
session_start();
?>

2.Output Buffering: Make sure no HTML or whitespace appears before session_start(). This can be a subtle issue, especially if multiple developers are working on the same project.

<?php
ob_start();
session_start();
// Your code
ob_end_flush();
?>

3. Check error_log: Look at the PHP error log for any session-related errors. This step often provides valuable insights into what might be going wrong.

Solutions
  • Always place session_start() at the very beginning of your script.
  • Use output buffering to prevent accidental output before sessions start.

2. Session Variables Not Persisting

Symptoms
  • Session variables reset on every page load.
  • Session data is not maintained across different pages.
Troubleshooting Steps
  1. Session Cookie Settings: Check if the session cookie is being set correctly. This can sometimes be overlooked in development environments where cookies are frequently cleared.
ini_set('session.cookie_lifetime', 0);

2. Browser Settings: Ensure cookies are enabled in the browser. I’ve had instances where a simple browser setting was the culprit behind persistent session issues.

3.Correct Session Variables: Ensure session variables are set correctly. Misconfigurations here can lead to confusing behavior.

<?php
session_start();
$_SESSION['username'] = 'user';
echo $_SESSION['username'];
?>
Solutions
  • Verify that session_start() is called on every page where session data is accessed.
  • Ensure consistent session settings across all scripts.

3. Session Expiring Too Soon

Symptoms
  • Sessions are expiring before the expected time.
  • Users are being logged out prematurely.
Troubleshooting Steps
  1. Session Timeout Settings: Check and adjust session.gc_maxlifetime and session.cookie_lifetime. In my experience, adjusting these settings can significantly improve user experience by keeping sessions active for the desired duration.
ini_set('session.gc_maxlifetime', 3600); // 1 hour
ini_set('session.cookie_lifetime', 3600);

2. Garbage Collection: Ensure session garbage collection is not overly aggressive. Fine-tuning this setting can prevent premature session deletions.

ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 100);
Solutions
  • Adjust session.gc_maxlifetime and session.cookie_lifetime to reasonable values.
  • Balance garbage collection settings to prevent premature session deletion.

4. Session Fixation

Symptoms
  • Security vulnerability where an attacker can fixate a session ID and hijack a user session.
Troubleshooting Steps
  1. Regenerate Session ID: Regenerate the session ID upon login or privilege change. This is a critical step in securing your application against session fixation attacks.
session_regenerate_id(true);

2. Set Session Cookie Securely: Use httponly and secure flags for session cookies. This helps in preventing session hijacking through XSS attacks.

ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_secure', 1);
Solutions
  • Always regenerate the session ID after login or significant changes in privileges.
  • Set the session cookie parameters to enhance security.

Upload Image In Angular With PHP

The post Fixing PHP Session Issues: Troubleshooting and Solutions. appeared first on PHPFOREVER.

]]>
Column Chooser Example In HTML And JavaScript https://phpforever.com/javascript/column-chooser-example-in-html-and-javascript/ Thu, 01 Aug 2024 11:34:13 +0000 https://phpforever.com/?p=4144 Dynamic Column Chooser Tutorial. Unlock the potential of your web applications with our comprehensive guide to implementing a dynamic column chooser. This blog post dives into the step-by-step process of building an interactive column selector using HTML, CSS, and JavaScript. Whether you’re looking to enhance the user experience by providing customizable table views or streamlining …

The post Column Chooser Example In HTML And JavaScript appeared first on PHPFOREVER.

]]>
Dynamic Column Chooser Tutorial.

Unlock the potential of your web applications with our comprehensive guide to implementing a dynamic column chooser. This blog post dives into the step-by-step process of building an interactive column selector using HTML, CSS, and JavaScript. Whether you’re looking to enhance the user experience by providing customizable table views or streamlining data presentation, our tutorial covers everything you need to know.

Explore the intricacies of:

  • Setting up a flexible and responsive HTML table structure.
  • Styling your table and column chooser for a clean, user-friendly interface.
  • Adding JavaScript functionality to toggle column visibility seamlessly.

With practical code examples and detailed explanations, you’ll be able to integrate a column chooser into your projects effortlessly. Perfect for web developers aiming to create user-centric solutions that cater to diverse needs and preferences. Elevate your web development skills and improve your application’s usability with this essential feature!

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Column Chooser Example</title>
    <style>
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            border: 1px solid black;
            padding: 8px;
            text-align: left;
        }
        .column-chooser {
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="column-chooser">
        <label><input type="checkbox" checked data-column="name"> Name</label>
        <label><input type="checkbox" checked data-column="age"> Age</label>
        <label><input type="checkbox" checked data-column="email"> Email</label>
    </div>
    <table>
        <thead>
            <tr>
                <th class="name">Name</th>
                <th class="age">Age</th>
                <th class="email">Email</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td class="name">John Doe</td>
                <td class="age">30</td>
                <td class="email">john@example.com</td>
            </tr>
            <tr>
                <td class="name">Jane Smith</td>
                <td class="age">25</td>
                <td class="email">jane@example.com</td>
            </tr>
        </tbody>
    </table>
    <script>
        document.querySelectorAll('.column-chooser input[type="checkbox"]').forEach(checkbox => {
            checkbox.addEventListener('change', (event) => {
                const columnClass = event.target.getAttribute('data-column');
                const isChecked = event.target.checked;
                document.querySelectorAll(`.${columnClass}`).forEach(cell => {
                    cell.style.display = isChecked ? '' : 'none';
                });
            });
        });
    </script>
</body>
</html>
Explanation:
  1. HTML Structure:
    • A div with the class column-chooser contains checkboxes for each column.
    • A table is defined with thead and tbody sections.
    • Each column and cell have a class corresponding to the column name (name, age, email).
  2. CSS:
    • Basic styling is applied to the table and its elements for readability.
  3. JavaScript:
    • Adds an event listener to each checkbox in the column chooser.
    • When a checkbox is toggled, the corresponding column cells are shown or hidden by changing their display style.

This example provides a simple, interactive way for users to choose which columns they want to display in a table. You can expand this by adding more functionality or integrating it into a larger application as needed.

 

Export HTML Table To PDF Using JSPDF Autotable.             Find the maximum value in an array in JavaScript.

The post Column Chooser Example In HTML And JavaScript appeared first on PHPFOREVER.

]]>
Top 10 PHP Security Best Practices. https://phpforever.com/php/php-security-best-practices/ Mon, 01 Jul 2024 17:16:19 +0000 https://phpforever.com/?p=4026 Top 10 PHP Security Best Practices. In today’s digital landscape, security is a paramount concern for developers and users alike. With the increasing sophistication of cyber threats, ensuring the security of web applications is more critical than ever. PHP, being one of the most widely used server-side scripting languages, powers millions of websites and applications. …

The post Top 10 PHP Security Best Practices. appeared first on PHPFOREVER.

]]>
Top 10 PHP Security Best Practices.

In today’s digital landscape, security is a paramount concern for developers and users alike. With the increasing sophistication of cyber threats, ensuring the security of web applications is more critical than ever. PHP, being one of the most widely used server-side scripting languages, powers millions of websites and applications. However, its popularity also makes it a prime target for attackers.

As a PHP developer, it is your responsibility to safeguard your applications and user data from potential threats. Whether you’re building a small personal project or a large-scale enterprise application, adhering to security best practices is essential. In this blog post, we will delve into the top PHP security best practices every developer should follow. From input validation and sanitization to secure session management and error handling, we’ll cover practical strategies to fortify your PHP applications against common vulnerabilities.

Join us as we explore these crucial practices, providing you with actionable insights and code snippets to enhance the security of your PHP projects. By the end of this post, you’ll have a solid understanding of implementing these best practices, ensuring your applications are robust, secure, and resilient against potential attacks. Let’s get started on the path to mastering PHP security!

Here are some top PHP security best practices for developers:

1. Input Validation and Sanitization
  • Validate Input: Always validate and sanitize all user inputs to prevent attacks such as SQL injection, XSS, and CSRF.
  • Use Built-in Functions: Use PHP functions like filter_var() to validate data, and htmlspecialchars() or htmlentities() to sanitize output.
2. Use Prepared Statements
  • SQL Injection Prevention: Always use prepared statements and parameterized queries with PDO or MySQLi to prevent SQL injection attacks.
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
$stmt->execute(['email' => $email]);
3. Cross-Site Scripting (XSS) Prevention
  • Escape Output: Escape all user-generated content before outputting it to the browser using htmlspecialchars().
  • Content Security Policy (CSP): Implement CSP headers to prevent the execution of malicious scripts.
4. Cross-Site Request Forgery (CSRF) Protection
  • Use CSRF Tokens: Include a unique token in each form submission and validate it on the server side.
// Generating a CSRF token
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));

// Including the token in a form
echo '';
5. Session Management
  • Secure Cookies: Use secure and HttpOnly flags for cookies to prevent XSS attacks.
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
'domain' => '',
'secure' => true, // Only send cookies over HTTPS
'httponly' => true, // Prevent access via JavaScript
'samesite' => 'Strict' // Prevent CSRF
]);
session_start();
  • Regenerate Session IDs: Regenerate session IDs frequently, particularly after login, to prevent session fixation.
session_regenerate_id(true);
6. Error Handling and Reporting
  • Disable Error Display: Do not display errors in production. Log errors to a file instead.
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', '/path/to/error.log');
7. Secure File Handling
  • File Uploads: Validate and sanitize file uploads. Restrict file types and ensure proper permissions are set on uploaded files.
$allowed_types = ['image/jpeg', 'image/png'];
if (!in_array($_FILES['file']['type'], $allowed_types)) {
die('File type not allowed');
}
8. Secure Configuration
  • Use HTTPS: Always use HTTPS to encrypt data transmitted between the client and server.
  • Secure Configuration Files: Restrict access to configuration files. Store sensitive information like database credentials securely.
9. Keep Software Updated
  • Update PHP and Libraries: Regularly update PHP, frameworks, and libraries to the latest versions to patch security vulnerabilities.
10. Use Security Headers
  • Set Security Headers: Use headers like X-Content-Type-Options, X-Frame-Options, X-XSS-Protection, and Strict-Transport-Security to enhance security.
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: SAMEORIGIN');
header('X-XSS-Protection: 1; mode=block');
header('Strict-Transport-Security: max-age=31536000; includeSubDomains');

 

By following these best practices, PHP developers can significantly enhance the security of their applications and protect against common vulnerabilities and attacks.

Ajax Live Search Example In PHP & MYSQL.

The post Top 10 PHP Security Best Practices. appeared first on PHPFOREVER.

]]>
How To Generate QR Code In Angular https://phpforever.com/angular/how-to-generate-qr-code-in-angular/ Fri, 28 Jun 2024 12:36:07 +0000 https://phpforever.com/?p=3992 How To Generate QR Code In Angular: In the modern digital era, QR codes have become essential for quickly sharing information through a simple scan. QR codes provide a versatile solution for marketing purposes, linking to a website, or sharing contact details. In this blog post, we’ll explore how to generate QR codes in your …

The post How To Generate QR Code In Angular appeared first on PHPFOREVER.

]]>
How To Generate QR Code In Angular:

In the modern digital era, QR codes have become essential for quickly sharing information through a simple scan. QR codes provide a versatile solution for marketing purposes, linking to a website, or sharing contact details. In this blog post, we’ll explore how to generate QR codes in your Angular applications using the angularx-qrcode library.

We’ll guide you through the installation process, show you how to integrate the library into your Angular project and provide a complete example to get you started. By the end of this tutorial, you’ll be able to create and customize QR codes effortlessly, adding an extra layer of interactivity and functionality to your applications. Perfect for developers of all levels, this step-by-step guide ensures you can implement QR code generation quickly and efficiently. Join us as we dive into the world of QR codes and enhance your Angular projects with this powerful feature!

Below are the steps to implement it.

Step 1: Set Up Your Angular Project.

If you don’t have an existing Angular project, create a new one using the Angular CLI:

ng new qr-code-app
cd qr-code-app
Step 2: Install angularx-qrcode
Install the angularx-qrcode library using npm:
npm install angularx-qrcode
Step 3: Create a Component and import the QRCodeModule.

 

import { Component } from '@angular/core';
import { MatFormFieldModule } from '@angular/material/form-field';
import { QrCodeModule } from 'ng-qrcode';


@Component({
  selector: 'app-qrcode',
  standalone: true,
  imports: [MatFormFieldModule,QrCodeModule],
  templateUrl: './qrcode.component.html',
  styleUrl: './qrcode.component.css'
})
export class QrcodeComponent {

  value: string = 'QRCODE Generator';
}
4. Update the QR Code Component.

 

<div class="container">   
    <h1>Generate QR Codes Example</h1>
    <qr-code value="{{value}}" size="300" errorCorrectionLevel="M"></qr-code>
</div>

5. Run the Application.
ng serve

Navigate to http://localhost:4200/ in your web browser. You should see a QR code generated based on the data provided.

Summary

  1. Set up your Angular project.
  2. Install the angularx-qrcode library.
  3. Import QRCodeModule in the imports section.
  4. Create a new component for the QR code.
  5. Update the component to generate and display the QR code.
  6. Run your application.

This setup allows you to generate and display QR codes in your Angular application easily.

Weather App In JavaScript                 Custom Pipe Example In Angular.

https://www.npmjs.com/package/angularx-qrcode

The post How To Generate QR Code In Angular appeared first on PHPFOREVER.

]]>
Custom Pipe Example In Angular. https://phpforever.com/angular/custom-pipe-example-in-angular/ Wed, 21 Feb 2024 16:28:43 +0000 https://phpforever.com/?p=3928 Custom Pipe Example In Angular. This tutorial will show you how to create an Angular Custom Pipe. It is handy if we want to reuse some logic across our applications. It allows us to change the format in which data is displayed on the pages. For instance, consider the date of birth as 01-01-2024 and …

The post Custom Pipe Example In Angular. appeared first on PHPFOREVER.

]]>
Custom Pipe Example In Angular.

This tutorial will show you how to create an Angular Custom Pipe. It is handy if we want to reuse some logic across our applications. It allows us to change the format in which data is displayed on the pages. For instance, consider the date of birth as 01-01-2024 and we want to display it as 01-January-2023. To achieve this we will make one pipe that can be used anywhere in our application. In angular

Types of Pipe.
  •  Pure Pipe.
  •  Impure pipes.
Pure Pipe.

The pure pipe is a pipe called when a pure change is detected in the value. It is called fewer times than the latter.

Impure Pipes.

This pipe is often called after every change detection. Be it a pure change or not, the impure pipe is called repeatedly.

Steps to Create Pipe

Below are the steps to create the custom pipe.

  1. Create a pipe class.
  2. Decorate the class with the @Pipe decorator.
  3. Give a pipe name under name metadata in @Pipe decorator.
  4. Implement the PipeTransform interface and it will contain only one method that is transform.
  5. The transform method must transform the value and return the result.
  6. Import the pipe class in the component.
  7. Use the custom pipe by its name in the HTML file.
Example.

Create a pipe class and add the below code.

import { Pipe,PipeTransform } from '@angular/core';

@Pipe({
    name: 'custompipe',
    standalone: true,
})

export class custompipePipe implements PipeTransform {

    monthNumbers:any = ['January','February','March','April','May','June','July','August','September','October','November','December'];
    transform(value: any) {
        let date = value.split(/[.,\/ -]/);
        if(date[1]>12 || date[1]<1 || isNaN(date[1])){
            return "Invalid Month";
        }else{
            date[1] = this.monthNumbers[date[1]-1];
            return date.join('-');
        }   
         
    }
}

Import the custom pipe in pipe-example.componenet.ts file and add the below code.

import { Component } from '@angular/core';
import { custompipePipe } from '../custompipe/custompipe.pipe';

@Component({
  selector: 'app-pipe-example',
  standalone: true,
  imports: [custompipePipe],
  templateUrl: './pipe-example.component.html',
  styleUrl: './pipe-example.component.css'
})

export class PipeExampleComponent{

  monthName:number = 0;
  ngOnIt(){

  }

  getMonthName(event:any){
    this.monthName = event.target.value;
  }
}

Add the below code in pipe-example.component.html file

 <input type="text" placeholder="Enter Month Name" (keyup)="getMonthName($event)" autofocus>    
Month Name: {{ monthName | custompipe}}

Input: 12-02-2023

Output: 12-February-2023

 

JavaScript Program To Count The Frequency Of Given Character In String.          Angular Dropdown With Search And Multi Select.

The post Custom Pipe Example In Angular. appeared first on PHPFOREVER.

]]>
How to Style Even and Odd Div. https://phpforever.com/css-example/how-to-style-even-and-odd-div/ Mon, 19 Feb 2024 11:21:13 +0000 https://phpforever.com/?p=3916 We can easily change the background color of div’s even and odd index using the:nth-child pseudo-class with the even and odd keywords, respectively. Odd and even are keywords that can be used to match child elements whose index is odd or even (the index of the first child is 1). Here, we specify two different …

The post How to Style Even and Odd Div. appeared first on PHPFOREVER.

]]>
We can easily change the background color of div’s even and odd index using the:nth-child pseudo-class with the even and odd keywords, respectively. Odd and even are keywords that can be used to match child elements whose index is odd or even (the index of the first child is 1). Here, we specify two different background colors for odd and even p elements.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>Even Odd Example</title>
    <style type="text/css">
    div :nth-child(even){
        background-color: yellow;
    }
    div :nth-child(odd){
        background-color: blue;
    }
    </style>
</head>
<body>
<div id="main">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
    <div>7</div>
    <div>8</div>
    <div>9</div>
    <div>10</div>
</div>	

</body>
</html>

 

 

The post How to Style Even and Odd Div. appeared first on PHPFOREVER.

]]>
Angular Code Review Checklist. https://phpforever.com/angular/angular-code-review-checklist/ Sat, 04 Nov 2023 05:55:33 +0000 https://phpforever.com/?p=3850 Introduction: Code review is a process where developers have their work reviewed by their peers to check the code’s quality and functionality. In the case of Angular, there are specific points that we must check to ensure code effectiveness, which we will be discussing in detail in our upcoming blog post. Effective code reviews are …

The post Angular Code Review Checklist. appeared first on PHPFOREVER.

]]>
Introduction:

Code review is a process where developers have their work reviewed by their peers to check the code’s quality and functionality. In the case of Angular, there are specific points that we must check to ensure code effectiveness, which we will be discussing in detail in our upcoming blog post. Effective code reviews are crucial to delivering high-quality applications to end-users. This process involves a peer review of developers’ work. The main aim of this evaluation is to detect any bugs, syntax issues, and other factors that could impact the application’s performance. However, code reviews can be time-consuming. Therefore, we have created a comprehensive list of the most crucial elements to consider during your Angular code reviews.

Imports Organization:

You should group your imports by source and arrange them alphabetically, which will help keep your import section organized and tidy.

Bad Code Example:
import { Component, OnInit, Input } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { AuthService } from '../services/auth.service';
import { BehaviorSubject, Observable, Subject, timer } from 'rxjs';
import { UserService } from '../services/user.service';
import { SomeOtherService } from '../services/some-other.service';
import { SomeComponent } from '../some-component/some-component.component';
import { AnotherComponent } from '../another-component/another-component.component';
import { SharedModule } from '../shared/shared.module';
import { ActivatedRoute, Router } from '@angular/router';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-component',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  // ...
}

 

Good Example (Organized imports order) 

// Organize Angular modules separately
import { Component, OnInit, Input } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { FormsModule } from '@angular/forms'; 


// Organize Rxjs imports separetly 
import { BehaviorSubject, Observable, Subject, timer } from 'rxjs';

// Organize services imports separetly
import { AuthService } from '../services/auth.service';
import { UserService } from '../services/user.service';
import { SomeOtherService } from '../services/some-other.service';

import { SomeComponent } from '../some-component/some-component.component';
import { AnotherComponent } from '../another-component/another-component.component';
Service Injection:

It is recommended to review dependency injection in components and utilize TypeScript’s access modifiers (public, private, etc.).

Bad Code Example:
@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
  // ...
 constructor(
    public dialog: MatDialog,
    authService: JobService,
    userService,
    public ref: ChangeDetectorRef,

  ) {
  }
}
Good Example (With private access modifier ):
@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
  // ...
 constructor(
    private dialog: MatDialog,
    private authService: JobService,
    private userService,
    private ref: ChangeDetectorRef,

  ) {
  }
}

 

Observable Cleanup:

Use the async pipe to simplify the component code instead of etching data with observables, doing the subscribe and cleanup in ngOnDestroy.

Bad Code Example:
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { DataService } from './data.service';

@Component({
  selector: 'app-data-list',
  template: `
    <h2>Data List</h2>
    <ul>
      <li *ngFor="let item of data">{{ item }}</li>
    </ul>
  `,
})
export class DataListComponent implements OnInit, OnDestroy {
  data: string[] = [];
  private dataSubscription: Subscription;

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.dataSubscription = this.dataService.getData().subscribe((result) => {
      this.data = result;
    });
  }

  ngOnDestroy() {
    if (this.dataSubscription) {
      this.dataSubscription.unsubscribe();
    }
  }
}
Good Example ( With async pipe):
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import { DataService } from './data.service';

@Component({
  selector: 'app-data-list',
  template: `
    <h2>Data List</h2>
    <ul>
      <li *ngFor="let item of data$ | async">{{ item }}</li>
    </ul>
  `,
})
export class DataListComponent {
  data$: Observable<string[]>;

  constructor(private dataService: DataService) {
    this.data$ = this.dataService.getData();
  }
}
Property Initialization:

It is considered a best practice to set default values for properties to prevent runtime errors.

Bad Code Example ():
import { Component } from '@angular/core';

@Component({
  selector: 'app-data-grid',
  template: `
    <!-- Data grid rendering code -->
  `,
})
export class DataGridComponent {
  data; // No initialization

  constructor() {
    // Imagine some logic to populate dataArray dynamically.
  }
}
Good Example:
import { Component } from '@angular/core';

@Component({
  selector: 'app-data-grid',
  template: `
    <!-- Data grid rendering code -->
  `,
})
export class DataGridComponent {
  data: any[] = []; // Initialize with an empty array

  constructor() {
    // Logic to populate dataArray dynamically.
  }
}

 

Component Initialization:

I recommend reviewing the ngOnInit  method, don’t make it too long. Try to break it into smaller methods for better readability and maintainability.

Bad Code Example :

import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-data-list',
  template: `
    <h2>Data List</h2>
    <ul>
      <li *ngFor="let item of data">{{ item }}</li>
    </ul>
  `,
})
export class DataListComponent implements OnInit {
  data: string[] = [];

  constructor(private dataService: DataService) {}

  ngOnInit() {
    // Fetch data from the service
    this.dataService.getData().subscribe((result) => {
      // Filter and transform the data
      const filteredData = result.filter((item) => item.length > 5);
      const transformedData = filteredData.map((item) => item.toUpperCase());

      // Sort the data
      transformedData.sort();

      // Set the component data
      this.data = transformedData;
    });
  }
}

Good Example (Breaking Down ngOnInit)

 

import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-data-list',
  template: `
    <h2>Data List</h2>
    <ul>
      <li *ngFor="let item of data">{{ item }}</li>
    </ul>
  `,
})
export class DataListComponent implements OnInit {
  data: string[] = [];

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.loadData();
  }

  private loadData() {
    this.dataService.getData().subscribe((result) => {
      const filteredData = this.filterData(result);
      const transformedData = this.transformData(filteredData);
      this.data = this.sortData(transformedData);
    });
  }

  private filterData(data: string[]): string[] {
    return data.filter((item) => item.length > 5);
  }

  private transformData(data: string[]): string[] {
    return data.map((item) => item.toUpperCase());
  }

  private sortData(data: string[]): string[] {
    return [...data].sort();
  }
}
Consider Extracting Logic to Services:

If a component logic can be reused in multiple places, we can extract it into services for better code organization and reusability.

Bad Code Example:

import { Component } from '@angular/core';
import { User } from './user.model'; // Assuming User model is imported

@Component({
  selector: 'app-user-management',
  template: `
    <h2>User Management</h2>
    <button [title]="generateTooltipForEditButton(currentUser)">Edit User</button>
  `,
})
export class UserManagementComponent {
  currentUser: User;

  constructor() {
    // Initialize the currentUser based on user data retrieval
    this.currentUser = this.getUser(/* specify user ID or other criteria */);
  }

  generateTooltipForEditButton(user: User): string {
    if (user) {
      if (user.state === 'SUSPENDED') {
        return 'This user is suspended and cannot be edited';
      } else if (user.state === 'INACTIVE') {
        return 'This user is inactive and cannot be edited';
      } else if (!user.authorizedToUpdate) {
        return 'You are not authorized to edit this user';
      } else {
        return 'Edit';
      }
    }
    return 'Edit';
  }

  // Simulated method to retrieve a user, replace with actual logic
  getUser(userId: number): User {
    return {
      id: userId,
      name: 'John Doe',
      state: 'ACTIVE',
      authorizedToUpdate: true,
    };
  }
}

 

Good Example:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class UserService {
  // Other user-related methods and properties
// move the component fucntion to the service 
  getEditUserButtonTooltip(user: User): string {
    if (user) {
      if (user.state === 'SUSPENDED') {
        return 'This user is suspended and cannot be edited';
      } else if (user.state === 'INACTIVE') {
        return 'This user is inactive and cannot be edited';
      } else if (!user.authorizedToUpdate) {
        return 'You are not authorized to edit this user';
      } else {
        return 'Edit';
      }
    }
    return 'Edit';
  }
}




import { Component } from '@angular/core';
import { UserService, User } from '../user.service';

@Component({
  selector: 'app-user-management',
  template: `
    <h2>User Management</h2>
    <button [title]="generateTooltipForEditButton(currentUser)">Edit User</button>
  `,
})
export class UserManagementComponent {
  currentUser: User;

  constructor(private userService: UserService) {
    // Initialize the currentUser based on user data retrieval
    this.currentUser = this.userService.getUser(/* specify user ID or other criteria */);
  }

  generateTooltipForEditButton(user: User): string {
    return this.userService.generateTooltipForEditButton(user);
  }
}
Hard-Coded Styles:

It’s important to avoid using inline styles as they can be difficult to maintain. Instead, it’s recommended to define appropriate styling classes.

Bad Example (Hard-Coded Styles in Template):

<!-- bad-example.component.html -->
<div>
  <h2 style="font-size: 24px; color: red;">Welcome to our website</h2>
  <p style="font-size: 18px; color: blue;">This is some text with hard-coded styles.</p>
  <button style="background-color: green; color: white;">Click me</button>
</div>

Good Example (Separate Styles in a CSS File) :

<!-- good-example.component.html -->
<div>
  <h2>Welcome to our website</h2>
  <p>This is some text with Angular-applied styles.</p>
  <button (click)="onButtonClick()">Click me</button>
</div>

/* styles.css or component-specific styles file */
h2 {
  font-size: 24px;
  color: red;
}

p {
  font-size: 18px;
  color: blue;
}

button {
  background-color: green;
  color: white;
}

 

Angular Dropdown With Search And Multi Select.   Quiz App In Angular.

The post Angular Code Review Checklist. appeared first on PHPFOREVER.

]]>
Create PDF in PHP Using FPDF. https://phpforever.com/php/create-pdf-in-php-using-fpdf/ Sun, 09 Jul 2023 14:40:47 +0000 https://phpforever.com/?p=3823 In this post, I  will explain how to create a pdf file in php. To create a PDF file in PHP we will use the FPDF library. It is a PHP library that is used to generate a PDF. FPDF is an open-source library. It is the best server-side PDF generation PHP library. It has …

The post Create PDF in PHP Using FPDF. appeared first on PHPFOREVER.

]]>
In this post, I  will explain how to create a pdf file in php. To create a PDF file in PHP we will use the FPDF library. It is a PHP library that is used to generate a PDF. FPDF is an open-source library. It is the best server-side PDF generation PHP library. It has rich features right from adding a PDF page to creating grids and more.

Example:

<?Php
require('fpdf/fpdf.php');
$pdf = new FPDF(); 
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(80,10,'Hello World From FPDF!');
$pdf->Output('test.pdf','I'); // Send to browser and display
?>

Output:

 

 

The post Create PDF in PHP Using FPDF. appeared first on PHPFOREVER.

]]>