updating database where had the same name but when it has new name will make new data [duplicate]

I want to update my data at database where condition that they had same name they will update the stock not making new data.

But when U run this program nothing happen and I got no error.

Please help me to fix it.

This is my query code to update data while button clicked.

if (isset($_POST['tambah'])) {
        $namaBarang = $_POST['barang'];
        $stok = $_POST['stok'];

        //cek barang sudah ada atau belum
        $result = mysqli_query($conn,"SELECT*FROM barang WHERE name ='$namaBarang'");
        if (mysqli_fetch_assoc($result)) {
            mysqli_query($conn,"UPDATE barang SET stock = stock + $stok WHERE name = $namaBarang");
        } else{
            mysqli_query($conn,"INSERT INTO barang VALUES ('','$namaBarang',$stok)");
        }

Woocommerce Product Variant [closed]

I am not getting solution,in wocommerce site i have addred product like HOODIES which has two sizes Youth|Adult Youth Size has two color option White|Grey and Adult has White|Grey|Red I want is as user select Youth Sizefrom drop down only White| Grey appears and when select Adult all White|Grey|Red appear. I don’t want to use any plugin. Can it be possible ?

Moving uploaded file error becasue of FakePath [closed]

Im trying to add user profile photo, but the problem is moving the uploaded file to the target directory because of the fakepath.

since the this is fakepath and temp location is (C:fakepathroundtableandchairs.jpg), moving the uploaded file will return error as well.

what i did is, i have change the line 106 and i also removed moving uploaded file section and the return is success.

I already did a research about the fakepath it is because of the browser security.

is there any way to get the temp path of the file in localhost (not live)? i just want to test it first in my computer (localhost). or to get this [name][tmp_name][size][type] using the code?

public function add(array $data)
{

    if ($errors = $this->registrator->validateUser($data, false)) {
    Response::validationError($errors);
    }

    $allowedTypes = ['jpg', 'jpeg', 'png', 'gif'];

    $profilepic = (string)$data['profile_image'];

    // Handle secure profile image upload
    $targetDirectory = 'c:/Apache24/AdminLTE/dist/assets/img/usersprofile/';
    $imageFileType = strtolower(pathinfo($profilepic, PATHINFO_EXTENSION));

    // Generate a unique filename: complete_name_uniqueID.extension
    $safeName = preg_replace('/[^A-Za-z0-9]/', '_', $data['username']); // Remove special chars
    $uniqueID = uniqid();
    $imageName = "{$safeName}_{$uniqueID}.{$imageFileType}";
    $targetFile = $targetDirectory . $imageName;

    $profilepicsize = getimagesize($profilepic);
    // Validate image file size
    if ($profilepicsize > 5000000) {
        return "File size exceeds the 2MB limit.";
    }

    //Validate Mime Types
    if (!in_array($imageFileType, $allowedTypes)) {
                return ['success' => false, 'message' => 'Invalid file type. Only JPG, JPEG, PNG, GIF allowed.'];
            }

    // Prevent executable file uploads
    if (preg_match('/.(php|html|htm|js|exe|sh)$/i', $profilepic[0])) {
        return "Invalid file type.";
    }

    // Ensure upload directory exists
    if (!is_dir($targetDirectory)) {
        if (!mkdir($targetDirectory, 0755, true)) {
            return "Failed to create upload directory.";
        }
    }

    // Move the uploaded file
    if (!move_uploaded_file($profilepicpic, $targetFile)) {
        return "Error uploading the image.";
    }

    // Insert data into the database
    $this->db->insert('users', [
            'email' => $data['email'],
            'username' => $data['username'],
            'password' => $this->hashPassword($data['password']),
            'confirmed' => 'Y',
            'confirmation_key' => '',
            'register_date' => date('Y-m-d H:i:s'),
            'profile_image' => $imageName
        ]);

    $this->db->insert('user_details', [
        'user_id' => $this->db->lastInsertId(),
        'first_name' => $data['first_name'],
        'last_name' => $data['last_name'],
        'phone' => $data['phone'],
        'address' => $data['address']
    ]);

        Response::success(["message" => trans("user_added_successfully")]);
}

Warning: getimagesize(roundtableandchairs.jpg): Failed to open stream: No such file or directory in C:Apache24htdocsAdminLTEdistScriptUser.php on line 106

line 106 :

$profilepicsize = getimagesize($profilepic); 

Replacement of line 106

$profilepicsize = pathinfo($profilepic, PATHINFO_DIRNAME);

Is it possible to pass recaptcha v2 using php-webdriver? [closed]

I am trying to fill a web form to send SMS using php-webdriver on a site that uses recaptcha v2. My PHP script also start Selenium standalone server from bat files: selenium-server-hub.bat and selenium-server-node.bat.

selenium-server-hub.bat

chcp 65001
chdir C:inetpubwwwrootmedserviceswwwrootseleniumserver
"C:Program FilesJavajdk-24binjava.exe" -jar "selenium-server-4.35.0.jar" hub

selenium-server-node.bat

chcp 65001
chdir C:inetpubwwwrootmedserviceswwwrootseleniumserver
"C:Program FilesJavajdk-24binjava.exe" -Dwebdriver.edge.driver=msedgedriver.exe -jar "selenium-server-4.35.0.jar" node --config "NodeWebDriver.json"

NodeWebDriver.json

{
  "capabilities": [
    {
      "browserName": "MicrosoftEdge",
      "maxInstances": 5,
      "seleniumProtocol": "WebDriver",
      "platform": "WINDOWS"
    },
    {
      "browserName": "firefox",
      "maxInstances": 5,
      "seleniumProtocol": "WebDriver",
      "platform": "WINDOWS"
    },
    {
      "browserName": "chrome",
      "maxInstances": 5,
      "seleniumProtocol": "WebDriver",
      "platform": "WINDOWS"
    },
    {
      "browserName": "internet explorer",
      "maxInstances": 1,
      "seleniumProtocol": "WebDriver",
      "platform": "WINDOWS"
    }
  ],
  "proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
  "maxSession": 5,
  "port": 5555,
  "register": true,
  "registerCycle": 5000,
  "hub": "http://Администратор:[email protected]:4444",
  "nodeStatusCheckTimeout": 5000,
  "nodePolling": 5000,
  "role": "node",
  "unregisterIfStillDownAfter": 60000,
  "downPollingLimit": 2,
  "debug": false,
  "servlets": [],
  "withoutServlets": [],
  "custom": {}
}

PHP script, which fills a web form and attempts to pass recaptcha

<?php
require_once "C:\Program Files\IIS Express\PHP\v8.3\lib\php-webdriver\vendor\autoload.php";

use FacebookWebDriverRemoteRemoteWebDriver;
use FacebookWebDriverRemoteDesiredCapabilities;
use FacebookWebDriverWebDriverBy;

function CheckIfSeleniumServerStarted(string $role) : bool
{
    $isStarted = false;
    $handle = curl_init();
    if($handle instanceof CurlHandle)
    {
        curl_setopt_array($handle,
        [
            CURLOPT_URL => $role === "node" ? "http://Администратор:7565@localhost:5555" : "http://Администратор:7565@localhost:4444",
            CURLOPT_HTTPHEADER => [ "Connection: keep-alive", "Accept: */*" ],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CONNECTTIMEOUT => 60,
            CURLOPT_TIMEOUT => 60,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_USERAGENT => $_SERVER["HTTP_USER_AGENT"],
            CURLOPT_SSL_VERIFYHOST => FALSE,
            CURLOPT_SSL_VERIFYPEER => FALSE
        ]);
        $result = curl_exec($handle);
        $isStarted = is_string($result) && ($statusCode = curl_getinfo($handle, CURLINFO_HTTP_CODE)) >= 200 && $statusCode < 300;
        curl_close($handle);
    }
    return $isStarted;
}

ini_set("display_errors", true);
header('Content-Type: text/html; charset=utf-8');
$log_filename = str_replace("php", "log", __FILE__);
$log_handle = fopen($log_filename, "w+");
if($log_handle !== false)
{
    set_error_handler(fn(int $errno, string $errstr, string $errfile = null, int $errline = 0) =>
        error_log("Error: {$errno} in {$errfile}, line no {$errline}n{$errstr}", 3, $log_filename), E_ALL);
}
// Start Selenium server
$cmdPath = "C:\Windows\system32\cmd.exe";
$workingDir = __DIR__ . "\selenium\server";
$shell = null;
if(!CheckIfSeleniumServerStarted("hub"))
{
    $command = "{$cmdPath} /C {$workingDir}\selenium-server-hub.bat 2>&1 &";
    $shell = new COM("WScript.Shell");
    $shell->Run($command, 1, false);
    sleep(1);
}
if(!CheckIfSeleniumServerStarted("node"))
{
    $command = "{$cmdPath} /C {$workingDir}\selenium-server-node.bat 2>&1 &";
    $shell = $shell ?? new COM("WScript.Shell");
    $shell->Run($command, 1, false);
    sleep(1);
}
$classRemoteWebDriver = "\Facebook\WebDriver\Remote\RemoteWebDriver";
$classRemoteWebElement = "\Facebook\WebDriver\Remote\RemoteWebElement";
$pageHtml = "";
$edgeOptions = ["args" => [ "--ignore-certificate-errors"]];
$capabilities = DesiredCapabilities::microsoftEdge();
$capabilities->setCapability("ms:edgeOptions", $edgeOptions);
$host = "http://localhost:4444";
$webDriver = RemoteWebDriver::create($host, $capabilities);
if($webDriver instanceof $classRemoteWebDriver)
{
    $webDriver->get("https://bomgovka.ru");
    $elemNumber = $webDriver->findElement(WebDriverBy::xpath("//input[@id='number']"));
    $elemMessage = $webDriver->findElement(WebDriverBy::xpath("//textarea[@id='message']"));
    if($elemNumber instanceof $classRemoteWebElement && $elemMessage instanceof $classRemoteWebElement)
    {
        $phoneNumber = "XXXXXXXXXXX";
        $elemNumber->sendKeys($phoneNumber);
        sleep(3);
        $elemMessage->sendKeys("Test message");
        sleep(3);
        $element = $webDriver->findElement(WebDriverBy::xpath("//iframe[starts-with(@name, 'a-') and starts-with(@src, 'https://www.google.com/recaptcha')]"));
        error_log("Recaptcha iframe is " . ($element instanceof $classRemoteWebElement ? "found" : "not found"), 3, $log_filename);
        if($element instanceof $classRemoteWebElement)
        {
            $webDriver = $webDriver->switchTo()->frame($element);
            error_log("Switch to recaptcha iframe is " . (!($webDriver instanceof $classRemoteWebDriver) ? "not " : "") . "completed.", 3, $log_filename);
            if($webDriver instanceof $classRemoteWebDriver)
            {
                $element = $webDriver->wait(25)->until(FacebookWebDriverWebDriverExpectedCondition::elementToBeClickable(WebDriverBy::xpath("//div[@class = 'recaptcha-checkbox-border']")));
                error_log("Recaptcha checkbox is " . ($element instanceof $classRemoteWebElement ? "found and clickable" : "not found or not clickable"), 3, $log_filename);
                if($element instanceof $classRemoteWebElement)
                {
                    $element->click();
                    $pageHtml = $webDriver->getPageSource();
                    $webDriver = $webDriver->switchTo()->defaultContent();
                    error_log("Switch to default content is " . (!($webDriver instanceof $classRemoteWebDriver) ? "not " : "") . "completed.", 3, $log_filename);
                    if($webDriver instanceof $classRemoteWebDriver)
                    {
                        $elemButton = $webDriver->wait(25)->until(FacebookWebDriverWebDriverExpectedCondition::elementToBeClickable(WebDriverBy::xpath("//input[@name='contact-submit']")));
                        error_log("Submit button is " . ($elemButton instanceof $classRemoteWebElement ? "found and clickable." : "not found or not clickable."), 3, $log_filename);
                        if($elemButton instanceof $classRemoteWebElement)
                        {
                            $elemButton->click();
                            sleep(3);
                            $pageHtml = $webDriver->getPageSource();
                        }
                    }
                }
            }
        }
    }
    $webDriver->quit();
}
echo $pageHtml;
if(is_resource($log_handle))
{
    fclose($log_handle);
}
?>

But as a result of the script executing, recaptcha is not passed and site returns “Error. Please pass the ‘I’m not a robot’ check”.
How to pass recaptcha using php-webdriver correctly or it’s impossible using only php-webdriver?

Why my browsers do not read php files any more [duplicate]

I run php files and echo, nothing comes out but I saw the whole php get commented out in the console,

I try to run php program, but I get nothing in return on browser rather I got this error message in the console

(This page is in Quirks Mode. Page layout may be impacted. For
Standards Mode use “<!DOCTYPE html>”.)

I will like to know if there are possible ways to get out of it

522 connection time out on cloudflair for php laravel and node

I’m running a PHP 8.1 Laravel application on an Apache server. The same server also runs a Node.js API (separate subdomain). The site is behind Cloudflare.

The issue:

The site randomly goes down for 10–20 minutes, then comes back without me doing anything.

During downtime, the Laravel site is inaccessible and Node.js APIs return Cloudflare 522 (connection timeout).

Sometimes the APIs still work when tested directly with Postman, but the Laravel frontend is down.

I’ve confirmed this with Uptime Robot monitoring, which shows repeated outages.

Laravel logs during downtime:

[2025-09-01 04:27:35] production.ERROR: Product Detail Error: cURL
error 56: Recv failure: Connection reset by peer for
http://ip-api.com/json/52.167.144.238

[2025-09-01 04:28:39] production.ERROR: API Request Error: Server
error: POST https://node.byyu.com/api/oneapiseconds resulted in a 522
response: error code: 522

Apache (cPanel) error logs show: [Mon Sep 01 02:19:50.127766 2025]
[authz_core:error] [client 52.71.218.25:19567] AH01630: client denied
by server configuration: /home/byyu/public_html/app/Http/error_log

[Sun Aug 31 22:23:46.573272 2025] [autoindex:error] [client
87.58.67.112:63776] AH01276: Cannot serve directory /home/byyu/public_html/admin/images/: No matching DirectoryIndex
found, and server-generated directory index forbidden

What I’ve observed:

Short outages (~5 min) sometimes produce no Laravel logs.

Longer outages (~10–20 min) always produce the above errors.

The website recovers automatically after some minutes, without restarting services.

My questions:

What could cause Laravel + Apache + Node.js to become unreachable for 10–20 minutes and then recover automatically?

Are the cURL error 56 and Cloudflare 522 hints of a resource bottleneck (CPU/memory), or a configuration issue with Apache/PHP-FPM?

What’s the best way to diagnose this kind of intermittent downtime on a shared server (cPanel)?

Any advice on debugging steps, or configuration changes I should check (Apache KeepAlive, PHP-FPM workers, Node process manager, etc.), would be appreciated.

Environment:

PHP 8.1, Laravel, Apache (cPanel hosting) Node.js backend on same server (node.byyu.com) Cloudflare in front of both domains

I tried changing the apis mentioned above which are node apis and optimized the api queries. Also i break out the api on dashboard again a node api the dashboard api was previously gaetting all data in sigle api i break down that api in one and two part first bings only banners, categories data and other brings the products.

Different Web Authentication Flow [closed]

I read something a few months ago about an Authentication flow, where the server would validate the credentials and store something (token ? id ?) directly in the request’s headers.

The client would then just do normal requests without specifying any header and the token/id/hash would already be in the header for the server to validate (or it might already be validated).

Of course, I forgot about it for a while and now that I want to learn more I can’t find anything about it.

I’ve been crawling the OAuth website and other available documentations but can’t seem to find this one…

I don’t think it’s the Session Token Flow or other Authorization Code Flow but again, I’m not sure of what I read.

Does it ring a bell to you or did I invent this memory of mine ?

Thank you !

After upgrading from PHP 8.3 to 8.4 I get “Maximum call stack size … reached. Infinite recursion?” [closed]

After upgrading my project from PHP 8.3 to PHP 8.4, I started getting the following error:

Maximum call stack size of 8339456 bytes (zend.max_allowed_stack_size – zend.reserved_stack_size) reached. Infinite recursion?

This happens when trying to sync data with Google Cloud Logging through gRPC.
Here is a snippet of the stack trace:

/workspace/vendor/google/gax/src/CredentialsWrapper.php:244
/workspace/vendor/grpc/grpc/src/lib/UnaryCall.php:45
/workspace/vendor/grpc/grpc/src/lib/BaseStub.php:295
/workspace/vendor/google/gax/src/Transport/GrpcTransport.php:267
...
/workspace/vendor/monolog/monolog/src/Monolog/Logger.php:391
/workspace/vendor/laravel/framework/src/Illuminate/Log/Logger.php:183

Environment:

Laravel project
Google Cloud Logging SDK (google/gax, google/cloud-logging),

gRPC extension enabled,

Works fine with PHP 8.3, only fails on PHP 8.4,

Question:

Has anyone encountered this issue after upgrading to PHP 8.4?

Is this a known incompatibility between PHP 8.4 and gRPC/Google Cloud libraries?

Any workaround or configuration change (e.g., zend.max_allowed_stack_size) that helps, or should I downgrade back to PHP 8.3 until support is fixed?

Base glyph is incorrect when parsing ligature components with PHP php-font-lib fork [closed]

I’m trying to parse ligature components to Unicode mapping in PHP using my own fork of php-font-lib which implements gsub table parsing. The official library doesn’t support this yet.

I’m using it with the Material Icons Font.
According to Fontdrop, the font contains all necessary ligature and GSUB data:
Fontdrop ligature parse image

The output I am trying to achieve should follow this pattern:

[
"fire_extinguisher": "uniF1D8",
]

However with my current script (You can find the code below), I get an output like this:

2ire_extinguisher -> 

The base glyph is wrong or sometimes missing entirely:

oom_in -> 
2ont_download_off -> 

Steps to reproduce:

1.) Clone my fork:

