Using fibers with PHP <8.4? [closed]

I am looking into PHP fibers. I read that to use fibers it’s a good idea to have PHP 8.4 but my servers will only support partially 8.1 and partially 8.3 for some time ahead.

Question: Are the changes to fibers in 8.4 so significant that you would advise against using them when not having access to PHP 8.4?

I want to access my static video files with expire time

I want to access my static video files with expire time the video file will only work when it have valid token and expire time.

function generateSignedUrl($file, $secret, $expiry) {
    $md5 = md5($file . $expiry . $secret);
    return "https://example.com/files/$file?md5=$md5&expires=$expiry";
}
$file = "sample-file.mp4";
$secret = "secret-key";
$expiry = time() + 3600;

$signedUrl = generateSignedUrl($file, $secret, $expiry);
echo "Signed URL: $signedUrl";

i try to control it using .htaccess but it not working here is my htaccess code.

RewriteEngine On
RewriteCond %{QUERY_STRING} (^|&)md5=([^&]+) [NC]
RewriteCond %{QUERY_STRING} (^|&)expires=([0-9]+) [NC]
RewriteCond %{TIME} >%3
RewriteRule ^files/(.*)$ - [F]
RewriteCond %{QUERY_STRING} (^|&)md5=([^&]+) [NC]
RewriteCond %{QUERY_STRING} (^|&)expires=([0-9]+) [NC]
RewriteCond %{REQUEST_URI} (.*) [NC]
RewriteCond %{ENV:SECURE_KEY} (secret-key) [NC]
RewriteCond %{QUERY_STRING} (^|&)md5=%{ENV:CALC_MD5} [NC]
RewriteRule ^files/(.*)$ /files/$1 [L]
RewriteCond %{QUERY_STRING} !(md5=.+&expires=.+) [NC]
RewriteRule ^files/ - [F]

i need that url will only work when it was access like this https://example.com/files/sample-file.mp4?md5=545f27b2a8b719c6ed87b1db624b1eb5&expires=1737717458 if someone try to access directly it with return 403 https://example.com/files/sample-file.mp4 this will not work.

Storing app secret key in database, smart move, over-engineering, or dump act? [closed]

I am building a backend application with some basic user authentication mechanisms, so I did what most would: creating a .env file, putting APP_SECRET inside, and having the application load from it.

Now, since I also have a database dedicated to this application, it should be feasible to store that APP_SECRET inside the database (It could be a table with just one column and one row storing the value) and have the application load from it on start.

Although I’ll still have to supply DB connection credentials via the .env file, so it won’t go anywhere, at least I have one less thing to put inside now.

The question is: Is this a legitimate move? Does this paradigm have any security concerns? Is there a better alternative if I don’t like to generate APP_SECRET and put them in .env?

How to parse DIVI theme row page content to html code

I need to parse the page and post content created using the DIVI theme’s drag-and-drop elements. My goal is to export this content to a Strapi website. To achieve this, I want to convert the DIVI theme’s page and post layouts into HTML code, which can then be used in Strapi.

How to test and what should be tested for CommandHandler in CQRS?

I have a bunch of handlers. Every of them, eventually, contains code for saving data and releasing events.

How to test CommandHandler? What should be tested? For now it is unit tests, maybe it should be integrational? Should I mock anything or not? Why? Should it be tested at all?

Code of handlers:

public function __invoke(AddCategory $command): int
{
    // some code

    $this->categories->save($category);
    $this->events->publishAll($category->releaseEvents());

    return $category->id()->value;
}

public function __invoke(RenameCategory $command): void
{
    // some code

    $this->categories->save($category);
    $this->events->publishAll($category->releaseEvents());
}

At the moment my tests look like that:

Test addition

protected function setUp(): void
{
    $this->categories = new TestCategoryRepository();
    $this->events     = new TestEventDispatcher();
    $this->handler    = new AddCategoryHandler($this->categories, $this->events);
}

public function testHandler(): void
{
    // preparing code

    ($this->handler)($command);

    $this->assertTrue($currentEventsCountMoreThanInitialEventsCount);
    $this->assertTrue($currentRepositoryCountMoreThanInitialRepositoryCount);
    $this->assertIsInt($categoryId);
    $this->assertNotNull($category);
}

Test some changes:

protected function setUp(): void
{
    $this->categories = $this->createMock(CategoryRepository::class);
    $this->events     = new TestEventDispatcher();
    $this->handler    = new RenameCategoryHandler($this->categories, $this->events);
}

public function testHandler(): void
{
    // preparing code

    $this->categories->expects($this->once())
                     ->method('getById')
                     ->with($categoryId)
                     ->willReturn($category);

    $this->categories->expects($this->once())->method('save');

    ($this->handler)($command);

    $this->assertTrue($currentEventsCountMoreThanInitialEventsCount);
}

Integrate 2FA with Twilio in Laravel [closed]

I have a PHP Laravel backend application that uses the Passport package for authentication. I want to integrate Two-Factor Authentication (2FA) using Twilio into the login flow.

The issue I’m facing is that the /oauth/token API in Laravel Passport automatically creates an access token and authenticates the user as soon as valid credentials are provided. Because of this, there’s no opportunity to introduce a 2FA step before the token is issued.

My goal is to:

  1. Validate the user’s credentials (email and password).
  2. If 2FA is enabled for the user, send a verification code via Twilio and require the user to verify it.
  3. Issue the access token only after the 2FA verification is successfully completed.

How can I modify or extend the Passport authentication flow to achieve this? Any guidance or examples would be greatly appreciated!

How to distinguish between syntax error and deadlock or connection error? [duplicate]

I try to upgrade my PDOException handling code to retry on error when it makes sense. For this I need to distinguish between syntax error and deadlock, connection error, etc. I tried to find the PDOException error codes to be able to do so, but I had no luck. Did any of you manage to distinguish between these errors?

My current scenario that I have a transaction in a cron which inserts or updates a table and another transaction that deletes from the same table when there is user interaction. I got a deadlock a few times a week. My current code just logs the PDOException and keeps doing its work, but it is pointless when the entire transaction is gone. I want to retry in these cases and only in the case of syntax or out of range parameter error I want to ignore it and keep working and commit the transaction. How do you check the type of the PDOException in your code?

Prevent json_decode from Converting Unicode Escaped Characters (e.g., u003C to <) in PHP

I’m working with a JSON string that contains Unicode-escaped characters, such as u003C, and I want to decode the JSON into an associative array without converting these Unicode characters to their literal equivalents (e.g., u003C should stay as it is and not convert to <).

Here’s a simplified example of my JSON and code:

 // Original JSON string
    $json = '{"Code_Injecting":{"Code":"u003Cstyleu003E div#example { display: none; }u003C/styleu003E"}, "RemoveKey":"removeValue"}';
   

// Step 1: Decode JSON to an array
$array = json_decode($json, true);

// Check if decoding was successful
if (json_last_error() !== JSON_ERROR_NONE) {
    die('Error decoding JSON: ' . json_last_error_msg());
}

// Step 2: Unset the key "Code_Injecting" if it exists
if (isset($array['Code_Injecting'])) {
    unset($array['Code_Injecting']);
}

// Step 3: Encode it back to JSON while preserving Unicode-escaped characters
$newJson = json_encode($array, JSON_UNESCAPED_SLASHES);

// Output the final JSON
echo $newJson;

// Expected Output:
// {"Code_Injecting":{"Code":"u003Cstyleu003E div#example { display: none; }u003C/styleu003E"}}

I need the Unicode-escaped characters (like u003C) to remain unchanged when decoding JSON. Is there a way to achieve this in PHP?

I’ve tried looking into JSON_UNESCAPED_UNICODE during encoding but didn’t find an equivalent for decoding. Any help or suggestions would be appreciated!

Why is POST Request Being Interpreted as a GET Request?

I am working on a project where my React frontend sends a POST request to a PHP backend using Axios. However, on the server-side, $_SERVER[‘REQUEST_METHOD’] consistently indicates that the request is a GET, even though I am using the POST method in Axios.

Front-end with react

const handle_submit = async (event) => {
  event.preventDefault();
  try {
    const axios_response = await axios.post(
      'http://localhost/deletable/tutorial/vite-project/php_backend/index.php',
      { firstname, lastname, email, password, enrollment_year, dob, is_note_sharer },
      { headers: { 'Content-Type': 'application/json' } }
    );
    console.log('axios_response', axios_response);
  } catch (error) {
    console.error('Error submitting data', error);
  }
};

PHP Backend

