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?

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>

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.

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!

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?

Use of LDAP in PHP generates an error when the wrong password is supplied

I’m using the LDAP functions in PHP.

My code works quite well, but a problem arises when the user types the wrong password.

In that case my expectation is a message that says “wrong password inserted” (I created a function for it) but instead of it PHP returns an error that blocks the script execution.

Warning: ldap_bind(): Unable to bind to server: Invalid credentials in
/var/www/html/0functions/logon.php on line 83

Warning: ldap_search(): Search: Operations error in
/var/www/html/0functions/logon.php on line 85

Fatal error: Uncaught TypeError: ldap_get_entries(): Argument #2
($result) must be of type LDAPResult, false given in
/var/www/html/0functions/logon.php:86 Stack trace: #0
/var/www/html/0functions/logon.php(86):
ldap_get_entries(Object(LDAPConnection), false) #1
/var/www/html/login.php(22): logdap(‘USER’, ‘PWD’) #2 {main} thrown in
/var/www/html/0functions/logon.php on line 86

My perception is that this is a DLL error. Is there a way to get around this error and let my function go to the end?

It is annoying for the user because they receive the error 500 and get stuck without understanding that it is just because the password is wrong.

Apache is running on Docker but is not receiving a response on host

Trying to run a Moodle instance on Docker using php-apache

Hi, I am currently trying to set up a moodle instance using Docker.

  • A mariadb container (image: mariadb:latest)
  • A php container (image: php:8.3-apache)

According to docker everything is running and if I use nmap to ping the adress, I get:

Nmap scan report for localhost (127.0.0.1)
Host is up (0.000099s latency).
Not shown: 997 closed tcp ports (conn-refused)
PORT     STATE SERVICE
80/tcp   open  http
443/tcp  open  https
3306/tcp open  mysql

Nmap done: 1 IP address (1 host up) scanned in 0.05 seconds

My code is a simple fork from Github – Moodle and has correctly been installed in /var/www/html/moodle on build.

Error: Empty response

When I open my localhost in the browser, I get 127.0.0.1 didn’t send any data. (note: this is a browser message, not an apache error message). I am not getting any error/log messages in my docker containers..

I updated the apache DocumentRoot to match the WORKDIR, but the problem still persists.
Due to the lack of error/feedback I am finding it difficult to figure out where to look.

Setup Docker

Here are my docker files in case you want to replicate my scenario:

  • create a /moodle directory in your root containing a clone from this Github repository
  • create a /moodledata repository that is empty (make sure it has write/create rights)

docker-compose.yml

name: 'moodle_405'

services:
  mariadb:
    image: mariadb:latest
    container_name: mariadb
    environment:
      - MYSQL_ROOT_PASSWORD=bitnami
      - MYSQL_DATABASE=moodle
      - MYSQL_USER=admin
      - MYSQL_PASSWORD=password
    volumes:
      - ./mariadb:/var/lib/mysql
    ports:
      - "3306:3306"

  moodle:
    image: php:8.3-apache
    container_name: moodle
    build:
      context: .
      dockerfile: Dockerfile
    environment:
      - MOODLE_DATABASE_HOST=mariadb
      - MOODLE_DATABASE_NAME=moodle
      - MOODLE_DATABASE_USER=admin
      - MOODLE_DATABASE_PASSWORD=password
    volumes:
      # ./moodle contains a simple fork from moodle's github repository
      - ./moodle:/var/www/html/moodle
      # ./moodledata is an empty folder that will be updated during moodle's setup
      - ./moodledata:/var/www/moodledata
    depends_on:
      - mariadb
    ports:
      - "80:8080"
      - "443:8443"

Dockerfile

FROM php:8.3-apache

LABEL maintainer="John Whick <[email protected]>"
LABEL description="John's Moodle setup for docker"
LABEL version="1.2"

# PHP extensions
RUN apt-get update && apt-get install -y 
    libpng-dev 
    libjpeg-dev 
    libfreetype6-dev 
    libxml2-dev 
    libzip-dev 
    unzip 
    git 
    && docker-php-ext-install mysqli zip gd xml soap intl 
    && a2enmod rewrite

# Set Apache DocumentRoot
RUN sed -ri -e 's!/var/www/html!/var/www/html/moodle!g' 
    /etc/apache2/sites-available/*.conf 
    /etc/apache2/apache2.conf 
    /etc/apache2/conf-available/*.conf

WORKDIR /var/www/html/moodle

EXPOSE 80
EXPOSE 8080

Thank you for your time.

I need to change a field number_format

I need your help.
I have this code that I need to change

$metMessage = "";
        foreach($batches as $batch)
        {
            $metMessage .= '<tr>
            <td>' . $batch['comp_code'] . '</td>
            <td>' . $batch['description'] . '</td>
            <td>' . number_format($batch['quantity'], 0, '.', '') .'</td>
            </tr>';
        }

What i need:

If $batch['quantity'] < 3 then . 
    number_format($batch['quantity'], 2, '.', '') .'
else . 
    number_format($batch['quantity'], 0, '.', '') .'

I don’t know how to add this condition

Uncaught Error: Call to undefined function wp_kses() with PHP 8.3.6

I migrated my WordPress (multisite) website from PHP 7.4 to PHP 8.3.6 and got the following error:

Fatal error: Uncaught Error: Call to undefined function wp_kses() in /home/devnote/www/wp-includes/functions.php:6073 
Stack trace:
#0 /home/devnote/www/wp-includes/functions.php(5554): wp_trigger_error()
#1 /home/devnote/www/wp-includes/class-wpdb.php(1333): _deprecated_function()
#2 /home/devnote/www/wp-content/sunrise.php(11): wpdb->escape()
#3 /home/devnote/www/wp-includes/ms-settings.php(47): include_once('...')
#4 /home/devnote/www/wp-settings.php(155): require('...')
#5 /home/devnote/www/wp-config.php(107): require_once('...')
#6 /home/devnote/www/wp-load.php(50): require_once('...')
#7 /home/devnote/www/wp-blog-header.php(13): require_once('...')
#8 /home/devnote/www/index.php(17): require('...')
#9 {main} thrown in /home/devnote/www/wp-includes/functions.php on line 6073

./wp-includes/functions.php:

$message = wp_kses(
    $message,
    array(
            'a'      => array( 'href' => true ),
            'br'     => array(),
            'code'   => array(),
            'em'     => array(),
            'strong' => array(),
    ),
    array( 'http', 'https' )
);

I disabled the plugins and changed the theme, see here for details, but it did not help.