git clone https://github.com/NLion74/php-font-lib
cd php-font-lib
touch reproduction_example.php

1.) Add this code to reproduction_example.php

<?php
require __DIR__ . '/vendor/autoload.php';
use FontLibFont;

$fontPath = "../MaterialIcons-Regular.ttf";
if (!file_exists($fontPath)) die("Font not found");

$font = Font::load($fontPath);
$font->parse();

$cmap = $font->getData("cmap")['subtables'][0]['glyphIndexArray'] ?? [];
$glyphIDtoChar = [];
foreach ($cmap as $unicode => $gid) {
    if ($gid !== 0) $glyphIDtoChar[$gid] = mb_chr($unicode, 'UTF-8');
}

$gsub = $font->getData("GSUB");
$ligatureMap = [];

foreach ($gsub['lookupList']['lookups'] as $lookup) {
    if ($lookup['lookupType'] !== 4) continue;
    foreach ($lookup['subtables'] as $subtable) {
        if (!isset($subtable['ligSets'])) continue;

        $leadingChars = [];
        if (!empty($subtable['coverage']['rangeRecords'])) {
            foreach ($subtable['coverage']['rangeRecords'] as $range) {
                for ($gid = $range['start']; $gid <= $range['end']; $gid++) {
                    $leadingChars[] = $glyphIDtoChar[$gid];
                }
            }
        }
        if (!empty($subtable['coverageGlyphs'])) {
            foreach ($subtable['coverageGlyphs'] as $gid) {
                $leadingChars[] = $glyphIDtoChar[$gid];
            }
        }

        foreach ($subtable['ligSets'] as $index => $ligSet) {
            $baseGlyph = $leadingChars[$index];
            foreach ($ligSet['ligatures'] as $lig) {
                $components = array_map(fn($gid) => $glyphIDtoChar[$gid], $lig['components']);
                array_unshift($components, $baseGlyph);
                $seqStr = implode('', $components);
                $ligatureGlyph = $glyphIDtoChar[$lig['ligatureGlyph']];
                $ligatureMap[$seqStr] = $ligatureGlyph;
            }
        }
    }
}

