Trouble implementing redis cache in php laminas

I have installed php redis in my local system and have added the redis adapter via the composer command:
composer require laminas/laminas-cache-storage-adapter-redis

I tried following this documentation:
https://docs.laminas.dev/laminas-cache/v3/storage/adapter/#redis-adapter

I am having trouble setting up the service and the factory files for the same

So far I have defined the options in a config file ‘redis.local.php’:

return [
    'redis-cache' => [
        'adapter' => [
            'name' => 'redis',
            'options' => [
                'ttl' => 3600,
                'server' => [
                    'host' => '127.0.0.1',
                    'port' => 6379,
                ],
            ],
        ],
        'plugins' => [
            [
                'name' => 'exception_handler',
                'options' => [
                    'throw_exceptions' => true,
                ],
            ],
        ],
    ]
];

and tried to add the options via the factory:

class RedisCacheServiceFactory implements FactoryInterface
{
    public function __invoke(ContainerInterface $container, $requestedName, ?array $options = null): RedisCacheService
    {
        $config = $container->get('config');

        return new RedisCacheService($config['redis-cache']);
    }
} 

and then try to typecast it as a StorageInterFace object (might be doing something wrong here):

class RedisCacheService
{
    public function __construct(private StorageInterface $cacheStorage)
    {
    }
}

What is the best way to generate dynamic videos from template in php or laravel? [closed]

I was trying to find a way to generate videos from some templates with a mechanism similar to what happens with DOMpdf that allow to inject a blade, that can use dynamic variables to generate different content based on data, to generate a dynamic PDF that can store dynamic variables. I know that there is FFMPEG but it is not used directly to do so or maybe i don’t understand how to do it. Is there someone that found a better way? a simple and efficient way to accomplish that task?

i tried to find some resources online but there were very few answers to my problem.

Add percentage to price during wpallimport [duplicate]

I have a wordpress site using wpallimport to import from suppliers, the price they provide is wholesale pricing. The structure is:

productcode  01-4231
statuscode  A
netprice  3.01
freestock  12

I wish to add a percentage of 20% to the netprice, what would the php function be? And should I place netprice in regular_price aswell as have the function?

$cost = $product->price; //Get product price
if($product->price > 0){ //If shipping fee needs to be applied
   $cost += 40%; //Add percentage
}

Issue with DataTables Editor PHP Library After Migrating to Composer

Problem:
I’m having an issue with DataTables Editor PHP after migrating from a 3rd-party library to using Composer. Everything was working fine when I was using the old 3rd-party library, but after switching to Composer, I can see the data in the table, but when trying to add data, the data comes back empty.
Old Code (With 3rd-Party Library):

When using the older version of DataTables Editor (version 1.4.2), the following setup worked correctly:


<?php

include( "../3rdParty/DataTables-1.10.7/extensions/Editor-PHP-1.4.2/php/DataTables.php" );
use
    DataTablesEditor,
    DataTablesEditorField,
    DataTablesEditorFormat,
    DataTablesEditorJoin,
    DataTablesEditorValidate;

$klantendata = Editor::inst( $db, 'KlantenGroep' )
    ->pkey( 'id' )
    ->field(
        Field::inst( 'KlantenGroep.name' ),
        Field::inst( 'KlantenGroep.mobielehelptekst' )
    );

    $data = $klantendata->process($_POST)
    ->data();

echo json_encode( $data );

Explanation:

  • I was using an older version of DataTables Editor PHP (1.4.2), and this code worked perfectly for displaying and adding data to the KlantenGroep table.
  • The database connection was managed using a custom DatabaseConfig class and passed into DataTablesDatabase.

New Code (With Composer Package):

After migrating to Composer and installing “datatables.net/editor-php”: “^2.3”, I updated the code to reflect the new setup:

<?php

require_once '../bootstrap.php';
require_once '../db_config.php';

$sql_details = DatabaseConfig::getDetails();
$db = new DataTablesDatabase($sql_details);

use
    DataTablesEditor,
    DataTablesEditorField,
    DataTablesEditorFormat,
    DataTablesEditorJoin,
    DataTablesEditorValidate;

$klantendata = Editor::inst($db, 'KlantenGroep')
    ->pkey('id')
    ->field(
        Field::inst('KlantenGroep.name'),
        Field::inst('KlantenGroep.mobielehelptekst')
    );

$data = $klantendata->process($_POST)
    ->data();

echo json_encode($data);