header('Access-Control-Allow-Origin: http://localhost:5173');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Credentials: true');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'));
    echo json_encode(['status' => 'success', 'data' => $data]);
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
}

Issue:
Despite using POST in the Axios request, $_SERVER[‘REQUEST_METHOD’] in PHP evaluates to GET. I have also tried adding Access-Control-Allow-Methods: POST in the PHP headers, but the issue persists.

Additional Info:
The frontend is running on http://localhost:5173.
The backend is served from http://localhost.
CORS headers have been added to the PHP file.
No network errors are observed in the browser’s developer tools.
Question:
What could be causing the PHP backend to treat the POST request as a GET, and how can I resolve this issue?

read protected json file from https server [closed]

I need to read json file from https server. Json file can only be read after logging into the server. And this server login with 3 parameter username , password and client id.

I tried curl to login but it’s always saying “please login”.

What procedure I need to follow?

How do i Use Php in order to display image from the path on Xamp server under image folder? [closed]

I have a column and its fetching all the fields from the table fine, the issue is picking up the image as per course name is not shown and need some help as to how to display these images on each course name as per table.

How do i make a select column to allow a user to click as per course_name?

//php code

<!-- BOOKING COURSES -->
<div class="udb-sec udb-cour">
    <h4><img src="images/icon/db2.png" alt="" /> Booking Courses</h4>
    <p>The courses available for booking or registration by the student.</p>
    <form action="register_course.php" method="POST">
        <div class="sdb-cours">
        <?php
include 'db_connection.php'; // Include the database connection

// Check if the user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: index.html");
    exit;
}

$user_id = $_SESSION['user_id']; // Get the user ID from the session

// Check if the connection is still valid
if (!$conn->ping()) {
    die("Database connection failed.");
}

// Query to fetch available courses for the logged-in user
$sql = "
SELECT ac.course_id, ac.course_name, ac.duration, ac.image
FROM available_courses ac
LEFT JOIN student_modules sm ON ac.course_name = sm.module_name AND sm.student_id = ?
WHERE sm.student_id IS NULL";

// Prepare the SQL statement
$stmt = $conn->prepare($sql);
if (!$stmt) {
    die("Error preparing the query: " . $conn->error);
}

// Bind the parameters
$stmt->bind_param("i", $user_id); // Bind the user_id parameter

// Execute the statement
if (!$stmt->execute()) {
    die("Error executing the query: " . $stmt->error);
}

// Get the result
$result = $stmt->get_result();

// Base directory for images
$baseDir = '../img/Courses/';


// Check if courses exist for the logged-in user
if ($result->num_rows > 0) {
    echo '<table class="table table-striped">';
    echo '<thead class="table-dark">';
    echo '<tr>';
    echo '<th scope="col">Select</th>';
    echo '<th scope="col">Image</th>';
    echo '<th scope="col">Course Name</th>';
    echo '<th scope="col">Duration</th>';
    echo '</tr>';
    echo '</thead>';
    echo '<tbody>';
    while ($row = $result->fetch_assoc()) {
        $imagePath = $baseDir . htmlspecialchars($row['image']);
        echo '<tr>';
        echo '<td><input type="checkbox" name="courses[]" value="' . htmlspecialchars($row['course_id']) . '"></td>';
        echo '<td><img src="' . $imagePath . '" alt="' . htmlspecialchars($row['course_name']) . '" width="100"></td>';
        echo '<td>' . htmlspecialchars($row['course_name']) . '</td>';
        echo '<td>' . htmlspecialchars($row['duration']) . '</td>';
        echo '</tr>';
    }
    echo '</tbody>';
    echo '</table>';
} else {
    echo '<p>No courses available at the moment.</p>';
}

// Close the statement and the connection
$stmt->close();
$conn->close();
?>

        </div>
        <button type="submit" class="btn btn-primary">Register</button>
    </form>
</div>

Laravel nwidart “$CLASSServiceProvider” not found

After installing the package nwidart/laravel-modules and configuring it with the commands provided in the package documentation, I encounter the following error after creating a simple module:

Class “ModulesPhpMyAdminProvidersPhpMyAdminServiceProvider” not
found

Here are the changes made to the composer.json file to use the module:

{
    "$schema": "https://getcomposer.org/schema.json",
    "name": "laravel/laravel",
    //........................
    "require": {
        "php": "^8.2",
        //........................
        "nwidart/laravel-modules": "^11.1"
    },
    "require-dev": {
        //........................
    },
    "autoload": {
        "psr-4": {
            "Modules\": "Modules/",
            //........................
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\": "tests/"
        }
    },
    //........................
    "extra": {
        "laravel": {
            "dont-discover": [
            ],
            "merge-plugin": {
                "include": [
                    "Modules/*/composer.json"
                ]
            }
        }
    },
    //........................
    "minimum-stability": "dev",
    "prefer-stable": true
}

After running the command composer dump-autoload, I expected to access the route within the phpmyadmin module using the address localhost:8000/phpmyadmin:
php

Route::get('phpmyadmin', function () {
    dd('test');
})->name('phpmyadmin');

What I’ve noticed is that in the file bootstrap/cache/module.php, the service provider for the module I created is defined as follows:

<?php return array (
  'providers' => 
  array (
    0 => 'Modules\PhpMyAdmin\Providers\PhpMyAdminServiceProvider',
  ),
  'eager' => 
  array (
    0 => 'Modules\PhpMyAdmin\Providers\PhpMyAdminServiceProvider',
  ),
  'deferred' => 
  array (
  ),
);

When I remove these service providers, the error goes away, but the issue of accessing the page still persists, resulting in a 404 error, and this route is not visible in the Laravel routes list when I run:

php artisan route:list

Feel free to post this on Stack Overflow for assistance!

Authorize.net refund Transaction error: has invalid child element ‘payment’ in namespace

On the sandbox API endpoint i try to refund a previously valid transaction (120053733345) with the following createTransactionRequest array (converted into JSON):

Array
(
    [merchantAuthentication] => Array
        (
            [name] => mytestname
            [transactionKey] => mytestkey
        )
    [refId] => 1041-352205
    [transactionRequest] => Array
        (
            [transactionType] => refundTransaction
            [amount] => 29.00
            [currencyCode] => CAD
            [refTransId] => 120053733345
            [payment] => Array
                (
                    [creditCard] => Array
                        (
                            [cardNumber] => 5121212121212124
                            [expirationDate] => 2028-01
                        )
                )
        )
)

While the authCaptureTransaction operation works fine, i receive an error with the refundTransaction operation:

The element ‘transactionRequest’ in namespace ‘AnetApi/xml/v1/schema/AnetApiSchema.xsd’ has invalid child element ‘payment’ in namespace ‘AnetApi/xml/v1/schema/AnetApiSchema.xsd’. List of possible elements expected: ‘splitTenderId, order, lineItems, tax, duty, shipping, taxExempt, poNumber, customer, billTo, shipTo, customerIP, cardholderAuthentication, retail, employeeId, transactionSettings, userFields, surcharge, merchantDescriptor, subMerchant, tip, processingOptions, subsequentAuthInformation, otherTax, shipFrom, authorizationIndicatorType’ in namespace ‘AnetApi/xml/v1/schema/AnetApiSchema.xsd’.

I’ve tried to follow the instruction in
https://developer.authorize.net/api/reference/index.html#payment-transactions-refund-a-transaction
and
Is it possible to refund a transaction in Authorize.Net sandbox account?
but with no success.

Facebook Ad replacing UTMs with FBCLID

I am promoting landing pages with forms through Facebook Ads.

The form is designed to capture UTM parameters passed in the landing page URL.
In the Facebook Ad, I add the UTM parameters using the appropriate fields. However, when I click on the ad and get redirected to my landing page, I notice that Facebook modifies the URL, removing the UTM parameters and adding the “fbclid” parameter instead.

How can I retrieve the UTM parameters?

I see that landing pages created by platforms like EverAd are still able to capture them, but after analyzing the landing page code, it’s unclear how they manage to do it.

How to show a message, redirect user, and generate PDF in the background?

I need to implement a flow where, when a user clicks the “Generate PDF” button, a message appears saying “Your PDF is being generated,” and the user is redirected to the homepage. Meanwhile, the PDF generation continues in the background on the server.

I’m using JavaScript for the frontend and PHP on the backend. The PDF generation may take some time, so I want to ensure the user isn’t blocked during this process. I plan to send an asynchronous request to start PDF generation and then redirect the user. On the backend, I want to run the PDF generation in the background (via a worker or exec()).

What’s the best approach to implement this without blocking the user’s experience?