foreach ($ligatureMap as $seq => $lig) {
    echo "$seq -> $lign";
}

3.) Run:

composer install
php reproduction_example.php

Expected behavior:

  • The base glyph plus components map correctly to the ligature glyph.

Actual behavior:

  • The base glyph seems to be entirely wrong

Question:

  • How can I correctly extract the base glyph for each ligature set when parsing the GSUB table in PHP?

Email link open [closed]

I built a web view mobile app. After the app has been installed on a mobile phone, whenever a password reset link is sent to a user email to reset password, the link proceeds to open on a web browser instead of popping out and option for the link to be open in app. I used phpmailer to send the message with the following code

$message = "Hi Adeyemi <p>We received a request to reset the password for your account. You can reset your password by clicking the link below:</p><p>https://investwithbth.com/app/reset-password.php?token=78uiyt65redfty78iuhj</p><p>If you didn’t request a password reset, you can safely ignore this email, no changes have been made to your account.</p><p>If you have any questions or need further assistance, feel free to contact our support team.</p><p>Thanks</p>";

Telegram API (check likes) [closed]

Is there a way to check if a person liked a post? as “mandatory subscription to the channel”
On Python or PHP, you need a tg bot. or leave ideas

I haven’t tried anything yet. Is it possible without complicated options?

