نویسنده: AliBina

  • Create PDF in PHP Using FPDF.

    Create PDF in PHP Using FPDF.


    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:

     

     



    Source link

  • Angular Code Review Checklist. – PHPFOREVER

    Angular Code Review Checklist. – 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 Angular Code Review Checklist. - PHPFOREVER="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 Angular Code Review Checklist. - PHPFOREVER="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.



    Source link

  • How to Style Even and Odd Div.

    How to Style Even and Odd Div.


    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>

     

     



    Source link

  • Custom Pipe Example In Angular. Pipe example get month name.

    Custom Pipe Example In Angular. Pipe example get month name.


    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.



    Source link

  • how to generate qr code in angular.

    how to generate qr code in angular.


    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



    Source link

  • Top 10 PHP Security Best Practices.

    Top 10 PHP Security Best Practices.


    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' => "https://phpforever.com/",
    '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.



    Source link

  • Dynamic column chooser example to enhance web application

    Dynamic column chooser example to enhance web application


    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.



    Source link

  • VBA – A* Search Algorithm with Excel – Useful code


    Ok, so some 10 years ago, I was having fun coding A* Search Algorithms in Excel in VitoshAcademy and this is what I had built back then:

    VBA – A* search algorithm with Excel – Really?

    VBA – A Search Algorithm with VBA – Teil Zwei

    The second one is actually quite fun and I had forgotten about it. Today, I will present a third one, that has a few more features, namely the following:

    • It can be copied completely into a blank Excel’s VBA module, without any additional setup and it will work
    • You can choose for distance method (Manhattan or Heuristics)
    • You can choose for displaying or not calculations in Excel (
      writeScores = False )
    • You can
      ResetAndKeep() , which cleans out the maze, but keeps the obstacles
    • You can setup your own start and goal cell. By simply writing
      s and
      g , somewhere in the PLAYGROUND.
    • You can change the speed of writing in the Excel file, by changing the
      delay variable.

    These are the current commands:



    Source link

  • Fixing PHP Session Issues: Troubleshooting and Solutions.

    Fixing PHP Session Issues: Troubleshooting and Solutions.


    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



    Source link

  • Top 10 JavaScript Array Functions.

    Top 10 JavaScript Array Functions.


    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);
    

    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);
    

    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); 
    

    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.



    Source link