How to use ESLint 9.11 with PHP?

Previously, I used .eslintrc.json setting with ESLint, using the eslint-plugin-html and the eslint-plugin-php-markup plugins to work through the PHP code. Here’s my previous setting:

{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": "eslint:recommended",
  "overrides": [
  ],
  "parserOptions": {
    "ecmaVersion": "latest"
  },
  "rules": {
    "no-redeclare": "warn",
    "no-unused-vars": "warn",
    "no-redeclare": "warn",
    "no-extra-semi": "off",
    "no-empty": "off",
    "no-inner-declarations": "off",
    "no-useless-escape": "off"
  },
  "plugins": [ "html", "php-markup" ],
  "settings": {
    "php": {
      "php-extensions": [ ".php" ],
      "markup-replacement": { "php": "", "=": "0" },
      "keep-eol": false,
      "remove-whitespace": false,
      "remove-empty-line": false,
      "remove-php-lint": false
    }
  }
}

Now that I’ve upgraded to ESLint 9.11, the setting was automatically migrated to eslint.config.mjs, here’s my new settings:

import html from "eslint-plugin-html";
import phpMarkup from "eslint-plugin-php-markup";
import globals from "globals";
import path from "node:path";
import { fileURLToPath } from "node:url";
import js from "@eslint/js";
import { FlatCompat } from "@eslint/eslintrc";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const compat = new FlatCompat({
    baseDirectory: __dirname,
    recommendedConfig: js.configs.recommended,
    allConfig: js.configs.all
});

export default [...compat.extends("eslint:recommended"), {
    plugins: {
        html,
        "php-markup": phpMarkup,
    },

    files: ["**/*.{php,js,html,htm}"],

    languageOptions: {
        globals: {
            ...globals.browser,
        },

        ecmaVersion: "latest",
        sourceType: "script",
    },

    settings: {
        "php-markup": {
            "php-extensions": [".php"],

            "markup-replacement": {
                php: "",
                "=": "0",
            },

            "keep-eol": false,
            "remove-whitespace": false,
            "remove-empty-line": false,
            "remove-php-lint": false,
        },
    },

    rules: {
        "no-redeclare": "warn",
        "no-unused-vars": "warn",
        "no-extra-semi": "off",
        "no-empty": "off",
        "no-inner-declarations": "off",
        "no-useless-escape": "off",
    },
}];

However, I can no longer lint my PHP files anymore. With the existing settings, ESLint just throw up valid JS-embedded PHP constructs as syntax errors.

How can I make PHP work with ESLint 9.11?

Why mt_rand is not a good option?