How to edit a running WordPress site that isnt mine with Php Storm? [closed]

Currently I am a person who is studying I have coded websites with WebStorm but a person has asked me to do edits on their website. I have received admin access but I need to find a way to get the WordPress website into either Php Storm or WebStorm as those are the 2 I know best and know how to edit efficiently. I am unable to find any way to do this. Is anyone able to assist me.

I have tried plugins to download it as a zipfile.
I have tried to understand how it works but it seems all of them need me to have access to the local machine that the person has made the website from. I am unable to get access to it and I wont lie I am still a student who is still trying to understand these mechanics. I have also asked lecturers and they where unable to assist me in any way.

Deployer setup with vps bare repo [closed]

I need some help, for the past 3-4 days I tryed everything, nothing works.

Setup deployer / symfony app inside vps.
I delete /domain/public_html/.dep/repo

Set deployer repository :

  1. deploy@aliasname:/path, I get this : ssh: Could not resolve hostname Temporary failure in name resolution fatal: Could not read from remote repository.
  2. deploy@ip:/path, I get this : Permission denied (publickey).fatal: Could not read from remote repository.
  3. file:///path : deploy succes but site has 500 error. I have to sudo chown -R phpUser:phpUserGroup on /var/www/domain so the site works. Then, redo deploy, and it fails with this error :
    error in update_code.php on line 100:
    [vps] run cd /var/www/domain.com/public_html/.dep/repo && (/usr/bin/git config –get remote.origin.url)
    [vps] exit code 1 (General error) . ERROR: Task deploy:update_code failed!

