How to replace hyperlink dynamically using PHP

I want to replace the following hyperlinks dynamically

from

<a href="/xsearch2?q=some search/21">21</a>

to

<a href="/xsearch2?q=some search&page=21">21</a>

how can I do that dynamically

have tried the following

preg_replace('#<a.*?>([^>]*)</a>#i', '<a href="/xsearch2?q='.$key.'&page=$1">$1</a>', $pagination);

but its changing the hyperlinks also, just want to remove the last slash / from hyperlinks and add &page=

How can I integrate stripe with flutter frontend and php backend?

I want to use my own payment form to process payments using flutter frontend and php backend. The form will be created with the following fields: amount, card holder name, card number, expiry date, cvv and a submit button in flutter. I dont want to use stripe’s payment form.

I have created an account with stripe and have the publishable and secret keys. ( test account)

Now when I click the submit button after the form has been filled up I want to create a stripe token (which uses the publishable key) and send the token details to my php backend, which will then process the payment and return / success /error codes. The php backend will use the secret key provided by stripe.

Is it possible to do this. I am do so using javascript and php library from stripe in our web application.

If you could guide me as to how to do this it will be of great help. Is this the right way to use your own payment form for flutter / php

PHP inheritance in constructor

I’m doing tests.
Given this code snippet

<?php

class Point
{
    public $x;
    public $y;

    public function __construct($x, $y) {
        $this->x = $x;
        $this->y = $y;
    }
}

class Point3D extends Point
{
    public $z;

    public function __construct($x, $y, $z) {
        $this->z = $z;
    }
}

$p = new Point3D(1, 2, 3);
echo sprintf('(%d, %d, %d)', $p->x, $p->y, $p->z);

I’m confused because the correct answer seems to be :

(0,0,3)

But $x and $y are not initialized in child class.
__parent() is not called
When I run the code in a sandbox, it does give the expected answer
When I ask ChatGPT about it, he gives the answer I would have given : $x, $y are not initialized before… => fatal error

The question is why both me and ChatGPT are wrong
What’s the principle here ?

How to prevent sorting of options in a SELECT control of Elementor Addon

I came across one issue with the Elementor while checking for the custom select dropdown
Below is my code, I am using with the custom widget

Value of key in a option are number or integer and not string

<?php
$this->add_control( 'Legacy', [
    'type' => ElementorControls_Manager::SELECT,
    'label' => 'Legacy',
    'options' => array_replace([
        '20' => esc_html__( 'Linear', 'elementor' ),
        '10' => esc_html__( 'Radial', 'elementor' ),
    ]),
] );
?>

The expected result in a select dropdown should be

Linear
Radial

Right?

But, when I see the result, it says

Radial
Linear

What I think is Elementor is filtering the options by key automatically before rendering

I am unable to find any filters or hooks associated with this

Do any of you have a solution to prevent this filtering of options and display as passed in the ‘options’ argument?

Attempt to read property “ConnID” on bool

i was checking the affected_rows but i experience such bug from my model. my model code below

namespace AppModels;

use CodeIgniterModel;

class ContactModel extends Model {
    public function saveData($data)
    {
        $db= ConfigDatabase::connect();
        $builder = $db->table('message');
        $res = $builder->insert($data);
        if ($res->connID->affected_rows>=1) 
        {
            return true;
        } 
        else 
        {
            return false;
        }
    }
}

PHP Fatal error: implements the Serializable interface, which is deprecated. Implement __serialize() and __unserialize

Getting this error in php 8 while the error is coming from page below.

PHP Fatal error: During inheritance of FacebookFacebookApp, while implementing Serializable: Uncaught Exception: Deprecated Functionality: FacebookFacebookApp implements the Serializable interface, which is deprecated. Implement __serialize() and __unserialize() instead (or in addition, if support for old PHP versions is necessary)

The file is

<?php
/**
 * Copyright 2017 Facebook, Inc.
 *
 * You are hereby granted a non-exclusive, worldwide, royalty-free license to
 * use, copy, modify, and distribute this software in source code or binary
 * form for use in connection with the web services and APIs provided by
 * Facebook.
 *
 * As with any software that integrates with the Facebook platform, your use
 * of this software is subject to the Facebook Developer Principles and
 * Policies [http://developers.facebook.com/policy/]. This copyright notice
 * shall be included in all copies or substantial portions of the software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */
namespace Facebook;

use FacebookAuthenticationAccessToken;
use FacebookExceptionsFacebookSDKException;

class FacebookApp implements Serializable
{
    /**
     * @var string The app ID.
     */
    protected $id;

    /**
     * @var string The app secret.
     */
    protected $secret;

