PHP FILAMENT attaching to a model with related table

I’d like to customize the attach select that is shown when i attach a resource to a course.

The model to attach to has a relation to a related table (like a category of the resource).

Table COURSE

Table COURSE_RESOURCE
course_id
resource_id

Table RESOURCE
resource_name
resource_type_id
….

Table RESOURCE_TYPE
resource_type

When attaching a resource to a course with the relationManager, i’d like to be able to use the select to filter on both the resource_name AND the resource_type. Or at least showing the resource_type with the resource_name and not only the resource_name.

The issue is that i have multiple same resource_name that have different resource_type. Right now, i could search by resource_name and their are all showed but i can tell wich select option is related to which resource_type.

I try this (where resourceType is the eloquent model relation belongsTo between the 2 tables resource && resource_type)

AttachAction::make()
->recordSelectSearchColumns([‘resource_name’, ‘resourceType.resource_type’])

but i doesn’t work, it does not make the join in the query.

An other way would be to present a full table of the model to attach to instead of just the select.

Is there a way to setup the attach form to show a full table of resource (with related resource_type column) with filter so that you can select any row to attach to (after eventualy filtering) ?

Any idea ?

How to remove “added” and “view cart” from AJAX “add to cart” buttons on WooCommerce?

I’m currently on WooCommerce with Bricks Builder.

I’d like to hide the appearance and transformation of my “add to cart” button, which is the div below (image attached). I’m on a separate page and it’s an AJAX add-to-cart.

Default item

The problem

When I try to “display:none” the “add” and “view cart” buttons, my element completely disappears.

Does anyone have a solution for completely removing these messages from WooCommerce’s AJAX buttons?

Sonata : how to create a 404 error template?

I can’t create working 404 custom error pages in a production environment, with Sonata 4.13 and Symfony 5.4.

The official Sonata documentation didn’t help me, so I followed the Symfony documentation. I created a file in /templates/bundles/TwigBundle/Exception/error404.html.twig with the following content:

{% extends '@SonataAdmin/standard_layout.html.twig' %}

{% block title %}
    Erreur 404
{% endblock %}

{% block sonata_admin_content %}
<div class="box box-primary">
    <div class="box-body">
        <h1>404 - Page introuvable</h1>
        <p>La page que vous recherchez n'existe pas.</p>
        <p>Vous pouvez <a href="{{ path('home') }}">revenir au Dashboard</a>.</p>
    </div>
</div>
{% endblock %}

This page displays correctly when I access localhost/_error/404, but the sidebar is empty. When I test on the production environment, the same thing happens.

On this 404 error page, I notice that I’m not logged in (my username is not displayed), unlike on the other pages. Maybe the problem is coming from here?

What am I missing?

enter image description here

JCrop Cut Half Resolution of Image

here I am using JCrop as a tool to crop images which will later be used for profile photos.

Previously I tried cropping, for example I wanted to crop an image with a size of 512 x 512. The program ran smoothly, but when I saw the results of the image stored in the image folder, the size was 512 x 256.

How do you keep the height resolution from being cut in half?
Here’s the script, I’m using CodeIgniter 3.

