“Am I correctly setting up a Laravel REST API project with artisan commands and XAMPP database config?

Is this a good way to setup a laravel project?

composer create-project laravel/laravel [project_name]

Then, navigate into the newly created project directory:
php artisan install:api # (If prompted, feel free to answer: no)
php artisan migrate:reset

Delete the contents of the database/migrations directory.

.env settings — these may depend on your XAMPP/PhpMyAdmin configuration (e.g., port number, user, password):
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=webvill DB_USERNAME=root DB_PASSWORD=

Create a model, controller, and migration with:
php artisan make:model -mc --api [Name]

Start the development server:
php artisan serve
In routes/api.php — define your routes without the /api prefix!

All requests should use URLs like:
http://localhost:8000/api/something

I tried this method, but I’m not sure it’s working correctly.

Unable to retrieve a value after a PRAGMA statment using sqlite3

I’m trying to learn to use php interacting with db.
To connect to sqlite3 I’m using the ADOdb library.
This is the PHP snippet I’m using.


require_once 'ADOdb/adodb.inc.php';

$db = NewADOConnection('sqlite3');

$databasePath = 'test.db';

$db->Connect($databasePath);

$query = $_GET['table'];
$result = $db->Execute($query);
echo $result;
?> 

Using this script I’m able to run queries without any problem, but until I try to run a query like this,
PRAGMA table_info('test');SELECT 1;,
I’m unable to retrieve the value of the second query. Could anyone tell me why? Thanks in advance.

Fatal error with Stripe Class ‘StripeStripe’ not found in Woocommerce

i’m trying to charge customer when they has order status upaid.

and i trigger it by one admin action button from wp-admin side.

problem is when i try to charge i’m getting error StripeStripe’ not found

i check woocommerce stripe getway folder there is no library to call autoload in my code.

need help to fix my code. my code is given below.