    /**
     * @param string $id
     * @param string $secret
     *
     * @throws FacebookSDKException
     */
    public function __construct($id, $secret)
    {
        if (!is_string($id)
          // Keeping this for BC. Integers greater than PHP_INT_MAX will make is_int() return false
          && !is_int($id)) {
            throw new FacebookSDKException('The "app_id" must be formatted as a string since many app ID's are greater than PHP_INT_MAX on some systems.');
        }
        // We cast as a string in case a valid int was set on a 64-bit system and this is unserialised on a 32-bit system
        $this->id = (string) $id;
        $this->secret = $secret;
    }

    /**
     * Returns the app ID.
     *
     * @return string
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Returns the app secret.
     *
     * @return string
     */
    public function getSecret()
    {
        return $this->secret;
    }

    /**
     * Returns an app access token.
     *
     * @return AccessToken
     */
    public function getAccessToken()
    {
        return new AccessToken($this->id . '|' . $this->secret);
    }

    /**
     * Serializes the FacebookApp entity as a string.
     *
     * @return string
     */
    public function serialize()
    {
        return implode('|', [$this->id, $this->secret]);
    }

    /**
     * Unserializes a string as a FacebookApp entity.
     *
     * @param string $serialized
     */
    public function unserialize($serialized)
    {
        list($id, $secret) = explode('|', $serialized);

        $this->__construct($id, $secret);
    }
}

I understand that i need to replace serialize and unserialize with __ but i am not getting desired result

when i did __serialize and __unserialize , the error comes up with 2 abstract method used

Get post’s author data in a shortcode within the WordPress loop

I am building a block theme for WordPress.

I wrote a shortcode function that is supposed to output the message “By [author’s display name with author’s link]”.
More specifically, I am trying to use it in the search result loop (main loop for the search result template).

function auteur_par(){
    $auteur = get_the_author();
    $auteur_nom = get_the_author_meta('display_name', $auteur);
    $auteur_url = get_the_author_meta('user_url', $auteur);
    return '<p>Par <a href="' . $auteur_url . '" target="_self" class="wp-block-post-author-name__link">' . $auteur_nom . '</a></p>';
}
add_shortcode('auteur_par', 'auteur_par');

I also tried using get_the_author_meta directly:

function auteur_par(){
    $auteur_nom = get_the_author_meta('display_name');
    $auteur_url = get_the_author_meta('user_url');
    return '<p>Par <a href="' . $auteur_url . '" target="_self" class="wp-block-post-author-name__link">' . $auteur_nom . '</a></p>';
}
add_shortcode('auteur_par', 'auteur_par');

Both don’t work work when I use it as a shortcode within the “Modèle de publication” block (I can’t find what the english name is for this block, it’s the block under the query loop block in the outline). On the page, the paragraph is there, but the variables are empty.
I made a similar function using get_the_modified_date() and that one works perfectly. I don’t understand why it works for the modification date but not for the author.

I tried the solutions referenced in this post and this post but it doesn’t work.

Xdebug for php in Visual Studio code – how to set up and allow breakpoints

Ive read most all of the posts about setting up pgp xdebug for VS code but no solution for me. Ive installed VS code on a new laptop (thats relevant because I know what else is installed and theres no multiple instance of php – but there seems to be!!)
Ive installed XAMP which includes php 8.2.12 on a win11 pc.
the php -v shows

Copyright (c) The PHP Group
Zend Engine v4.2.12, Copyright (c) Zend Technologies
    with Xdebug v3.3.2, Copyright (c) 2002-2024, by Derick Rethans`
the PHP.ini says `zend_extension = c:xamppphpextphp_xdebug.dll
xdebug.start_with_request = yes
xdebug.client_port = 9900
xdebug.client_host = 127.0.0.1
xdebug.default_enable=1
xdebug.remote_enable = 1
xdebug.remote_autostart = 1
xdebug.remote_log="C:xamppapachelogsxdebug.log"

the json settings in VScode are