EditUser.php (Controller)

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class EditUser extends CI_Controller {
  function __construct() {
    parent::__construct();
    $this->load->helper('url');
    $this->load->library('image_lib');
  }

  public function upload_crop() {
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_FILES['userfile']['name'])) {
      $config['upload_path'] = './assets/images/foto_profile_pengguna/';
      $config['allowed_types'] = 'jpg|png';
      $config['max_size'] = 2048; // 2 MB

      $this->load->library('upload', $config);
      if ($this->upload->do_upload('userfile')) {
          $uploaded_data = $this->upload->data();
          $uploaded_image = $uploaded_data['full_path'];
          $file_name = $uploaded_data['file_name']; // Dapatkan nama file

          // Load gambar
          $config['image_library'] = 'gd2';
          $config['source_image'] = $uploaded_image;
          $config['maintain_ratio'] = FALSE;
          $config['width'] = 512; // Setel dimensi sesuai keinginan
          $config['height'] = 512;

          $this->image_lib->initialize($config);

          // Tampilkan halaman cropping dengan mengirimkan data yang diperlukan
          $data['uploaded_image'] = base_url('./assets/images/foto_profile_pengguna/' . $uploaded_data['file_name']);
          $data['file_name'] = $file_name; // Kirimkan nama file ke view
          $this->load->view('upload_crop_view', $data);
      } else {
        $data['error'] = $this->upload->display_errors();
        $this->load->view('upload_crop_view', $data);
      }
    } else {
      $this->load->view('upload_crop_view');
    }
  }

  public function crop() {
    $x = $this->input->post('x');
    $y = $this->input->post('y');
    $w = $this->input->post('w');
    $h = $this->input->post('h');
    $file_name = $this->input->post('file_name');

    $image_path = './assets/images/foto_profile_pengguna/' . $file_name;
    $cropped_image_path = './assets/images/foto_profile_pengguna/cropped_' . $file_name;

    // Load gambar menggunakan pustaka CodeIgniter
    $this->load->library('image_lib');
    $config['image_library'] = 'gd2';
    $config['source_image'] = $image_path;
    $config['width'] = $w;
    $config['height'] = $h;
    $config['x_axis'] = $x;
    $config['y_axis'] = $y;

    $this->image_lib->initialize($config);
    $this->image_lib->crop();

    redirect('EditUser/upload_crop');
  }
}

upload_crop_view.php (Views)

<!DOCTYPE html>
<html>
<head>
    <title>Upload and Crop Image</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-jcrop/0.9.15/css/jquery.Jcrop.min.css">
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-jcrop/0.9.15/js/jquery.Jcrop.min.js"></script>
    <script>
        $(function() {

            var cropBoxWidth = 512;
            var cropBoxHeight = 512;

            $('#crop-image').Jcrop({
                aspectRatio: 1, // Menjaga aspek rasio persegi
                setSelect: [0, 0, cropBoxWidth, cropBoxHeight], // Area cropping awal
                onSelect: updateCoords
            });
        });

        function updateCoords(c) {
            $('#x').val(c.x);
            $('#y').val(c.y);
            $('#w').val(c.w);
            $('#h').val(c.h);
        }
    </script>
</head>
<body>
    <?php if (isset($error)) : ?>
        <p style="color: red;"><?php echo $error; ?></p>
    <?php endif; ?>

    <?php if (isset($uploaded_image)) : ?>
    <h2>Upload and Crop Image</h2>
      <form action="<?php echo site_url('EditUser/crop'); ?>" method="post">
          <img src="<?php echo $uploaded_image; ?>" id="crop-image" />
          <input type="text" name="x" id="x">
          <input type="text" name="y" id="y">
          <input type="text" name="w" id="w">
          <input type="text" name="h" id="h">
          <input type="text" name="file_name" value="<?php echo $file_name; ?>">
          <input type="submit" value="Crop">
      </form>
    <?php else : ?>
        <h2>Upload Image</h2>
        <?php echo form_open_multipart('EditUser/upload_crop'); ?>
        <input type="file" name="userfile" size="20" />
        <br /><br />
        <input type="submit" value="Upload and Crop" />
        </form>
    <?php endif; ?>

</body>
</html>

Hope I can get the solution here, thanks a lot

PHP Laravel migration file does not create relation

I want to create a relation between the users-table and my other tabe in php laravel. After migrating this with the command:

  • php artisan migrate:fresh --seed

nothing happens

The migration file:

$table
    ->unsignedBigInteger('updated_from')
    ->nullable()
    ->foreign('updated_from')
    ->references('id')
    ->on('users');

And after refreshing the erd in datagrip there is no relation between the two tables:
enter image description here