Current Issue:

  • Library Version: “datatables.net/editor-php”: “^2.3”
  • Problem: Data is successfully displayed in the table, but when trying to add or edit data, the data comes back empty in the response.
  • Error: There’s no specific error message, but no data is being added or updated.

Question:

Why is the data being returned empty when adding or editing, despite using the same logic that worked in the previous version with the 3rd-party library? Could this be an issue with the new version of the DataTables Editor PHP library, or am I missing something in my code migration?

Any guidance or suggestions on how to resolve this issue would be greatly appreciated!

Steps I’ve Tried:

  • Verified the PDO connection works correctly by executing manual queries.
  • Verified that $_POST contains the expected data by dumping it.
  • Ensured the structure and syntax of the new code match what is required by the new version.

Convert JWK to PEM key using native PHP

How to convert a JWK key into a pem key in PHP without using third-party libraries?
Example of JWK

{
      "kty": "RSA",
      "kid": "FftONTxoEg",
      "use": "sig",
      "alg": "RS256",
      "n": "wio-SFzFvKKQ9vl5ctaYSi09o8k3Uh7r6Ht2eJv-hSaZ6A6xTXVIBVSm0KvPxaJlpjYPTCcl2sdEyXlD2Uh1khUKU7r9ON3rpN8pFHAere5ig_JGVEShxmt5E_jzMymYnSfkoSW44ulevQeUwP_MiC5VC1KJjTfD73ghX0tQ0-_RjTJJ2cLyFC4VFNboBMCVioUrz8IA3c0KIOl507qswQvMsh2vBTMDDSJfippAGLzUiWXxUlid-vyOC8GCtag61taSorxCw14irk-tsh7hWjDDkSTFn2gChPMfXXj10_lCv0UG29TVUVCAsay4pszzgmc4zwhgSsqQRd939BJexw",
      "e": "AQAB"
    }

Expected result

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwio+SFzFvKKQ9vl5ctaY
Si09o8k3Uh7r6Ht2eJv+hSaZ6A6xTXVIBVSm0KvPxaJlpjYPTCcl2sdEyXlD2Uh1
khUKU7r9ON3rpN8pFHAere5ig/JGVEShxmt5E/jzMymYnSfkoSW44ulevQeUwP/M
iC5VC1KJjTfD73ghX0tQ0+/RjTJJ2cLyFC4VFNboBMCVioUrz8IA3c0KIOl507qs
wQvMsh2vBTMDDSJfippAGLzUiWXxUlid+vyOC8GCtag61taSorxCw14irk+tsh7h
WjDDkSTFn2gChPMfXXj10/lCv0UG29TVUVCAsay4pszzgmc4zwhgSsqQRd939BJe
xwIDAQAB
-----END PUBLIC KEY-----

I try to convert with this code and the key is almost similar to the required result, but still differs from the signature required for verification. Can someone help me with this?

    private function jwkToPem($jwk) {
        $modulus = $this->base64UrlDecode($jwk['n']);
        $exponent = $this->base64UrlDecode($jwk['e']);

        if (ord($modulus[0]) > 0x7f) {
            $modulus = "x00" . $modulus;
        }

        $modulus = "x02" . $this->asn1Length(strlen($modulus)) . $modulus;
        $exponent = "x02" . $this->asn1Length(strlen($exponent)) . $exponent;

        $rsaPublicKey = "x30" . $this->asn1Length(strlen($modulus . $exponent)) . $modulus . $exponent;

        $rsaOID = "x30x0Dx06x09x2Ax86x48x86xF7x0Dx01x01x01x05x00";

        $publicKeyBitString = "x03" . $this->asn1Length(strlen($rsaPublicKey) + 1) . "x00" . $rsaPublicKey;

        $fullKey = "x30" . $this->asn1Length(strlen($rsaOID . $publicKeyBitString)) . $rsaOID . $publicKeyBitString;

        return "-----BEGIN PUBLIC KEY-----n" . chunk_split(base64_encode($fullKey), 64) . "-----END PUBLIC KEY-----n";
    }
    private function asn1Length($length) {
        if ($length <= 0x7F) {
            return chr($length);
        }
        $temp = ltrim(pack('N', $length), "");
        return chr(0x80 | strlen($temp)) . $temp;
    }

Laravel – React Native : Sanctum getting 302 redirects to homepage

I have a laravel backend and a react native frontend, I want to protect the api routes that are hit from my react native app with axios, for this i installed laravel sanctum.