   "workbench.colorTheme": "Visual Studio Light",
   "debug.allowBreakpointsEverywhere": true,
   "php.executables": { "v8.2": "//xampp//php//php.exe" },
   "launch": {      
       "configurations": [  {
           "name": "Listen for Xdebug",
           "type": "php",
           "request": "launch",
           "port": 9900,
           "pathMappings": {
               "c:/xampp/php/ext": "${workspaceFolder}"
           }
       }
   ]]
   }
}`


According to all the posts Ive read that should do it but on trying to debug a simple php I get this error 

   `Failed loading C:phpextphp_xdebug-2.6.1-7.2-vc15-nts-x86_64.dll`

Now Im no expert but this seems to be saying its trying to run php 7.2 and wants the xdebug  2.6.1. non thread safe   xdebug.dll  
BUT I can find NO other instance of php.exe on the PC - where in VS code is it looking for c:phpext   a folder which doesnt exist   - I cant find in VS code where such settings exist or how to tell VS code to look in right folder (in this case c:xamppphpext)

FWIW Im using RobertLu's php debug extension though Ive tried all others available. On previous laptop some time ago I did have some success using Felix Beckers php debug externsion but that is no longer appearing in VSCode list of available extensions

Any comments or suggestions gratefully received

  

PHPStan Configuration Error in TYPO3 Extension: Alias Loader Already Registered

I’m encountering an issue while configuring PHPStan for a TYPO3 extension (TYPO3 v13.4.1, PHP 8.2, DDEV environment).

I have a custom extension and need to configure PHPStan to use rules from an additional package while avoiding TYPO3 core code. To achieve this, I created a custom ddev command to run PHPStan within the DDEV container. However, when I execute the command, I get the following error:

/var/www/html/vendor/bin/phpstan analyse -c phpstan.neon
PHP Fatal error: Uncaught RuntimeException: Cannot set the alias loader, as it is already registered! in /var/www/html/packages/my_extension/vendor/typo3/class-alias-loader/src/ClassAliasMap.php:72

Here is the relevant part of my composer.json file for the extension:

"require-dev": {
"friendsofphp/php-cs-fixer": "3.64.*",
"phpstan/phpstan": "1.12.*",
"phpstan/extension-installer": "1.4.*",
"saschaegerer/phpstan-typo3": "1.10.*",
"captainhook/captainhook": "5.23.*"
}

Observations:

  • When I run the standard phpstan analyse command, the analysis executes successfully using my custom phpstan.neon configuration. However, it includes errors related to TYPO3 core code, which suggests that TYPO3-specific rules are not being applied.
  • The same configuration works correctly in another environment running TYPO3 v12 and PHP 8.2. I have compared both environments but haven’t found any significant differences.

What I’ve tried:

  • Ensuring the configurations and dependencies are identical in both environments.
  • Checking the PHPStan, extension-installer, phpstan-typo3 and TYPO3-related documentation, but I couldn’t find a solution.
  • Searching online for similar issues, but nothing has resolved the problem so far.

Question:
What might be causing this issue, and how can I resolve it? Any suggestions or insights are greatly appreciated. Thank you!

Greetings, Chanyss921.

How to achieve reactivity without reloading the component when responding/rendering inertia-laravel

problem of creating a shopping cart in laravel inertia vue bundle – I want to use transitionGroup to animate products in the cart, however the component reloads when I get information from laravel, the cart is in session memory.
my code looks like:
ProductComponent:

   methods: {
        addToCart(id) {
            router.visit(`/cart/add/${id}`, {
                method: 'post',
                onSuccess: () => {
                    console.log('Product added to cart');
                },
                preserveScroll: true, 
            });
        }
    }

cart:

            <TransitionGroup 
                name="cart-items-anim" 
                >
                <HeaderCartItem
                    v-for="item in cart"
                    :key="item.product.id"
                    :item="item.product"
                    :qty="item.qty"
                >
                </HeaderCartItem>
            </TransitionGroup>

controller:

  public function addToCart($id)
    {
        $product = Product::findOrFail($id);
        $cart = session('cart', []);
        $found = false;

        foreach ($cart as &$item) {
            if ($item['product']['id'] === $product->id) {
                $item['qty'] += 1;  
                $found = true;
                break; 
            }
        }
        if (!$found) {
            $cart[] = [
                'product' => $product,  
                'qty' => 1,           
            ];
        }
        session(['cart' => $cart]);
    }

HadleInertiaRequest:

return array_merge(parent::share($request), [
    'cart' => fn () => $request->session()->get('cart', []),

Maybe there are better ways to work with the shopping cart than I’ve come up with?

How to use both HTML2PDF and FPDF in a multipage PDF document

I am trying to create a PDF document that is about 12 pages long. This document includes images as well as information from the database that will need to be pulled through. I am using various scripts from fpdf.org. I would like to use both HTML2pdf.php and fpdf.php to allow me to do multiple functions in one document. I started the document with a class in fpdf called class PDF_CircularText. Can I add a second class for html2pdf halfway through the code when I need it?

This is how I started the document and it works great, but now I want to add an extra class for PDF_HTML(); but still keep PDF_CircularText();

require('fpdf.php');

$pdf = new PDF_CircularText();

$pdf->AddFont('kids','','kids.php');
$pdf->AddFont('BENETOpti-Black','','BENETOpti-Black.php');

$pdf->AddPage();
$pdf ->Image('images/background.png',0, 0, 210, 0, 'PNG');

XAMPP: after install php 8 MySQL shutdown unexpectedly INNODB warnings

Help.
I have installed xampp 3.2.2 for a long time with php 5.6, inside the xampp folder i have another folder with a php 7.4.3.
Today i put another folder with php 8.2.12, after putting the data in the folder i launched xampp-control.exe, it asked me the language and i confirmed. After i see that the old xampp mysql doesn’t start anymore the mysql and it shows me the following log:

2024-11-28 11:50:50 1a9c InnoDB: Warning: Using innodb_additional_mem_pool_size is DEPRECATED. This option may be removed in future releases, together with the option innodb_use_sys_malloc and with the InnoDB's internal memory allocator.
2024-11-28 11:50:50 6812 [Note] InnoDB: innodb_empty_free_list_algorithm has been changed to legacy because of small buffer pool size. In order to use backoff, increase buffer pool at least up to 20MB.

2024-11-28 11:50:50 6812 [Note] InnoDB: Using mutexes to ref count buffer pool pages
2024-11-28 11:50:50 6812 [Note] InnoDB: The InnoDB memory heap is disabled
2024-11-28 11:50:50 6812 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
2024-11-28 11:50:50 6812 [Note] InnoDB: _mm_lfence() and _mm_sfence() are used for memory barrier
2024-11-28 11:50:50 6812 [Note] InnoDB: Compressed tables use zlib 1.2.3
2024-11-28 11:50:50 6812 [Note] InnoDB: Using generic crc32 instructions
2024-11-28 11:50:50 6812 [Note] InnoDB: Initializing buffer pool, size = 16.0M
2024-11-28 11:50:50 6812 [Note] InnoDB: Completed initialization of buffer pool
2024-11-28 11:50:50 6812 [Note] InnoDB: Highest supported file format is Barracuda.
InnoDB: No valid checkpoint found.
InnoDB: A downgrade from MariaDB 10.2.2 or later is not supported.
InnoDB: If this error appears when you are creating an InnoDB database,
InnoDB: the problem may be that during an earlier attempt you managed
InnoDB: to create the InnoDB data files, but log file creation failed.
InnoDB: If that is the case, please refer to
InnoDB: http://dev.mysql.com/doc/refman/5.6/en/error-creating-innodb.html
2024-11-28 11:50:50 6812 [ERROR] Plugin 'InnoDB' init function returned error.
2024-11-28 11:50:50 6812 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2024-11-28 11:50:50 6812 [Note] Plugin 'FEEDBACK' is disabled.
2024-11-28 11:50:50 6812 [ERROR] Unknown/unsupported storage engine: InnoDB
2024-11-28 11:50:50 6812 [ERROR] Aborting

Thank you

Permission to write in a directory

I have programmed a gallery on my website. In this gallery there is an upload function. When I try to upload a file (I tried .jpg .png), I get an error message that the directory is not writable.
I have changed the permission in FileZilla to 777 for the directory, but it does not work.

And it is not the file size

Specifications:

  • Languages: PHP
  • OS: Ubuntu 24.04

How to send emails from a different authenticated domain

I have authenticated domain . Now I want my users sending mail from that domain to able to choose the from_address of mail. They send mail within the domain using sendgrid, then the from address of the mail should be user’s own mail id. Mail reached to the receiver should be sent from the user themselves.
It is possible to achieve the scenario?

<?php

namespace AppServices;

use SendGrid;
use SendGridMailMail;
use IlluminateSupportFacadesLog;

class SendGridEmailService
{
   
    public function sendEmail($to, $subject, $htmlContent, $fromEmail = null, $fromName = null)
    {
        try {
            // Use authenticated domain from config
            $fromEmail = $fromEmail ?? config('mail.from.address');
            $fromName = $fromName ?? config('mail.from.name');

            $email = new Mail();
            $email->setFrom($fromEmail, $fromName);
            $email->setSubject($subject);
            $email->addTo($to);
            $email->addContent("text/html", $htmlContent);

            $response = $this->sendGrid->send($email);

            // Log successful send
            if ($response->statusCode() == 202) {
                Log::info('Email sent successfully', [
                    'to' => $to,
                    'subject' => $subject,
                    'status' => $response->statusCode()
                ]);
                return true;
            }

            // Log any unexpected response
            Log::warning('Email send returned unexpected status', [
                'status' => $response->statusCode(),
                'body' => $response->body()
            ]);

            return false;
        } catch (Exception $e) {
            Log::error('SendGrid Email Error: ' . $e->getMessage(), [
                'to' => $to,
                'subject' => $subject
            ]);

            return false;
        }
    }
}

I have been trying to find the solution for so long in docs and other places. I really am looking forward to achieve this functionality.