There is no relation. The other arrow comes from another table.

Why I get error with request to Google Identity Toolkit

I work with restAPI Identity Toolkit.

I get good response with request

POST https://identitytoolkit.googleapis.com/v1/accounts:sendOobCode

but there is a parameter ‘returnOobLink’ by default it’s false.
When I set it true to get OobCode for building my own custom request, I get error

{error:
    code: 400,
    message: 'INNSUFFICIENT_PERMISSION'
}

Which permission needs?

How to play mp4 video from url in php

I want to play mp4 video from url but not playing..

This is php code mp4.php


$video_file = 'https://opsukrat.in/Test.mp4';

$size = filesize($video_file);

header("Content-Type: video/mp4");

header("Content-Length: ".$size);

readfile($video_file);

This is html code



<video width="480" height="320" controls>

  <source src="mp4.php" type="video/mp4">

</video>

FakerPHP generate names in several locales without titles

I have a script to generate a list of names using FakerPHP in different Locales:

<?php
require_once(__DIR__ . "/vendor/autoload.php");
$gen_num = $sortBy = filter_input(INPUT_GET, 'num2gen', FILTER_SANITIZE_NUMBER_INT, array('options' => array('default' => 30, 'min' => 10, 'max' => 300)));

$faker_langs = ['da_DK', 'sv_SE', 'nb_NO', 'fr_FR', 'pl_PL', 'fi_FI', 'en_GB']; //'de_DE', 
$fakers = [];
foreach ($faker_langs as $l) {
    $fakers[] = FakerFactory::create($l);
}


for ($x = 0; $x < $gen_num; $x++) {
    $lang = rand(0, count($faker_langs) - 1);
    echo $fakers[$lang]->name() . "n";
}

I want this list to validate full names, but the titles that are generated in Polish and German introduce a lot of noise.

I noticed that the Danish formats do not include titles, but the German and Polish do:

Danish

https://github.com/FakerPHP/Faker/blob/main/src/Faker/Provider/da_DK/Person.php

    protected static $maleNameFormats = [
        '{{firstNameMale}} {{lastName}}',
        '{{firstNameMale}} {{lastName}}',
        '{{firstNameMale}} {{lastName}}',
        '{{firstNameMale}} {{middleName}} {{lastName}}',
        '{{firstNameMale}} {{middleName}} {{lastName}}',
        '{{firstNameMale}} {{middleName}}-{{middleName}} {{lastName}}',
        '{{firstNameMale}} {{middleName}} {{middleName}}-{{lastName}}',
    ];

German

https://github.com/FakerPHP/Faker/blob/main/src/Faker/Provider/de_DE/Person.php

    protected static $maleNameFormats = [
        '{{firstNameMale}} {{lastName}}',
        '{{firstNameMale}} {{lastName}}',
        '{{firstNameMale}} {{lastName}}',
        '{{firstNameMale}} {{lastName}}',
        '{{firstNameMale}} {{lastName}}-{{lastName}}',
        '{{titleMale}} {{firstNameMale}} {{lastName}}',
        '{{firstNameMale}} {{lastName}} {{suffix}}',
        '{{titleMale}} {{firstNameMale}} {{lastName}} {{suffix}}',
    ];

Is it possible to omit the {{titleMale}} and {{suffix}} ordo I have to create a new Provider inherriting the de_DE one and overriding the $maleNameFormats for the languages that have titles in their formatters?

GET http://myproject.com/insertData?product_id=1&amount=100&item=shoes 500 (Internal Server Error) [closed]

this is error :- GET http://myproject.com/insertData?amount=100&item=shoes 500 (Internal Server Error)