repo is set to vps inside /home/deployer/repo/domain.git
I can ssh with deployer no problem (with the aliasname)
remote is set to aliasname:/path-to-git-repo
ubuntu / nginx

any other information needed I will provide.

Best regards !

Failing to upload images via api endpoint in php

I’m building a bulk upload feature in WordPress for WooCommerce. The challenge I’m facing is with importing product images.

The image data comes from a CSV file, where each row represents a product.

The images column contains one or more image filenames, separated by a pipe (|) character (e.g., image1.jpg|image2.jpg).

These images are included in a ZIP folder uploaded alongside the CSV.

The goal is to match each filename in the CSV with its corresponding file from the ZIP, then upload and attach those images to the WooCommerce product.

Below is the function that processes the CSV and creates products. I’d appreciate help refining this code to better handle the image import logic and ensure best practices.

public function bulkUpload($csvBase64,$bId)
            {
            // Accept CSV as base64 string from POST body
            $csvBase64 = isset($_POST['csvBase64']) ? $_POST['csvBase64'] : null;
            $imagesDir = func_num_args() > 2 ? func_get_arg(2) : null;

            if (!$csvBase64) {
            return [
                'success' => false,
                'message' => 'No CSV file provided',
                'code'    => 400,
                'data'    => [],
            ];
           }

            // Decode base64
           $csvData = base64_decode($csvBase64);
            if ($csvData === false) {
            return [
                'success' => false,
                'message' => 'Failed to decode CSV',
                'code'    => 400,
                'data'    => [],
            ];
        }

        
        $rows = array_map('str_getcsv', preg_split('/rn|n|r/', $csvData));
        

        if (count($rows) < 2) {
            return [
                'success' => false,
                'message' => 'CSV must have at least one data row',
                'code'    => 400,
                'data'    => [],
            ];
        }

        $header = array_map('trim', $rows[0]);
        $productsCreated = [];
        $errors = [];
        for ($i = 1; $i < count($rows); $i++) {
            $row = $rows[$i];
            if (count($row) < count($header)) {
                continue; // skip incomplete rows
            }
            $data = array_combine($header, $row);
            error_log("BulkUpload row $i images: " . (isset($data['images']) ? $data['images'] : 'NONE'));
            // Required fields: title, price
            $title = isset($data['title']) ? sanitize_text_field($data['title']) : '';
            $regularPrice = isset($data['regular_price']) ? $data['regular_price'] : '';
            $salePrice = isset($data['sale_price']) ? $data['sale_price'] : '';
            $description = isset($data['description']) ? sanitize_text_field($data['description']) : '';
            $condition = isset($data['condition']) ? sanitize_text_field($data['condition']) : '';
            $categories = isset($data['categories']) ? explode('|', $data['categories']) : [];
            $post_status = isset($data['post_status']) ? sanitize_text_field($data['post_status']) : '';
            $availability = isset($data['availability']) ? sanitize_text_field($data['availability']) : '';
            $quantity   = isset($data['quantity']) ? $data['quantity'] : 0;
            $backOrders   = isset($data['backOrders']) ? $data['backOrders'] : 0;

            $product = new WC_Product_Simple();
            $product->set_name($title);
            $product->set_description($description);
            $product->set_status('publish');

            if ($availability === false) {
                $product->set_stock_status('outofstock');
            } else {
                $product->set_stock_status('instock');
            }

            $post_data = [
                'post_author' => get_current_user_id(),
                'post_title'  => $title,
                'post_type'   => 'product',
                'post_status' => 'publish',
            ];

            $product->set_stock_quantity((int)$quantity);
            $product->set_backorders($backOrders);
            $product->set_manage_stock(true);
            $post_id = wp_insert_post($post_data);
            $product->set_id($post_id);
            if (!empty($categories)) {
                $product->set_category_ids($categories);
            }

            $product->set_sale_price($salePrice);
            $product->set_regular_price($regularPrice);

            $productId = $product->save();
            update_post_meta($productId, 'bID', $bId);
            update_post_meta($productId, '_condition', $condition);
            $productsCreated[] = $productId;

            // Handle attribute_name_X and new_attribute_name_X pairs
            $attributesArray = [];
            foreach ($data as $key => $value) {
                if (preg_match('/^(attribute_name_|new_attribute_name_)(d+)$/', $key, $matches)) {
                    $index = $matches[2];
                    $attrName = sanitize_text_field($value);
                    $attrValueKey1 = 'attribute_value_' . $index;
                    $attrValueKey2 = 'new_attribute_value_' . $index;
                    if (isset($data[$attrValueKey1])) {
                        $attrValue = sanitize_text_field($data[$attrValueKey1]);
                    } elseif (isset($data[$attrValueKey2])) {
                        $attrValue = sanitize_text_field($data[$attrValueKey2]);
                    } else {
                        continue;
                    }
                    $attributesArray[] = [
                        'name' => $attrName,
                        'value' => $attrValue,
                    ];
                }
            }

            // Set all attributes at once
            $attributes = [];
            foreach ($attributesArray as $attribute) {
                $taxonomy     = sanitize_title($attribute['name']);
                $attributeObj = new WC_Product_Attribute();
                $attributeObj->set_name($taxonomy);
                $attributeObj->set_position(0);
                $attributeObj->set_options([$attribute['value']]);
                $attributeObj->set_visible(true);
                $attributeObj->set_variation(false);
                $attributes[$taxonomy] = $attributeObj;
            }
            if (!empty($attributes)) {
                $product->set_attributes($attributes);
                $product->save();
            }
            // Handle images from zip
            if ($imagesDir && isset($data['images']) && !empty($data['images'])) {
                $imageFiles = explode('|', $data['images']); // e.g. "img1.jpg|img2.png
                $images = [];
                foreach ($imageFiles as $fileName) {
                    $filePath = $imagesDir . '/' . trim($fileName);
                    if (file_exists($filePath)) {
                        $base64 = 'data:image/' . pathinfo($filePath, PATHINFO_EXTENSION) . ';base64,' . base64_encode(file_get_contents($filePath));
                        $images[] = ['url' => $base64];
                    }
                }
                if (!empty($images)) {
                    $this->uploadImages($images, $productId, true);
                }
              }
           }

            return [
            'success' => true,
            'message' => 'Bulk upload completed',
            'code'    => 200,
            'data'    => [
                'products' => $productsCreated,
                'errors'   => $errors,
                 ],
               ];
           }