I am creating an exericse for my users, where I am trying to tell them that using mt_rand() is not a good option from security point of view. What I did is that I showed them a normal user who gets a password reset email, the token is generated like this

 mt_srand(ip2long( crc32($email));
        $random_number = mt_rand();

Now I tell them once the user gets the token, we can reverse engineer it easily using https://www.openwall.com/php_mt_seed/, which would allow us to get the seed value for any randomly genrated value. My aim here is to show them if we get the seed, it would allow us to get access of admin token, or some catastrophic effect. but seems like getting the seed here is useless.

If the admin tries to reset his password, he will be using different email, thus a different seeding number and different random number. If I only have access to admin’s email, how can I show my audience the catastrophic effect of mt_rand using the same scenario?

Laravel 11: Basic Auth to protect & showcase unfinished app to Client

I have an app that is still under development, yet it is already deployed and live on the server. To protect it from being visited by boots or humans who should not see it yet, I have enabled Basic Auth via server provisioning dashboard (I use runcloud) not Laravel itself.

This all works fine, but because the app integrates payments I had to implement POST route (webhook) for external payment provider to hit it whenever it has to confirm payment. This single route should not be behind basic auth, otherwise payment provider is getting HTTP 401.

So I have:

  1. disabled basic auth on the provisioning dashboard
  2. enabled basic auth on Laravel level by adding auth.basic middleware to all my routes except the webhook one.
    Route::post('/payments/verify', [PaymentsController::class, 'verify'])
        ->name('payments.verify')
        ->withoutMiddleware('auth.basic');

This also works but by default, Laravel will use email and password from users table for credentials. I don’t want this. I want a fixed & simple credentials for everyone like “foo” / “bar”.

How can I do this in Laravel 11?

PHP Imagick – Scale Image – output not satisfying

I’m trying to scale a png image. The top most is scaled by the browser (so on client side):

<img src="data:image/png;base64,{articleImage.fileContent}" style="max-width: 200px; max-height: 200px;" />

The bottom one is scaled by PHP Imagick (so on server side):

$image->resizeImage($newWidth, $newHeight, Imagick::FILTER_BOX, 1);

The scaled output is not satisfying to me. I played a lot with Imagick:FILTER_ and blur factor (1) – but didn’t achieved a good result. Any hint from your side? Thank you!

enter image description here

WordPress SQL Query – Update

Very new to update queries.

My WordPress installation has a table which I need to update via a cron, need to change value via update (ideally) – I know wordpress has built in wpdb for this but I cannot for the life in me work it out.

All I want to do is change values in column ‘status’ if they contain ‘unconfirmed’ to ‘subscribed’

I have a working SQL query which I can confirm in phpmyadmin:

UPDATE wp_mailpoet_subscribers SET status = REPLACE(status, 'unconfirmed','subscribed');

So I my plan is to create a php file in wordpress and then setup a cron job, I have a bunch of others in the site (I didn’t make it!) which work fine.

The code I have tried is as follows:

global $wpdb;
$wpdb->query("UPDATE wp_mailpoet_subscribers SET status = REPLACE(status, 'unconfirmed','subscribed'");

Any help why this doesn’t work would be greatly appreciated

Thanks

global $wpdb;
$wpdb->query(“UPDATE wp_mailpoet_subscribers SET status = REPLACE(status, ‘unconfirmed’,’subscribed'”);

Laravel Inertia

I’m working on a project using Laravel with React and Inertia.js. After making changes to my components and routes, I’m unable to see them reflected in the browser. I’ve run the following commands to clear the caches:

php artisan view:clear

php artisan cache:clear

php artisan route:clear

php artisan config:clear

Despite these actions, the updates are still not showing. I’ve confirmed that I’m in development mode and there are no error messages in the console. I’ve also tried refreshing the page and clearing the browser cache. Is there something I might be overlooking or additional steps I should try to resolve this issue? Any guidance or suggestions would be greatly appreciated!

eratic php inquiry response

I have a web page that controls and inputs switch states into a database.
I confirm this works.
There is a php program to read the switch states from the database via a Get command and send this data in a json format to a remote microprocessor.
As I sit behind a Nat an ESP32 periodically calls in to Get those switch states and changes processor pin states accordingly for control.
From experience interrogating the Json data at microprocessor level and changing the pin status also works.

The Problem..
I can call the php directly via a web interface (Chrome, firefox) and get the pin state readings accurately in real time.
However when making the same inquiry via the Esp the intial readings upon start up are acurate but subsequent changes are erratic sometimes received but generally repeating the initial state. This has been confirmed by printed responses at microprpocessor level.
This will clear after varying times whereupon that readings at that time will become the default.
Switching off and rebooting the microprocessor makes no difference – strangely it defaults back to the last originating state.!

It is as though the states via an Esp call are cached somewhere and repeated as against a direct web inquiry through the php which does show the changes.

Is this a script problem ? and any ideas on how to correct it.

Code:

    <?php
    // board = 7
    // Database connection parameters
    $servername = "localhost";
    $dbname = "xxxxxxx";  // Database name
    $username = "yyyyyyy";  // User
    $password = "xxxx";  // Password

    $gpio = $state = $data = $row = "";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
    }

    // Set the board number for the query
    $board_number = 7;

    // Prepare and execute the SELECT query
    $sql = "SELECT gpio, state FROM switch_outputs WHERE board = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $board_number);
    $stmt->execute();
    $result = $stmt->get_result();

    // Fetch data and encode it as JSON
    $data = array();
    while ($row = $result->fetch_assoc()) {
    $data[] = $row;
    }

    // Update the database with the current time of the last request
    $update_sql = "UPDATE switch_outputs SET last_request = NOW() WHERE board = ?";
    $update_stmt = $conn->prepare($update_sql);
    $update_stmt->bind_param("i", $board_number);
    $update_stmt->execute();

    // Set content type to JSON and output the data
    header('Content-Type: application/json');
    echo json_encode($data);

    // Close statements and connection
    $stmt->close();
    $update_stmt->close();
    $conn->close();
    ?>

The Hosting service (Blue Host) claim it is a scripting problem. Server caching has been cleared without changing the resposne. I am unable to to check the database loggings as it is a shared hosting acount.
My concern is consistency of a timely resposne. Sometimes it works – sometimes it just locks up.

PHP Laravel, error screen shows sensitive information

I have a PHP application using Laravel, whenever there is an error, the system will open a screen containing the error details with db connection details, the database name even the password. How can I prevent the application from showing this sensitive information.
Thank you

Showing records/data from another database table based on the id in laravel

Hello Please I am trying to view the records of a user based on the user id I used as a foreign key in another table in laravel. Basically I want the name of the userID to show.

This is my Controller

    public function index()
    {
       
        
        $id = User::all();
        $organisedTrips = organisedTrip::where('userID', '=', $id)->get();
    
        $organisedTrips = organisedTrip::paginate(4);
        return view('welcome', compact('organisedTrips'));
        
    }

The user table

The table where I made the userID a foreign key from the user's table

How to make curl to the same server lightning fast?

I’m trying to create a proxy site AAA.com and relay the traffic to BBB.com in the backend via PHP cURL, and again relay the response from BBB.com to AAA.com visitors. Both sites are on the same server. Below is the code:

$proxied_site = 'https://BBB.com';

$proxied_site_parsed = parse_url($proxied_site);

$ch = curl_init();

$proxied_url = $proxied_site . $_SERVER['REQUEST_URI'];

curl_setopt($ch, CURLOPT_URL, $proxied_url);

curl_setopt($ch, CURLOPT_RESOLVE, array(
    "{$proxied_site_parsed['host']}:443:170.249.199.178",
));

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $_SERVER['REQUEST_METHOD']);
$requestHeaders = [];
foreach (getallheaders() as $name => $value) {
    if ($name == 'Host') {
        $value = $proxied_site_parsed['host'];
    }
    $requestHeaders[] = "$name: $value";
}

curl_setopt($ch, CURLOPT_HTTPHEADER, $requestHeaders);

if (in_array($_SERVER['REQUEST_METHOD'], ['POST', 'PUT', 'DELETE'])) {
    curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents('php://input'));
}

curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);

$response = curl_exec($ch);

$response_header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$responseHeaders = substr($response, 0, $response_header_size);
$responseBody = substr($response, $response_header_size);

foreach (explode("rn", $responseHeaders) as $header_line) {
    
    if (stripos($header_line, 'HTTP/') === 0 || stripos($header_line, 'Set-Cookie:') === 0) {
        header($header_line, false);
    } else {
        header($header_line);
    }
}

curl_close($ch);

echo $responseBody;

After some benchmarking, cURL still needs about 0.006 seconds of network time to get to the site BBB.com on the same server.

My question is, is it possible to make it faster? Can I make it lightning-fast and as fast as 0.00006 since they are both on the same server?

I tried using IP:

$ch = curl_init('XXX.XXX.XXX.XXX');

And CURLOPT_RESOLVE:

curl_setopt($ch, CURLOPT_RESOLVE, array(
    "{$proxied_site_parsed['host']}:443:XXX.XXX.XXX.XXX",
));

But neither worked and the network around time was still about 0.006s.

Is this possible with cURL at all? Or at least make it 0.0006s?

If not, why?

OpenSwoole: use UDP server to push messages into a channel

I’m trying to get started with OpenSwoole and I’m using the built-in UDP server. I’d like to push any received messages into a channel so that another coroutine can process them. I’ve Googled extensively and can’t find an obvious way of doing it.

This is the code that I currently have:

// Create a channel with space for 1000 messages
$chan = new OpenSwooleCoroutineChannel(1000);

co::run(function () use ($chan){

    // Listener
    go(function() use ($chan) {
        // Read from channel
        while (1) {
            $data_read = $chan->pop();
            echo ("Data read: $data_readn");
        }
    });
});

// UDP server

// Set coroutine options before the server is started
OpenSwooleCoroutine::set([
        'enable_coroutine' => true
]);

// Start a new UDP server on 12.0.0.1, listening on port 9502
$server = new OpenSwooleServer('127.0.0.1', 9502, OpenSwooleServer::POOL_MODE, OpenSwooleConstant::SOCK_UDP);

// Setup the incoming data event callback, called 'Packet'
$server->on('Packet', function ($server, $data, $clientInfo) use ($chan)
{
    echo ("Data written: $datan");
    $chan->push($data);
});

// Start the server and begin accepting incoming requests
$server->start();

But when I run it I get the error:

===================================================================
 [FATAL ERROR]: all coroutines (count: 1) are asleep - deadlock!
===================================================================

How do I wrap the UDP server up into a coroutine ? I thought that it already ran as one or have I missed something obvious ?

Adding initialize to body tag if I am using a specific ACF block

I am making a ACF block that includes a google map and I need to add:

onload="initialize()"

to the body tag.
Can I use PHP to add that code conditionally if a unique ACF block is being used on the page?

I tried this:

function check_if_block_exist($block_handle) {
  $post = get_post(); 

  if(has_blocks($post->post_content)) {
    $blocks = parse_blocks($post->post_content);

    foreach( $blocks as $block ) {
      if($block['blockName'] === $block_handle) {
        return true;
      }
    }
    return false;
  }
}

But it didn’t work.

PHP message: Notice: Undefined variable: DATABASE_USER_HOST

I’m getting this error even though I haven’t actually declared DATABASE_USER_HOST:

Notice: Undefined variable: DATABASE_USER_HOST in /home/jm4bwakj91is/public_html/student_dashboard.php on line 16

I double-checked the whole code, and I didn’t use DATABASE_USER_HOST. I also tried using error_reporting(E_ALL & ~E_NOTICE);.

Laravel Search by swapping origin and destination forms

I have a project to check shipping rates using Laravel 11, I already have a table with prices that have been determined from origin to destination.

enter image description here

I use a search form with these 2 fields, but how can I swap the search, for example origin 1 to destination 2 or origin 1 to destination 2, and the results are still in the same column. And if the origin and destination are different then the results should not be displayed or will be null. For example, origin 3 to destination 2.

I use the get method but the search results do not match what is in the database table.
enter image description here
Why does a search with input that does not match the data table still appear with a different origin and destination? The result should be null because it is not in the column?

I have tried the following code but it doesn’t work as I expected. And This is some of the code I used

From Search

<form action="{{ url('rates') }}" method="GET">
      @csrf
      <div class="form-row align-items-center row">
          <div class="col-md-5">
              <label>Origin</label>
              <select class="form-control single-select-field" name="origin">
                 <option selected>Origin...</option>
                   @foreach ($cities as $city)
                   <option value="{{ $city->id }}">{{ $city->id}}</option>
                   @endforeach
              </select>
            </div>
          <div class="col-md-5">
            <label>Destination</label>
            <select class="form-control single-select-field" name="destination">
               <option selected>Destination...</option>
                  @foreach ($cities as $city)
                    <option value="{{ $city->id }}">{{ $city->id }}</option>
                  @endforeach
            </select>
          </div>
          <div class="col-md-6 my-3">
             <button type="submit" class="btn btn-warning btn-block">Check Rates</button>
          </div>
         </div>
 </form>

Rates Controller

$origin = $request['origin'];
$destination = $request['destination'];
$result = RouteModel::where(['origin' => $origin, 'destination' => $destination])->orWhere(['destination' => $origin, 'origin' => $destination])->first();
return $result;

Thank you for the help

Encrypt Query Parameter in Flutter and decrypt in PHP to get Data

The IV and the key are up here.


 // Verschlüsselt den Job-Parameter
  String encryptJob(String job) {
    final encrypter = encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.cbc));
    final encrypted = encrypter.encrypt(job, iv: iv);
    return encrypted.base64; // Base64-String des verschlüsselten Textes
  }

  String encryptMessage (String message){
    final encrypter = encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.cbc));
    final encrypted = encrypter.encrypt(message, iv:iv);
    return encrypted.base64;
  }

Future<void> fetchData() async {
    final message = '&function=';

    // Verschlüsselung des Job-Parameters
    final encryptedJob1 = encryptJob('job=$job1');
    final encryptedJob2 = encryptJob('job=$job2');
    final encryptedJob3 = encryptJob('job=$job3');
    final encryptedJob4 = encryptJob('job=$job4');


    //IV und verschlüsselte Daten für die URL korrekt kodieren
    final encodedIV = Uri.encodeComponent(iv.base64);
    final encodedJob1 = Uri.encodeComponent(encryptedJob1);
    final encodedJob2 = Uri.encodeComponent(encryptedJob2);
    final encodedJob3 = Uri.encodeComponent(encryptedJob3);
    final encodedJob4 = Uri.encodeComponent(encryptedJob4);
    final encryptedMessage = encryptMessage('$message$encodedJob4');

    // Jetzt den IV korrekt in Base64 umwandeln und in die URL einfügen
    final webServiceURl = 'http://localhost/get_encrypt_request.php?iv=$encodedIV$message$encodedJob4';
    final url = Uri.parse(webServiceURl);
    final response = await http.get(url);

    print('$urln');
    print(response.body);

    setState(() {
      data = response.body;
    });

    if (response.statusCode == 200) {
      print('Erfolgreiche Antwort');
    } else {
      print('Fehler beim Abrufen der Daten: ${response.statusCode}');
    }
  }

My Task is to encrypt the queryParamters that no plaintext can be seen affter the ?.
I can encrypt my job but not my queryparameter in that case the message per se.
And after that the queryparameter must than be decrypt in php and send me the data from the job.

// Empfange den IV und die verschlüsselten Daten
$iv = isset($_GET['iv']) ? $_GET['iv'] : '';
$data = isset($_GET['function']) ? $_GET['function'] : '';
  final encryptedMessage = encryptMessage('$message$encodedJob4');

In this line you can see that i have tried to put the message with the job but than for the job it is a “double encryption” and that is indeed not that sence.

    final webServiceURl = 'http://localhost/get_encrypt_request.php?iv=$encodedIV$encryptedMessage';

When i change the queryparameters to this for sure it doesn’t work.