this is a javascript code :-

          <script type="text/javascript">
            document.addEventListener('DOMContentLoaded', function() {
                var form = document.getElementById('paypal_form');
                form.addEventListener('submit', function() {
                   
                    setData(document.getElementById('amount').value, document.getElementById('item').value);
                   
                });

                function setData(amount, item) {
                    
                    var xhttp = new XMLHttpRequest();
                    xhttp.onreadystatechange = function() { 
                    };
                    xhttp.open("GET", "/insertData? 
                    amount="+amount+"&item="+item, true);
                    xhttp.send();
                }
            });
          </script>

this is a insertdata code :-

          <?php 
          session_start();
         // Include database connection file 
          include_once 'dbConnect.phtml';

         $amount = $_GET['amount'];
         $item = $_GET['item'];
         $status = "pending";

         $insert = $db->query("INSERT INTO product(product_name, 
         price, status1) 
         VALUES('".$item."','".$amount."','".$status."')");

         if (!$insert) {
          die("Error: " . $db->error);
         }

         $last_id = $db->insert_id;

         $_SESSION['product_id'] = $last_id;

I am using laminas framework for develop app with PayPal. but its not save data to databases come this error. I need to fix this.

     'insertData' => [
                'type'    => Literal::class,
                'options' => [
                    'route'    => '/insertData',
                    'defaults' => [
                        'controller' => 
       ControllerViewController::class,
                        'action'     => 'insertData',
                    ],
                ],
            ],

this is a route in module.config.php

Connexion Intermittence: MongoDB from Php7.4

I have problems with intermittence in connection to mongodb since PHP 7.4. I don’t understand why sometimes it fails to connect to ReplicaSet. What can I do ?
I leave the log of my application below.

[18:58] [Worker 1] [109] Process with id 64bf99167c2a42530a2dbd97 has finished
[18:58] [Worker 1] [88] Start processing Process with id 64b920317c2a42530a2dbd72
[18:58] [Worker 1] [109] Process with id 64b920317c2a42530a2dbd72 has finished
[19:00] [Worker 1] [88] Start processing Process with id 64e61827874b0d115f5797d3
[19:00] [Worker 1] [109] Process with id 64e61827874b0d115f5797d3 has finished
[19:00] [Worker 1] [88] Start processing Process with id 64c37883921ed7598d54a694
[19:00] [Worker 1] [109] Process with id 64c37883921ed7598d54a694 has finished
[19:00] [Worker 1] [88] Start processing Process with id 64bf99167c2a42530a2dbd97
[19:00] [Worker 1] [109] Process with id 64bf99167c2a42530a2dbd97 has finished
[19:00] [Worker 1] [88] Start processing Process with id 64b920317c2a42530a2dbd72
[19:00] [Worker 1] [109] Process with id 64b920317c2a42530a2dbd72 has finished
[19:02] [Worker 1] [88] Start processing Process with id 64e61827874b0d115f5797d3
[19:02] [Worker 1] [109] Process with id 64e61827874b0d115f5797d3 has finished
[19:02] [Worker 1] [88] Start processing Process with id 64c37883921ed7598d54a694
[19:02] [Worker 1] [109] Process with id 64c37883921ed7598d54a694 has finished
[19:02] [Worker 1] [88] Start processing Process with id 64bf99167c2a42530a2dbd97
[19:02] [Worker 1] [109] Process with id 64bf99167c2a42530a2dbd97 has finished
[19:02] [Worker 1] [88] Start processing Process with id 64b920317c2a42530a2dbd72
[19:02] [Worker 1] [109] Process with id 64b920317c2a42530a2dbd72 has finished
[19:02] [Worker 1] [132] An error has ocurred on Process 64b920317c2a42530a2dbd72. Error Details: No suitable servers found (`serverSelectionTryOnce` set) on vendor/mongodb/mongodb/src/functions.php line 487 Trace: #0 vendor/mongodb/mongodb/src/functions.php(487): MongoDBDriverManager->selectServer()
#1 vendor/mongodb/mongodb/src/Collection.php(687): MongoDBselect_server()
#2 libs/Mongodb/Collection.php(412): MongoDBCollection->findOne()
#3 models/UserCollection.php(242): AppLibrariesMongodbCollection::findFirst()
#4 config/Injector.php(76): AppCollectionsUserCollection::findFirst()
#5 models/CoreCollection.php(182): AppCollectionsCoreCollection::getUser()
#6 models/ProcessCollection.php(454): AppCollectionsCoreCollection->save()
#7 tasks/ProcessTask.php(112): AppCollectionsProcessCollection->save()
#8 [internal function]: AppTasksProcessTask->AppTasks{closure}()
#9 vendor/php-amqplib/php-amqplib/PhpAmqpLib/Channel/AMQPChannel.php(1055): call_user_func()
#10 [internal function]: PhpAmqpLibChannelAMQPChannel->basic_deliver()
#11 vendor/php-amqplib/php-amqplib/PhpAmqpLib/Channel/AbstractChannel.php(220): call_user_func()
#12 vendor/php-amqplib/php-amqplib/PhpAmqpLib/Channel/AbstractChannel.php(374): PhpAmqpLibChannelAbstractChannel->dispatch()
#13 services/Queue/Worker.php(58): PhpAmqpLibChannelAbstractChannel->wait()
#14 tasks/ProcessTask.php(143): AppServicesQueueWorker->consume()
#15 [internal function]: AppTasksProcessTask->consumeAction()
#16 [internal function]: PhalconCliDispatcher->callActionMethod()
#17 [internal function]: PhalconDispatcherAbstractDispatcher->dispatch()
#18 run(27): PhalconCliConsole->handle()
#19 {main} 
[19:04] [Worker 1] [88] Start processing Process with id 64e61827874b0d115f5797d3
[19:04] [Worker 1] [109] Process with id 64e61827874b0d115f5797d3 has finished
[19:04] [Worker 1] [88] Start processing Process with id 64c37883921ed7598d54a694

php – Warning : mail() verify your SMTP and smtp_port setting

I was trying to make a working contact form using html and php but when i enter the name and email and message then click send, it shows this error
I am using normal local host with php (in cmd : $ php -S localhost:4000)

<br />
<b>Warning</b>: mail(): Failed to connect to mailserver at &quot;localhost&quot; port 25, verify your &quot;SMTP&quot; and &quot;smtp_port&quot; setting in php.ini or use ini_set() in <b>C:UsersBKMHDownloadsYahyai mustn't uplaod to mega but i need my filesProjectsWebsitesHtmlInteresitingGoodDesignePortfoliophpmessage.php</b> on line <b>12</b><br />
Sorry, failed to send your message!

and here is my php code: ( i am new to php )

<?php
  $name = htmlspecialchars($_POST['name']);
  $email = htmlspecialchars($_POST['email']);
  $message = htmlspecialchars($_POST['message']);

  if(!empty($email) && !empty($message)){
    if(filter_var($email, FILTER_VALIDATE_EMAIL)){
      $receiver = "[email protected]"; //enter that email address where you want to receive all messages
      $subject = "From: $name <$email>";
      $body = "Name: $namenEmail: $emailnnMessage:n$messagennRegards,n$name";
      $sender = "From: $email";
      if(mail($receiver, $subject, $body, $sender)){
         echo "Your message has been sent";
      }else{
         echo "Sorry, failed to send your message!";
      }
    }else{
      echo "Enter a valid email address!";
    }
  }else{
    echo "Email and message field is required!";
  }
?>

I spent two hours searching but i couldn’t find any working solution, please help, and thanks

I’m doing a laminas framework tutorial and getting some errors trying to access localhost/album

The error code is LaminasServiceManagerExceptionServiceNotFoundException
File:
D:Projectsvalidationvendorlaminaslaminas-servicemanagersrcServiceManager.php:586

The error message is Unable to resolve service “LaminasDbAdapterAdapterInterface” to a factory; are you certain you provided it during configuration?

Module.php file:

<?php
namespace Album;
use LaminasDbAdapterAdapterInterface;
use LaminasDbResultSetResultSet;
use LaminasDbTableGatewayTableGateway;
use LaminasModuleManagerFeatureConfigProviderInterface;

class Module implements ConfigProviderInterface
{
public function getConfig()
{
return include __DIR__ . '/../config/module.config.php';
}
    public function getServiceConfig()
    {
        return [
            'factories' => [
                ModelAlbumTable::class => function($container) {
                    $tableGateway = $container->get(ModelAlbumTableGateway::class);
                    return new ModelAlbumTable($tableGateway);
                },
                ModelAlbumTableGateway::class => function ($container) {
                    $dbAdapter = $container->get(AdapterInterface::class);
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new ModelAlbum());
                    return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
                },
            ],
        ];
    }
    public function getControllerConfig()
    {
        return [
            'factories' => [
                ControllerAlbumController::class => function($container) {
                    return new ControllerAlbumController(
                        $container->get(ModelAlbumTable::class)
                    );
                },
            ],
        ];
    }
}