How to start Selenium standalone server from a PHP script?

In my PHP script I am using php-webdriver library with Edge webdriver to get data from a web page and I need to start Selenium standalone server from the script. I copied selenium-server-4.35.0.jar, msedgedriver.exe and NodeWebDriver.json to the current user directory C:Userspnfst, and also created 2 bat files for running hab and for running node: selenium-server-hub.bat and selenium-server-node.bat respectively.

NodeWebDriver.json

{
  "capabilities": [
    {
      "browserName": "MicrosoftEdge",
      "maxInstances": 5,
      "seleniumProtocol": "WebDriver",
      "platform": "WINDOWS"
    },
    {
      "browserName": "firefox",
      "maxInstances": 5,
      "seleniumProtocol": "WebDriver",
      "platform": "WINDOWS"
    },
    {
      "browserName": "chrome",
      "maxInstances": 5,
      "seleniumProtocol": "WebDriver",
      "platform": "WINDOWS"
    },
    {
      "browserName": "internet explorer",
      "maxInstances": 1,
      "seleniumProtocol": "WebDriver",
      "platform": "WINDOWS"
    }
  ],
  "proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
  "maxSession": 5,
  "port": 5555,
  "register": true,
  "registerCycle": 5000,
  "hub": "http://Администратор:[email protected]:4444",
  "nodeStatusCheckTimeout": 5000,
  "nodePolling": 5000,
  "role": "node",
  "unregisterIfStillDownAfter": 60000,
  "downPollingLimit": 2,
  "debug": false,
  "servlets": [],
  "withoutServlets": [],
  "custom": {}
}