My current workflow is : I log or register user with email and password, get a sanctum token that I store using AsyncStorage in my app, then I send this token on the headers of all my axios calls uisng interceptors.

THE ISSUE:

Routes protected by auth:sanctum middleware get a 302 Found, then redirected to homepage / 200 OK.

How I create a token in backend:

$token = $user->createToken($request['device_name'])->plainTextToken;

How I add my Bearer toke to headers (I verify they are attached via console log):

if (token) 
{
    console.log('SANCTUM: Adding bearer token to axios: ' + token);
    axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
}

How I protect my routes:

Route::get('/auth/sanctum/user', 'AppHttpControllersApiAuthController@sanctumUser')->middleware('auth:sanctum');

In my RedirectIfAuthenticated middleware I tried changing it after reading some other posts but any i change I made it did not made any difference…

<?php

namespace AppHttpMiddleware;

use AppProvidersRouteServiceProvider;
use Closure;
use IlluminateSupportFacadesAuth;

class RedirectIfAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  Closure  $next
     * @param  string|null  ...$guards
     * @return mixed
     */

    //Added && !$request->wantsJson() part

    
    public function handle($request, Closure $next, ...$guards)
    {
        $guards = empty($guards) ? [null] : $guards;
 
        
        foreach ($guards as $guard) 
        {
//Added !$request->wantsJson()            
if (Auth::guard($guard)->check()  && !$request->wantsJson() ) 
            {
//Tried changing this too                
return redirect(RouteServiceProvider::HOME);
            }
        }
        

        return $next($request);
    }
}

In my Kernel http:

protected $middlewareGroups = [
        'web' => [
            //AppHttpMiddlewareEncryptCookies::class,
            IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
            //IlluminateSessionMiddlewareStartSession::class,
            //IlluminateSessionMiddlewareAuthenticateSession::class,
            IlluminateViewMiddlewareShareErrorsFromSession::class,
            AppHttpMiddlewareVerifyCsrfToken::class,
            IlluminateRoutingMiddlewareSubstituteBindings::class,
        ],
        
        
        'api' => [
            //EnsureFrontendRequestsAreStateful::class,
            IlluminateRoutingMiddlewareThrottleRequests::class.':api',
            IlluminateRoutingMiddlewareSubstituteBindings::class,
        ],
        
    ];

sanctum.php file

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Stateful Domains
    |--------------------------------------------------------------------------
    |
    | Requests from the following domains / hosts will receive stateful API
    | authentication cookies. Typically, these should include your local
    | and production domains which access your API via a frontend SPA.
    |
    */

    'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'localhost,127.0.0.1,127.0.0.1:8000,::1')),

    /*
    |--------------------------------------------------------------------------
    | Expiration Minutes
    |--------------------------------------------------------------------------
    |
    | This value controls the number of minutes until an issued token will be
    | considered expired. If this value is null, personal access tokens do
    | not expire. This won't tweak the lifetime of first-party sessions.
    |
    */

    'expiration' => null,

    /*
    |--------------------------------------------------------------------------
    | Sanctum Middleware
    |--------------------------------------------------------------------------
    |
    | When authenticating your first-party SPA with Sanctum you may need to
    | customize some of the middleware Sanctum uses while processing the
    | request. You may change the middleware listed below as required.
    |
    */

    'middleware' => [
        'verify_csrf_token' => AppHttpMiddlewareVerifyCsrfToken::class,
        'encrypt_cookies' => AppHttpMiddlewareEncryptCookies::class,
    ],

];

auth.php file:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        
        'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => AppModelsUser::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
            'throttle' => 60,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Password Confirmation Timeout
    |--------------------------------------------------------------------------
    |
    | Here you may define the amount of seconds before a password confirmation
    | times out and the user is prompted to re-enter their password via the
    | confirmation screen. By default, the timeout lasts for three hours.
    |
    */

    'password_timeout' => 10800,

];

How to insert data from php for multiple read Prolog functions

I have a Prolog program that I connected with php.
I call the Prolog file from php as follows:

$cmd = "swipl -f /path/to/my_file/prolog.pl -g test,halt -t 'halt(1)'"; exec( $cmd, $output); print_r($output);

With the exec() function i can see an array with the output obtained, but the problem is that in the Prolog code i have ‘read()’ function that allows me to insert a value. The problem is that i donโ€™t know how to handle multiple Prolog read functions from php.
Does anyone know a way to solve my problem?
The code of my prolog program is as follows:

start:- write('-----------------------------------------------------------------------'), nl, write(' Welcome'), nl, write('-----------------------------------------------------------------------'), nl, choices.

choices:- read_choices, read(S), ((S == 1; S == one) -> Reply = choice1; ((S == 2; S == two) -> Reply = choice2; ((S == 3; S == three) -> Reply = choice3; ((S == 4; S == four) -> Reply = exit_choice; (Reply = unknown) )))), nl, (Reply == exit_choice -> exit_from_program; (Reply == unknown -> (write('Reply not recognized'), start); (selection(Reply), end_guide(Reply), execute_again('Do you need help?')) )), nl.

read_choices:- write('Make a choice:'), nl, write('1. Choice 1'), nl, write('2. Choice 2'), nl, write('3. Choice 3'), nl, write('4. Exit'), nl, write('Insert choice: ').

execute_again(Text) :- nl, write(Text), nl, read(S), ((S==s ; S == si) -> start; ((S == n ; S == no) -> exit_from_program; (write('Reply not recognized'), execute_again(Text)) )).

end_guide(R):- nl,nl,nl, write(R), write(' ended'), nl.

exit_from_program:- write('Exit, Bye'),nl.

exit_from_program:- write('Closed by the user'),nl.

selection(choice1):- write('choice1 selected').
selection(choice2):- write('choice2 selected').
selection(choice3):- write('choice3 selected').

I would like to find a way to use more prolog read functions in the same program, without querying the knowledge base each time. I’m using swi-prolog

Stuck at (erno: 150 “Foreign key constraint is incorrectly formed,”)

I’m new to learning Laravel 11, and I’m stuck with the (erno: 150 “Foreign key constraint is incorrectly formed,”) and despite trying various suggestions Iโ€™ve seen, I still can’t resolve it. Could you please help me identify where I went wrong and how to fix it?

This is the expenses table

 public function up(): void
    {
        Schema::create('expenses', function (Blueprint $table) {

            $table->id();
            $table->increments('category_id');
            $table->foreign('category_id')->references('id')
            ->on(table:'categories')->onDelete('cascade')->onUpdate(action:'cascade');
            $table->decimal('amount',8, 2); 
            $table->date('entry_date'); 
            $table->timestamps();
            $table->engine = 'InnoDB';

        });
    }

This is the categories table

   public function up(): void
    {
        Schema::create('categories', function (Blueprint $table) {

            $table->increments('id');
            $table->string('category_name'); 
            $table->string('description')->nullable(); 
            $table->timestamps();
        }); 
    }

I need the foreign key category_id in the expenses table to be connected to the categories table. When I update a category, I want the category_id in the expenses table to also update, and the same goes for deletion. If a specific category_name is deleted, I want the corresponding records in the expenses table to be removed as well.

Unable to start firefox geckodriver in Symfony Panther using Ubuntu linux cronjob unless user is logged in

I have some web scraping and screeshotting using Symphony Panther. That worked flawlessly on my dev machine. With some adaptions I made it work on a Ubuntu 22 server also. Now I wanted to do it as a cron job.
I added

/usr/bin/php /usr/local/bin/composer --working-dir /opt/mybot/ start >> /var/log/mybot/cron.log 2>&1

As a cron job. While normale scraping worked fine, as soon as I want to create a firefox screenshot I get an exception
PHP Fatal error: Uncaught RuntimeException: Could not start firefox. Exit code: 1 (General error). Error output: /system.slice/cron.service is not a snap croup

However as long as I am logged into that machine via SSH (without doing anything else) the cron job runs fine without any exception. That puzzles me a bit (and makes it hard to debug to be fair).

Is there something I can do, so that it works unattended?

Fixed shortcode download button for all digital product WooCommerce [duplicate]

I’m using woocommerce and have “virtual” and “downloadable” products. I want to create a shortcode to display a “Download” button for these products. Because there are so many products, I want to have a fixed shortcode to use for all products, not shortcode like [download id=”123″].

I tried using this code and use [download_button] in short descreption but it doesn’t work

function download_button_shortcode( $atts ) {
    global $product;
    $download_files = $product->get_downloads();
    $download_url = isset( $download_files[0]['file'] ) ? $download_files[0]['file'] : '';
    $button = '<a href="' . esc_url( $download_url ) . '" class="button">Download</a>';
    return $button;
}