function handle_charge_unpaid_order() {
    if (
        !isset($_GET['order_id']) ||
        !wp_verify_nonce($_GET['_wpnonce'], 'charge_unpaid_order_' . $_GET['order_id'])
    ) {
        wp_die('Invalid or missing nonce');
    }

    $order_id = intval($_GET['order_id']);
    $order = wc_get_order($order_id);

    if (!$order || $order->get_status() !== 'unpaid') {
        wp_die('Invalid order or not unpaid');
    }

    if ($order->get_payment_method() !== 'stripe') {
        wp_die('Order does not use Stripe');
    }

    $customer_id   = $order->get_meta('_stripe_customer_id', true);
    $card_sourceid = $order->get_meta('_stripe_source_id', true);

    if (!$customer_id || !$card_sourceid) {
        wp_die('No Stripe customer or saved payment method found.');
    }

    // Load Stripe keys
    $options   = get_option('woocommerce_stripe_settings');
    $test_mode = isset($options['testmode']) && $options['testmode'] === 'yes';
    $secret_key = $test_mode ? $options['test_secret_key'] : $options['secret_key'];

    if (!$secret_key) {
        wp_die('Stripe API key not configured.');
    }
   // ✅ Ensure Stripe SDK is loaded
    if ( ! class_exists( 'StripeStripe' ) ) {
        if ( defined( 'WC_STRIPE_PLUGIN_PATH' ) ) {
            require_once WC_STRIPE_PLUGIN_PATH . '/includes/libraries/stripe-client/init.php';
        } else {
            wp_die('Stripe SDK not found. Please make sure the WooCommerce Stripe plugin is active.');
        }
    }

    StripeStripe::setApiKey($secret_key);

    try {
        $payment_intent = StripePaymentIntent::create([
            'amount' => intval(round($order->get_total() * 100)), // Convert to cents
            'currency' => strtolower(get_woocommerce_currency()),
            'customer' => $customer_id,
            'payment_method' => $card_sourceid,
            'off_session' => true,
            'confirm' => true,
            'metadata' => [
                'order_id' => $order->get_id(),
                'site' => get_bloginfo('name'),
            ],
        ]);

        $order->payment_complete($payment_intent->id);
        $order->add_order_note('Stripe payment successful. PaymentIntent ID: ' . $payment_intent->id);

        wp_redirect(admin_url('admin.php?page=wc-orders&action=edit&id=' . $order_id));
        exit;

    } catch (StripeExceptionCardException $e) {
        $order->update_status('failed');
        $order->add_order_note('Stripe card error: ' . $e->getMessage());
        wp_die('Stripe Card Error: ' . esc_html($e->getMessage()));
    } catch (Exception $e) {
        $order->update_status('failed');
        $order->add_order_note('Stripe charge failed: ' . $e->getMessage());
        wp_die('Stripe Error: ' . esc_html($e->getMessage()));
    }
} ```

Can’t access public property [closed]

I’ve set public property and define it in construct as following :

<?php

use AppModelsPlan;

class ClassB extends Base
{
    public $plan;

    public function __construct()
    {
        $this->plan = new Plan();
    }

    public function viewPlan()
    {
        View::renderTemplate('Plans/view.html', [
        'view' => $plan->getPlans()
        ]);
    }
}

But it says ‘Message: ‘Undefined variable $plan’ !

When I use this instead it’s work !

'view' => $this->plan->getPlans()

Please note I’m using this code in a controller file ( twig ).

Thanks in advance.

How create relation one-to-one for doctrine entities in this case?

I want store meta data of products and categories in separated table i.e. creates tables:

meta_data (id, title, description, ...)
products (id, ..., meta_data_id)
categories (id, ..., meta_data_id)

I create entities with one-to-one relations:

class MetaData
{
    #[ORMId]
    #[ORMGeneratedValue]
    #[ORMColumn(type: Types::INTEGER, unique: true, options: ['unsigned' => true])]
    private int $id;

    ...
}

class Product
{
    #[ORMColumn(type: Types::INTEGER, unique: true, options: ['unsigned' => true])]
    #[ORMId]
    #[ORMGeneratedValue]
    private int $id;

    #[ORMOneToOne(targetEntity: MetaData::class, cascade: ['persist'], orphanRemoval: true)]
    #[ORMJoinColumn(name: 'meta_data_id', unique: true, onDelete: 'CASCADE')]
    private MetaData $metaData;

    ...
}

class Category
{
    #[ORMColumn(type: Types::INTEGER, unique: true, options: ['unsigned' => true])]
    #[ORMId]
    #[ORMGeneratedValue]
    private int $id;

    #[ORMOneToOne(targetEntity: MetaData::class, cascade: ['persist'], orphanRemoval: true)]
    #[ORMJoinColumn(name: 'meta_data_id', unique: true, onDelete: 'CASCADE')]
    private MetaData $metaData;

    ...
}

In this case, foreign keys adds to products and categories tables, but I want adds foreign keys to meta_data table to delete meta data at product/category deletion. How configure entities in this case?

Problem making a .webm to .mp4 conversion page with CloudConvert API and PHP backend

I am making a simple .webm to .mp4 conversion page called upload.html
I am using CloudConvert API and my backend is using PHP. I have a convert.php to do the operation.

The upload.html only has 2 buttons: “Choose File” & “Upload & Convert”.
When I click Choose File and select a 5seconds .webm file, then hit the “Upload & Convert” button, it says:

*Error: Unexpected token '<', "<br />
<b>"... is not valid JSON*

Opening up the developer tool > Network > Response, there’s message:

*<br />
<b>Fatal error</b>:  Uncaught Error: Call to undefined method       CloudConvertModelsJob::setTasks() in .../public_html/convert.php:37
Stack trace:
#0 {main}
  thrown in <b>.../public_html/convert.php</b> on line <b>37</b><br />*

Here’s the convert.php Code:

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
header('Content-Type: application/json');

require 'vendor/autoload.php';

use CloudConvertCloudConvert;
use CloudConvertModelsJob;
use CloudConvertModelsTask;

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Only POST allowed');
    }

    if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        throw new Exception('No valid video uploaded');
    }

    $apiKey = getenv('CLOUDCONVERT_API_KEY');
    if (!$apiKey) {
        throw new Exception('API key not set in environment');
    }

    $cloudConvert = new CloudConvert(['api_key' => $apiKey]);

    // Save uploaded file temporarily
    $tempFile = tempnam(sys_get_temp_dir(), 'upload_') . '.webm';
    if (!move_uploaded_file($_FILES['file']['tmp_name'], $tempFile)) {
        throw new Exception('Failed to save uploaded file');
    }

    // Create job with tasks
    $job = new Job();
    $job->setTasks([
        (new Task('import/upload'))->setName('import-my-file'),
        (new Task('convert'))
            ->setName('convert-my-file')
            ->setInput(['import-my-file'])
            ->setOutputFormat('mp4')
            ->setVideoCodec('h264'),
        (new Task('export/url'))
            ->setName('export-my-file')
            ->setInput(['convert-my-file'])
            ->setInline(false)
            ->setArchiveMultipleFiles(false),
    ]);

    $createdJob = $cloudConvert->jobs()->create($job);

    // Upload file to import task
    $uploadTask = $createdJob->getTasks()->whereName('import-my-file')[0];
    $cloudConvert->tasks()->upload($uploadTask, fopen($tempFile, 'rb'));

    // Wait for job to finish (conversion)
    $cloudConvert->jobs()->wait($createdJob->getId());

    // Get updated job info after completion
    $finishedJob = $cloudConvert->jobs()->get($createdJob->getId());

    // Get export task to fetch converted file URL
    $exportTask = $finishedJob->getTasks()->whereName('export-my-file')[0];
    $files = $exportTask->getResult()->files;

    if (empty($files)) {
        throw new Exception('No converted file returned');
    }

    // Cleanup temporary upload
    unlink($tempFile);

    // Return JSON with job ID and download URL
    echo json_encode([
        'job_id' => $finishedJob->getId(),
        'file_url' => $files[0]->url
    ]);
} catch (Exception $e) {
    if (isset($tempFile) && file_exists($tempFile)) {
        unlink($tempFile);
    }
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
}

I don’t know what is the problem, and don’t know how to fix it. I just want a simple upload .webm file, convert and download in .mp4 file.

I checked the log.txt, it says nothing about the error.
I requested new API key from CloudConvert and replaced the old one with the new one. Problem not fixed.
I’ve make sure the API Key in .htaccess in my web hosting is readable, I’ve tested it by writing a simple php script to ECHO the API Key on the browser.
I have make sure the API Key requested from CloudConvert, the scopes are user.read, user.write, task.read, task.write.
I have checked my web hosting to make sure curl, SSL are enabled.
The CloudConvert PHP SDK is v3.4.2

Laravel Storage url

I was asked to create several websites for a non-profit organization, but using a single database and a single administration area.

I managed to create the admin area and two websites, but I’m having trouble displaying images on the websites.

I have three URLs, which are as follows (I’m on a local environment):

www.admin.test
www.website1.test
www.website2.test 

etc…

The store method of my controller is simple but functional:

$request->validate([
    'title' => 'required',
    'content' => 'required',
    'website_id' => 'required',
]);

$filename = time() . '.' . $request->post_image->extension();

$path = $request->file('post_image')->storeAs(
    'posts_featured_images',
    $filename,
    'public'
);

$post = Post::create([
    'title' => $request->title,
    'slug' => $slugify->slugify($request->title),
    'website_id' => $request->website_id,
    'user_id' => Auth::user()->id,
    'content' => $request->content
]);

$image = new PostImage();
$image->path = $path;
$image->post_id = $post->id;

$post->post_image()->save($image);

I have no problem viewing the image in my administration area (www.admin.test) in the edit view or show with this:

<img src="{{ Storage::url($post->post_image->path) }}" class="img-fluid" width="50%">

However, I don’t know how to display this image on www.website1.test, for example.

In my env file, I added this line: ADMIN_URL=http://admin.test to retrieve it in my views, but it doesn’t work.

I tried this, for example, but it doesn’t work.

<img src="{{ Storage::url(env('ADMIN_URL')) }}/{{ $post->post_image->path }}" alt="Image">

So my question is: is it possible to display my images on all my websites, and if so, how?

Thank you all in advance!

Store class instance in public variable into another class php

I’m new to OOP and I’m using twig.
However I’ve two classes ( different files ) and I want to call some functions from for example classA.php into classB.php.

Now I’m creating a new instance inside classB functions each time I want to call functions from classA.

My question now is.. is it possible to create a public variable in classB to create instance then just call that variable inside any function ?

For example:

classB.php

<?php

use AppModelsClassA

class ClassB extends Base
{
public $classA = new ClassA();

public function test
{
return $classA->functionA();
}
}

I’m trying the above, and I got the following error:

Fatal error: Constant expression contains invalid operations

I don’t know if it’s possible or correct, I need your advise.

Thanks in advance.

PHP manual installation on offline Redhat9

I have Radhat 9.4 that doesn’t connected to the internet. the machine was installed with apache by dnf command “dnf install httpd”, and have internal repository that contains PHP 8.0/
Now I need to install PHP 8.2/3 and I copied the tar.gz installtion and run it withe ./configuration, but Apache still doesnt support PHP.
I noticed that apache try to run php-fpm and I tried to run it from the CLI, and I received an Error “failed to open configuration file ‘/usr/local/etc/php-fpm.conf’. Itried to copy the conf from PHP8.0 but no luck.
What steps should I take to install php on apache on an offline linux machine? I can download and copy packages to this machine.
Thank you very much

Livewire 3 component not rendering inside Laravel Jetstream (Livewire stack) layout

‘m building an admin panel using Laravel 11, Livewire 3, Jetstream (Livewire stack), and DaisyUI. I’ve created a Livewire component, registered the route, and tried to render it inside a Jetstream page—but nothing shows up. The page is blank and there are no error messages.

Created the component:

php artisan make:livewire Admin/Dashboard

Registered the route in routes/web.php:

use AppLivewireAdminDashboard;

Route::middleware(['auth:sanctum', 'verified'])->get('/admin', Dashboard::class);

Tried rendering the component in a Blade view:

<livewire:admin.dashboard />

Also tried:

@livewire('admin.dashboard')

How can I split a 128-bit value into two 64-bit values [closed]

I’m trying to make a function that appends 2 longs into one and back again.

I used the (ac) + (ad) + (bc) + (bd) formula to combine the numbers.

I have searched for and wide (including this site) with no luck as to how to split the number into two.

I’m using PHP which as you know doesn’t have functions to convert floating point numbers into binary or hex.

I used unpack() with the “J*” setting. Each number returned is 8 bytes long.

I would like to be able to split it in the middle.

If anybody has any advice on how I can achieve this I will be forever thankful.

EDIT: I am trying to concat the two long strings into one (hash/ciphertext/aad) so I can do Polynomial multiplication so I can generate a hash for users with PHP versions less than 7.1.

PHP 7.1 and greater’s openssl_encypt() has support for the tags. The versions less than 7.1 don’t.

It’s been a pain due to PHP’s limitations regarding binary data. All implementations of GCM/CCM require data converted to a 128-bit number and the only number that can be 128-bits is a float number.

The implementations I found are too complex when all I want to do is find a way to get GCM/CCM working with PHP versions less than 7.1.

Additionally, you can’t even use openssl to encrypt GCM data if less than 7.1 because it does not provide a way to validate the tag.

PHP examples do NOT tell you this.

Hope this helps.

Hide On Sale products from Shop and Category Pages in WooCommerce [duplicate]

I found the following script to hide on sale products from the shop and category pages in Woocommerce:

function wc_exclude_sale_items_from_shop_page($query) {
    if ( is_admin() || ! $query->is_main_query() ) {
        return;
    }
    if ( is_shop() || is_product_category() ) {
        $query->set('meta_query', array(
            array(
                'key'     => '_sale_price',
                'compare' => 'NOT EXISTS',
            ),
        ));
    }
}

But it’s also hiding some products that do NOT have sale prices. Any ideas on why this might be happening?

Also — how would I adjust the script to also apply to the shop when the admin is logged in (so the admin sees the same thing as a customer) and product search pages?

Send Elementor Form via Webhook to n8n with Hidden Email Field

I need help configuring an Elementor form to send data via webhook to n8n. I want to include two fields: the user’s email (automatically captured since they’ll be logged in) and a YouTube link manually entered by the user.

My goal is to hide the email field in the form and auto-fill it with the logged-in user’s data, as the form will only be available after login.

How can I set this up efficiently in Elementor and ensure the information is correctly sent to my n8n workflow?

How to add file to localhost from another computer

I have a XAMPP-hosted MySQL database on one computer, and I can access it on this computer using the other computer’s IP address. There’s a couple of php files that I can use to interact with the database, and they work fine on this computer. However, in the same directory as those php files (xampp/htdocs/demo/) I want to add another php file, but I want to build it on this computer. There’s tons of stuff out there on accessing localhost on another computer (which I can do no problem) but not much on modifying the localhost directory from another computer.

So, is either of these two things possible:

  1. Actually adding a php file to the localhost directory from this computer (ideal) OR

  2. Creating a php file on this computer (not on localhost) that can still access and modify my database.

?

Thanks! (and let me know if you need more information.)

Sometimes no response is displayed, even though HTTP 200 is returned

I’m building a lightweight personal chatbot that uses the OpenAI Chat API. The chatbot is embedded into a custom HTML/JS frontend and runs on a PHP backend that sends the prompt and gives back the result using curl_setopt($ch, CURLOPT_WRITEFUNCTION, ...).

It works most of the time — but occasionally (especially on the second or third message), the frontend just hangs. In Chrome DevTools I can see the following:

Status: 200 OK
Response time: <300ms (very fast — suspiciously fast)

But: No text is ever rendered in the chat window

The request body is sent correctly and the request completes — but no chunks are received or displayed.

Here’s the php code, I’m using:

<?php

session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
@ini_set('zlib.output_compression', 0);
@ini_set('implicit_flush', 1);
ob_implicit_flush(true);

header('Content-Type: text/plain');
header('Cache-Control: no-cache');
header('Access-Control-Allow-Origin: *');

require_once 'config.php';

$systemPrompt = file_get_contents('prompt.txt');

if (!isset($_SESSION['chat_history'])) {
    $_SESSION['chat_history'] = [
        ["role" => "system", "content" => $systemPrompt]
    ];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $userMessage = trim($input['message'] ?? '');

    if ($userMessage === '') {
        http_response_code(400);
        echo "Leere Eingabe";
        exit;
    }

    $_SESSION['chat_history'][] = ["role" => "user", "content" => $userMessage];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.openai.com/v1/chat/completions");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Content-Type: application/json",
        "Authorization: Bearer " . OPENAI_API_KEY
    ]);

    $chatPayload = [
        "model" => MODEL,
        "messages" => $_SESSION['chat_history'],
        "temperature" => TEMPERATURE,
        "max_tokens" => MAX_TOKENS,
        "stream" => false
    ];

    $fullReply = '';

    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($chatPayload));

    curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($curl, $data) use (&$fullReply) {
        $lines = explode("n", $data);
        foreach ($lines as $line) {
            if (strpos($line, 'data: ') === 0) {
                $jsonStr = substr($line, 6);
                if (trim($jsonStr) === '[DONE]') break;

                $json = json_decode($jsonStr, true);
                if (isset($json['choices'][0]['delta']['content'])) {
                    $chunk = $json['choices'][0]['delta']['content'];
                    echo $chunk;
                    flush();
                    $fullReply .= $chunk;
                }
            }
        }
        return strlen($data);
    });

    curl_exec($ch);
    curl_close($ch);

    $_SESSION['chat_history'][] = ["role" => "assistant", "content" => $fullReply];

} else {
    http_response_code(405);
    echo "Method not allowed";
}

// Fehlerausgabe, falls nötig
if (isset($ch) && curl_errno($ch)) {
    echo "cURL-Fehler: " . curl_error($ch);
    exit;
}

Does anyone have an idea, why this is happening?

What I’ve ruled out:

  • It’s not an invalid API key — most requests work just fine
  • It’s not a missing prompt.txt — it’s read and logged successfully
  • It’s not a quota issue — no errors from OpenAI, no “insufficient quota”
  • It’s not a general connection problem — the server has internet and cURL works
  • It’s not a JS bug on the first request — only later requests (2nd or 3rd) hang