selenium-server-hub.bat

java -Dwebdriver.edge.driver=msedgedriver.exe -jar ".selenium-server-4.35.0.jar" hub

selenium-server-node.bat

java -Dwebdriver.edge.driver=msedgedriver.exe -jar ".selenium-server-4.35.0.jar" node --config ".NodeWebDriver.json"

Then I tried to start Selenium standalone server from PHP using exec as follows.

Variant 1

$hubCommand = 'C:\Program Files\Java\jdk-24\bin\java.exe -jar "C:\Users\pnfst\selenium-server-4.35.0.jar" hub 2>&1 &';
$nodeCommand = 'C:\Program Files\Java\jdk-24\bin\java.exe -Dwebdriver.edge.driver=C:\Users\pnfst\msedgedriver.exe -jar "C:\Users\pnfst\selenium-server-4.35.0.jar" node --config "C:\Users\pnfst\NodeWebDriver.json" 2>&1 &';
$hubResult = exec($hubCommand, $hubOutput, $hubResult_code);    // start hab
$nodeResult = exec($nodeCommand, $nodeOutput, $nodeResult_code);    // start node

Variant 2

$psHubCommand = 'Start-Process -FilePath "C:\Program Files\Java\jdk-24\bin\java.exe" -ArgumentList "-jar", "selenium-server-4.35.0.jar", "hub" -WorkingDirectory "C:\Users\pnfst" -Verb RunAs';
$psNodeCommand = 'Start-Process -FilePath "C:\Program Files\Java\jdk-24\bin\java.exe" -ArgumentList "-Dwebdriver.edge.driver=msedgedriver.exe", "-jar", "selenium-server-4.35.0.jar", "node", "--config", ".\NodeWebDriver.json" -WorkingDirectory "C:\Users\pnfst" -Verb RunAs';
$hubCommand = "powershell.exe -NonInteractive -NoProfile -ExecutionPolicy Bypass -Command " . escapeshellarg($psHubCommand) . " 2>&1 &";
$nodeCommand = "powershell.exe -NonInteractive -NoProfile -ExecutionPolicy Bypass -Command " . escapeshellarg($psNodeCommand) . " 2>&1 &";
$hubResult = exec($hubCommand, $hubOutput, $hubResult_code);    // start hab
$nodeResult = exec($nodeCommand, $nodeOutput, $nodeResult_code);    // start node