module.config.php file:

<?php
namespace Album;
use LaminasRouterHttpSegment;


return [

    'router' => [
        'routes' => [
            'album' => [
                'type'    => Segment::class,
                'options' => [
                    'route' => '/album[/:action[/:id]]',
                    'constraints' => [
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                        'id'     => '[0-9]+',
                    ],
                    'defaults' => [
                        'controller' => ControllerAlbumController::class,
                        'action'     => 'index',
                    ],
                ],
            ],
        ],
    ],

    'view_manager' => [
        'template_path_stack' => [
            'album' => __DIR__ . '/../view',
        ],
    ],
];

modules.config.php file:

<?php

/**
 * List of enabled modules for this application.
 *
 * This should be an array of module namespaces used in the application.
 */
return [
    'LaminasRouter',
    'LaminasValidator',
    'Application',
    'Album',
];

The problem seems to be that the tutorial uses LaminasDb service that isnt there anymore in the modules.config.php file, the tutorial shows a modules.config.php file that is different than mine, I tried adding ‘LaminasDb’ there but this just results in a different error.

Can not display username when using Cordova

My code works perfectly fine when I use it locally and can access the server (using XAMPP).
However, when I run it through Cordova I can not display the username. The username is saved as a $_SESSION variable in the login.php file when the user logs in, but gets the error message Warning: Undefined array key “username”.
The postings of the web application are shown, so I know I can access the server when using Cordova as well.