add_shortcode( 'download_button', 'download_button_shortcode' );

cansome one help me connect the php to my sql? [duplicate]

Fatal error: Uncaught Error: Class “mysqli” not found in
C:xampphtdocsStudy Spacedata.php:10 Stack trace: #0 {main} thrown
in C:xampphtdocsStudy Spacedata.php on line 10

How to fix it? I already delete what some of you told me – I already removed the ; tag. Can some one help me?

Some say delete XAMPP but I can’t delete it because some of my important files are in there.

Can I typehint a php enum?

I want to refactor my codebase from MyCLabs Enums to PHP’s native enum’s. I’m already running into a few small issues:

  1. How can I typehint that an argument or return type must be an enum?
  2. How can I check if a value is an enum?

The best I can do with regards to typehinting is typehinting object.
The best I can do for checking if a value is an enum is with with a ReflectionClass, eg:

if (
    is_object($value)
    && (new ReflectionClass($value))->isEnum()
) {
    // it's an enum.
}

Without these simple checks, it feels like refactoring to native enums is a step backwards. Am I approaching it incorrectly?

Laravel 8.75 doesn’t convert custom rule into a message

I am using Laravel 8.75 and I want to validate fields. I have created a custom rule to validate money.

The rule looks like this:

<?php

namespace AppRules;

use IlluminateContractsValidationRule;

class FlexibalCurrencyRule implements Rule
{
    private $regex = '/^([0-9]{1,10})([.,][0-9]{1,2})?$/';

    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return preg_match($this->regex, $value);
    }

    /**
     * Get the validation error message.
     *
     * @return string | array
     */
    public function message()
    {
        return "currency";
    }
}

It is very plain and simple. Then in my controllers I do the following:

$requestDto = json_decode($request->getContent(), true);

$validator = Validator::make($requestDto, [
    'name' => 'required|max:100',
    'price' => ['required', new FlexibalCurrencyRule],
]);

if ($validator->fails()) {
    // Send response to browser
}

When I call the endpoint my validation messages contain the following:

    "price": {
        "App\Rules\FlexibalCurrencyRule": []
    }

As you can see Laravel doesn’t call the message() function. It just prints the class name. From what I understand it should call the message() function and return ‘currency’ as the validation rule. How can I convert a custom rule into a string message instead of the class name being returned?

extra numbers attached to my values (PHP) [duplicate]

I’m facing a very odd phenomenon when trying to separate the whole numbers and decimals from a float value.

<?php

echo "<br>" . numToWords(1004712896.17);

function numToWords($value) : String
{   
    // $words is used to store the translated string
    $words = "";
    print "<br>VALUE: $value";
    $whole = floor($value);
    print "<br>WHOLE: $whole";    
    $deci = $value - $whole;
    print "<br>DECI: $deci";

    // continue to translate numbers into words
    ...
    return $words;
}

The out put shows the decimal part having some extra numbers attached at the end:

VALUE: 1004712896.17
WHOLE: 1004712896
DECI: 0.16999995708466001004712896

I noticed that the last 12 numbers are the whole-number part of my value. Also, it is not 0.17 as what I entered, but is 0.1699999…

I can get back 17 if I multiply it by 100 and ceil() the result, but still, the extra numbers are present in my result:

$deci = ceil(($value - $whole) * 100);

the output:

DECI: 17001004712896

So… What have I done wrong? I don’t think memory corruption is the cause as I tried to close the tab and re-open it, and even closed my browser and re-open it, the problem persists. And memory overflow is not the problem, since nothing changed even after I’ve reduced the value to the range of thousands.

Is there something I must do before performing any calculation to prevent this, or is this a bug of PHP?

Using XAMPP Version 8.0.30 on FireFox (Latest).

Edit:

trying another method, by using the string equivalent of the value, and then locate the position of the period, and separate the 2 parts into 2 strings, still, the extra numbers are attached to the substring, even when I specifically said I only want 2 characters for my decimal string:

$valstr = strval($value);
print "<br>VALSTR: $valstr";
$pos = strpos($valstr, ".", 0);
$intstr = substr($valstr, 0, $pos);
$decstr = substr($valstr, $pos+1, 2);
print "<br>POS: $pos";
print "<br>IntStr: $intstr";
print "<br>DecStr: $decstr";

output:
VALSTR: 8712896.34
POS: 7
IntStr: 8712896
DecStr: 34008712896 // supposed to be 34 only

I’m starting to think this is a bug in PHP…