Variant 3

$psHubCommand = 'Start-Process -FilePath "C:\Windows\system32\cmd.exe" -ArgumentList "/c", "C:\Users\pnfst\selenium-server-hub.bat" -WorkingDirectory "C:\Users\pnfst" -Verb RunAs';
$psNodeCommand = 'Start-Process -FilePath "C:\Windows\system32\cmd.exe" -ArgumentList "/c", "C:\Users\pnfst\selenium-server-node.bat" -WorkingDirectory "C:\Users\pnfst" -Verb RunAs';
$hubCommand = "powershell.exe -NonInteractive -NoProfile -ExecutionPolicy Bypass -Command " . escapeshellarg($psHubCommand) . " 2>&1 &";
$nodeCommand = "powershell.exe -NonInteractive -NoProfile -ExecutionPolicy Bypass -Command " . escapeshellarg($psNodeCommand) . " 2>&1 &";
$hubResult = exec($hubCommand, $hubOutput, $hubResult_code);    // start hab
$nodeResult = exec($nodeCommand, $nodeOutput, $nodeResult_code);    // start node

All variants return result code 0 and don’t start hab and node. Variant 2 throws with PowerShell MissingArgument (hub command) and PositionalParameterNotFound (node command) exceptions.
How to properly start a Selenium standalone server from PHP?