In the HTML file, the displayUserName() function is called onload which sends a request to displayName.php.

The displayAllPosts() function works.

Any help would be appreciated.

<?php

session_start();
// Establish connection to database
include("connection.php");

header('Access-Control-Allow-Origin: *');
//header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
//header('Access-Control-Allow-Headers: Content-Type');



// Setting the vairables for the email and password.
$email = $_POST['email'];
$password = $_POST['password'];

//SQL query for retrieving the username and userID where email is 
//current email and password is current password.
$sql_user = "SELECT username, user_id FROM users WHERE email = '$email' AND password = '$password'";

// Store the result from the sql query
$result_user = mysqli_query($link, $sql_user) or die (mysqli_connect($link));

// Check if there is data returned.
// If num of rows returned is 0, then there is no registered user with
// the provided email and password
if ((mysqli_num_rows($result_user) < 1)){
    echo 1;
}

// Otherwise the username and password has been found in the db.
else{
    //Saving the result as an associative array called row.
    $row = mysqli_fetch_array($result_user);
    //Setting the session variable for username and user id. 
    $_SESSION['username'] = $row['username'];
    $_SESSION['user_id'] = $row['user_id'];
    
    echo 2;
}
// Close the connection to the db
$conn->close();

?>

<?php

session_start();
// Establish connection to database
include("connection.php");

