نویسنده: AliBina

  • 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

  • PHP 8.3 new features

    PHP 8.3 new features


    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.



    Source link

  • Rule of 72 – Useful code

    Rule of 72 – Useful code


    Ever heard of the Rule of 72? It’s a classic finance shortcut that tells you how many years it takes for an investment to double at a given interest rate—without reaching for a calculator! Pretty much, if you want to understand when you are going to double your money, that are growing with 7% per year, then simply divide 72 by 7 and see the approximate answer. It works like that and it is approximately ok, for values between 5 and 10%.

    For all other values, the formula looks like this:

    ln(2) is approximately 0.693. Hence, it is 0.693 divided by ln(1+tiny percentage).

    With Python the formula looks like this:

    If you want to see how exact the formula is, then a good comparison vs the exact value looks like this:

    The execution of the code from above like this:

    The YT video, explaining the code and is here:

    https://www.youtube.com/watch?v=BURstTrQWkA

    The GitHub code is here: https://github.com/Vitosh/Python_personal/tree/master/YouTube/023_Python-Rule-of-72

    A nice picture from Polovrak Peak, Bulgaria

    Enjoy!



    Source link

  • Rules of 114 and 144 – Useful code


    The Rule of 114 is a quick way to estimate how long it will take to triple your money with compound interest.  The idea is simple: divide 114 by the annual interest rate (in %), and you will get an approximate answer in years.

    • If you earn 10% annually, the time to triple your money is approximately: 114/10=11.4 years.

    Similarly, the Rule of 144 works for quadrupling your money. Divide 144 by the annual interest rate to estimate the time.

    • At 10% annual growth, the time to quadruple your money is: 144/10=14.4 years

    Why Do These Rules Work?

    These rules are approximations based on the exponential nature of compound interest. While they are not perfectly accurate for all rates, they are great for quick mental math, especially for interest rates in the 5–15% range. While the rules are convenient, always use the exact formula when accuracy matters!

    Exact Formulas?

    For precise calculations, use the exact formula based on logarithms:

    • To triple your money:
    • To quadruple your money:

    These rules for 4x or 3x can be summarized with the following python formula:

    Generally, these rules are explained a bit into more details in the video, below:

    https://www.youtube.com/watch?v=iDcPdcKi-oI

    The GitHub repository is here: https://github.com/Vitosh/Python_personal/tree/master/YouTube/024_Python-Rule-of-114

    Enjoy it! 🙂



    Source link

  • Trigonometric Functions – Sine – Useful code


    import numpy as np

    import matplotlib.pyplot as plt

    import matplotlib.animation as animation

     

    # Generate unit circle points

    theta = np.linspace(0, 2 * np.pi, 1000)

    x_circle = np.cos(theta)

    y_circle = np.sin(theta)

     

    # Initialize figure

    fig, ax = plt.subplots(figsize=(8, 8))

    ax.plot(x_circle, y_circle, ‘b-‘, label=“Unit Circle”)  # Unit circle

    ax.axhline(0, color=“gray”, linestyle=“dotted”)

    ax.axvline(0, color=“gray”, linestyle=“dotted”)

     

    # Add dynamic triangle components

    triangle_line, = ax.plot([], [], ‘r-‘, linewidth=2, label=“Triangle Sides”)

    point, = ax.plot([], [], ‘ro’)  # Moving point on the circle

     

    # Text for dynamic values

    dynamic_text = ax.text(0.03, 0.03, “”, fontsize=12, color=“black”, ha=“left”, transform=ax.transAxes)

     

    # Set up axis limits and labels

    ax.set_xlim(1.2, 1.2)

    ax.set_ylim(1.2, 1.2)

    ax.set_title(“Sine as a Triangle on the Unit Circle”, fontsize=14)

    ax.set_xlabel(“cos(θ)”, fontsize=12)

    ax.set_ylabel(“sin(θ)”, fontsize=12)

    ax.legend(loc=“upper left”)

     

    # Animation update function

    def update(frame):

        angle = theta[frame]

        x_point = np.cos(angle)

        y_point = np.sin(angle)

        degrees = np.degrees(angle) % 360  # Convert radians to degrees

        

        # Update triangle

        triangle_line.set_data([0, x_point, x_point, 0], [0, y_point, 0, 0])

        

        # Update point on the circle

        point.set_data([x_point], [y_point])  # Fixed this line to avoid the warning

        

        # Update text for angle, opposite side length, and sin(θ)

        dynamic_text.set_text(f“Angle: {degrees:.1f}°\nOpposite Side Length: {y_point:.2f}\nsin(θ): {y_point:.2f}”)

        return triangle_line, point, dynamic_text

     

    # Create animation

    ani = animation.FuncAnimation(fig, update, frames=len(theta), interval=20, blit=True)

    plt.show()



    Source link

  • Sine and Cosine – A friendly guide to the unit circle



    Welcome to the world of sine and cosine! These two functions are the backbone of trigonometry, and they’re much simpler than they seem. In this article, we will explore the unit circle, the home of sine and cosine, and learn





    Source link