header('Access-Control-Allow-Origin: *');
//header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
//header('Access-Control-Allow-Headers: Content-Type');

// Session vaiable for username when logged in. 
echo $_SESSION['username'];

?>

function displayUserName() {

    $.ajax({
        url: 'http://MY_IP_ADDRESS/test/server/displayName.php',
        type: 'GET',
        data: {},
        success: function (userdata) {
            // Not found in db. Provide feedback to user.
            if (!userdata) {
                document.getElementById("displayname").innerHTML = "No text";
            }
            //Successfully found in db and username will be displayed.
            if (userdata) {
                document.getElementById("displayname").innerHTML = "Inloggad: " + userdata;
            }
        }
    });
};

function displayAllPosts() {

    $.ajax({
        url: 'http://MY_IP_ADDRESS/test/server/displayAllPosts.php',
        type: 'GET',
        data: {},
        dataType: "json",
        success: function (data) {
            //Check if there is data. 
            if (!data) {
                document.getElementById("displayAllPosts").innerHTML = "no data.";
            }
            else {
                //Create a constant to determine in which element the postings 
                //should be displayed. This element will be the parent element.
                const allPosts = document.getElementById('displayAllPosts');
<body onload="displayUserName(); displayAllPosts()">
    <!-- Here is the logo -->
    <div class="container pt-3 pb-3">
        <div class="row">
            <div class="justify-content-center">
                <img src="img/hth.png" alt="Here to help logo" width="300" height="100">
            </div>
        </div>
    </div>
    <!-- Display the username that is logged in-->
    <div class="container pt-3 pb-1">
        <div class="row">
            <div class="col d-flex justify-content-end" id="displayname">

            </div>
        </div>
    </div>

    <!-- Display the name of the section-->
    <div class="container pt-1 pb-3">
        <div class="row">
            <div class="col d-flex justify-content-center">
                <h1>Inlägg</h1>
            </div>
        </div>
    </div>
    
    <!-- Div to display all posts-->
    <div class="container pt-1 pb-3">
        <div class="row">
            <div class="event-wrapper" id="displayAllPosts">

            </div>
        </div>
    </div>

I have issue to retrive post thumbnail with rest api

i have two site. main site and blog site. both of them are wordpress. i want show my latest post from
blog site to main site. but I have issue to retrieve post thumbnail.
all thing is OK except Thumbnail.

wp_get_attachment_image_src(get_post_thumbnail_id($post['id']), 'thumbnail') 

retrive false.

function display_latest_blog_posts() {
    ob_start(); // Start output buffering

    // Replace with the URL of your blog site
    $blog_site_url = 'http://www.blog.domain.com';

    // Get the latest blog posts using WP REST API
    $response = wp_remote_get($blog_site_url . '/wp-json/wp/v2/posts?per_page=3');
    $posts = wp_remote_retrieve_body($response);

    if (!empty($posts)) {
        $posts = json_decode($posts, true);

        echo '<div class="latest-blog-posts">';
        
        foreach ($posts as $post) {
            echo '<div class="post">';
            echo '<h2 class="post-title">' . $post['title']['rendered'] . '</h2>';
            echo '<p class="post-date">' . date('F j, Y', strtotime($post['date'])) . '</p>';
            
            if (has_post_thumbnail($post['id'])) {
                $thumbnail_url = wp_get_attachment_image_src(get_post_thumbnail_id($post['id']), 'thumbnail')[0];
                echo '<img src="' . $thumbnail_url . '" class="post-thumbnail" alt="' . $post['title']['rendered'] . '">';
            }
            
            echo '</div>';
        }
        
        echo '</div>';
    }

    $output = ob_get_clean(); // Get the buffered content
    return $output;
}

Does anyone know where the problem is?

i have two site. main site and blog site. both of them are wordpress. i want show my latest post from
blog site to main site. but I have issue to retrieve post thumbnail.
all thing is OK except Thumbnail.