How to post response to another URL after close iframe in php

Good day, i am trying to find solutions to post/reroute a response receive from a URL1 (ccRtnResponse1) to URL2 (ccTxnResponse2) after closing iframe in function URL1

<script>

    document.getElementById('mpiReqForm').submit();

    // Get iframe and loading circle elements
    const iframe = document.getElementById('transactionIframe');
    const loadingCircle = document.getElementById('loading-circle');

    // Hide loading circle and show iframe when the iframe has finished loading
    iframe.onload = function() {
        loadingCircle.style.display = 'none';
    };

    // Function to remove the iframe
    function removeIframe() {
        if (iframe) {
            iframe.remove(); // Remove the iframe element from the DOM
        }
    }

    // Listen for messages from the iframe
    window.addEventListener("message", function(event) {
        console.log('Message received:', event.data);
        // Check if the message is to close the iframe
        if (event.data === "closeIframe") {
            removeIframe(); // Call the function to remove the iframe
            // response receive from function ccRtnResponse1 will be pass to function ccTxnResponse2
        }
    });
</script>

so after receive the response

  public function ccRtnResponse1(Request $request)
{
  // This is in the iframe response, after processing
  echo '<script>window.parent.postMessage("closeIframe", "*");</script>';

  $data=$request->all;
  // repost the response $data to function ccTxnResponse2 after 'close iframe"

}

i would like to pass the $data to URL2(ccTxnResponse2)

  public function ccTxnResponse2(Request $request)
{
  dd($request->all());
}

i have tried to use appendChild but it seems not working. I hope to get some suggestion here. thank you

How to add CSS to text located in submit.php file

A contact form forms part of a single-page website. It is situated at the bottom of the page. When the form is completed successfully by a user a ‘success’ message is generated and displayed immediately above the contact form. I wish to add CSS to the text of that message. Specifically, centering the text and changing the colour.

The form is controlled by contact.php and submit.php. The actual text is contained in an ‘echo’ statement in submit.php.

contact form code

<div class="container">
     <div id="responseMessage"></div>
    <div class="wrapper">
        <div class="form-inner-cnt" id="contact-page">
            <!--  -->
            <!-- <form action="" method="post" class="cnt-form"> -->
             <form id="contactForm" method="post" class="cnt-form">
                
                <!-- Status message -->
                                
                <!-- Form fields -->
                <div class="form-input">
                    <input type="text" name="name" id="name" placeholder="Name" value="" required="">
                </div>
                <div class="form-input">
                    <input type="email" name="email" id="email" placeholder="Email" value="" required="">
                </div>
                <div class="form-input">
                    <textarea name="message" id="message" placeholder="Message" required=""></textarea>
                </div>
                </div>
                <input type="submit" name="submit" class="btn" value="SEND">
            </form>
        </div>
    </div>

Part of submit.php

        // Send email
                // @mail($toEmail, $emailSubject, $htmlContent, $headers);

                //   echo json_encode(['status' => 'success', 'message' => 'Thank you for your message. We will respond as soon as possible.']);


            if (mail($toEmail, $emailSubject, $htmlContent, $headers)) {

                echo json_encode(['status' => 'success', 'message' => 'THANK YOU FOR YOUR MESSAGE. WE WILL RESPOND AS SOON AS POSSIBLE.']);
            } else {
                echo json_encode(['status' => 'error', 'message' => 'Failed to send your message.']);
            }
} 
?>

Any assistance would be much appreciated

Why can’t I get my n:href attribute to work?

I’m still pretty new to the whole nette/latte framework and I’m currently trying to figure out pagination. I have tried to mostly follow the official documentation (which “somewhat” worked), but as soon as I try to implement the n:href attribute, I get the following error:

PHP message: PHP Fatal error:  Uncaught LatteCompileException: Unexpected attribute n:href 

This is where the error occurs:

    {if !$paginator->isFirst()}
        <a n:href="default, 1">First</a>
        &nbsp;|&nbsp;
        <a n:href="default, $paginator->page-1">Previous</a>
        &nbsp;|&nbsp;
    {/if}

    Page {$paginator->getPage()} of {$paginator->getPageCount()}

    {if !$paginator->isLast()}
        &nbsp;|&nbsp;
        <a n:href="default, $paginator->getPage() + 1">Next</a>
        &nbsp;|&nbsp;
        <a n:href="default, $paginator->getPageCount()">Last</a>
    {/if}

I really hope someone can help me here.

I have already tried to change the code from the documentation in a couple of different ways, but that didn’t work either 🙁

Like this for example:

    {if !$paginator->isFirst()}
        <a n:href="default, $paginator->getPage() = 1">First</a>
        &nbsp;|&nbsp;
        <a n:href="default, $paginator->getPage() - 1">Previous</a>
        &nbsp;|&nbsp;
    {/if}

I have also tried to leave out the n:href all together, but keeping it seems to be my best bet for solving the problem.

This main part of my php code:

$latte = new Engine;
$latte->setTempDirectory(__DIR__ . '/temp');
$latte->setAutoRefresh(true); 

$dsn = "mysql:host=" . DBHOST . ";dbname=" . DBNAME . ";charset=UTF8";
$database = new Connection($dsn, DBUSER, DBPASS);
$articles = [];
$articles = $database->fetchAll('SELECT * FROM production.requests WHERE archived = "1" ORDER BY order_date ASC;');
 
// Paginator setup
$paginator = new Paginator;
$paginator->setItemCount(count($articles));
$paginator->setItemsPerPage(2); // items per page
$paginator->setPage(1); // actual page number

$items = [];
$items = $database->fetchAll('SELECT * FROM production.requests WHERE archived = "1" ORDER BY order_date ASC LIMIT ? OFFSET ?', $paginator->getLength(), $paginator->getOffset());

$parameters = [
    'items' => $items,
    'paginator' => $paginator,
];

$latte->render(__DIR__ . '/templates/main/test.latte', $parameters);

Unable to get Laravel Spatie/Browsershot working with Puppeteer, Ubuntu 24.04, PHP 8.3, Chrom & Nginx

Environment:

  • PHP 8.3
  • Laravel 11
  • Ubuntu 24.04 LTS
  • NGINX
  • Node (v18.19.1) (latest for today)
  • Spatie/Browsershot (Puppeteer, Chrome 128.0.6613.119)

Issues:

  1. Spatie wanting me to install outdated Node/Puppeteer versions (https://spatie.be/docs/browsershot/v4/requirements). And we all want the latest.
  2. Even if we follow Spatie instructions, we get Permissions errors (www-data user cannot run Chrome or has no permissions to create temp directories).
  3. Other Chrome versions (chromium-browser or non-snap .deb installations) methods do not work (php8.3-fpm does not belong to Snap cgroup or other issues with permissions).
  4. Since we want to use the latest soft versions, some packages are missing.

PHP Ratchet websocket listening + sending

I need to establish communication in PHP with a websocket server that is hosted on a node. The first part is to establish a connection to listen for responses from the ws server. The second is to be able to send my own commands and track responses in the listener from the first part. I am using the symfony project and the ratchet/pawl package.

I have created such a client to establish a connection and send messages:

<?php

namespace AppWebSocket;

use RatchetClientWebSocket;
use RatchetClientConnector;
use ReactEventLoopLoop;
use PsrLogLoggerInterface;

class WebsocketClient
{
    private $connection;
    private $loop;
    private $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->loop = Loop::get();
        $this->logger = $logger;
    }

    public function connect(string $url)
    {
        $connector = new Connector($this->loop);

        $connector($url)->then(function (WebSocket $conn) {
            $this->connection = $conn;
            dump('Connected to WebSocket');

            $conn->on('message', function ($msg) {
                dump("Received message: {$msg}");
                $this->onMessage($msg);
            });

            $conn->on('close', function ($code = null, $reason = null) {
                dump('Connection closed ({$code} - {$reason})');
            });
        }, function (Exception $e) {
            dump("Could not connect: {$e->getMessage()}");
        });
    }

    public function send(string $message)
    {
        if ($this->connection) {
            $this->connection->send($message);
        } else {
            echo "No connection established.n";
        }
    }

    private function onMessage($message)
    {
        $this->logger->info("Received message: {$message}");
    }

    public function run()
    {
        $this->loop->run();
    }

    public function close()
    {
        if ($this->connection) {
            $this->connection->close();
        }
    }
}

I also created a symfony command that sets up the ws server listening:

<?php

namespace AppCommand;

use AppWebSocketWebsocketClient;
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputInterface;
use SymfonyComponentConsoleOutputOutputInterface;
use SymfonyComponentConsoleStyleSymfonyStyle;

class WebsocketListenCommand extends Command
{
    protected static $defaultName = 'app:listen-websocket';
    private $webSocketClient;

    public function __construct(WebsocketClient $webSocketClient)
    {
        parent::__construct();
        $this->webSocketClient = $webSocketClient;
    }

    protected function configure(): void
    {
        $this
            ->setDescription('Listens for and processes messages from WebSocket');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);

        $io->success('Listening for WebSocket messages...');

        $this->webSocketClient->connect('ws://x.x.x.x:y');

        $this->webSocketClient->run();

        return Command::SUCCESS;
    }

}

After running the above command, everything works fine. It receives responses in real time.

I would then like to send messages to the websocket server and track the response (while keeping the listening I set up earlier). It injects the service anywhere in the code and tries to send a message:

$this->webSocketClient->send('{"some json, doesnt matter"}');

When trying to use the send method, it doesn’t see any connection and can’t send the message. I have tried setting up the connection myself during send, but then my listener stops responding. Where does the problem lie? Perhaps ZeroMQ or some other solution needs to be used here? I would appreciate your help.

How to calculate pay rate from worked time without using if statement

I am trying to calculate workers pay rate from their worked time. For example if workers go to each client house the number of hours or minutes or hours and minute they spent there, the rate will be calculated from a fixed pay rate($10).
Bellow is the code I was able to create

 $varWorkHour = '00:30';
    $varPayRate = 10.00;
    $varWorkTime = 10.00;
    if ($varWorkHour == '1:00') {
        $varWorkTime = (100 / 100) * $varPayRate;
    } else if ($varWorkHour == '00:45') {
        $varWorkTime = (85 / 100) * $varPayRate;
    } else if ($varWorkHour == '00:30') {
        $varWorkTime = (50 / 100) * $varPayRate;
    } else if ($varWorkHour == '00:15') {
        $varWorkTime = (15 / 100) * $varPayRate;
    }


    echo $varWorkTime;

The code worked
But the problem is I don’t want to use if statement, as you can see the code is limited to 1 hour below and there are some cases where workers can work up to 5 hours and more. Using if statement on that will be exhausting.
Please how can I calculate the pay rate from worked time dynamically without using if statement.

Doctrine querybuilder DATE_FORMAT / DATE_ADD in addSelect not working

I’m having some problems with DATE_FORMAT / DATE_ADD inside a createQueryBuilder

My code:

$em = $this->getEntityManager()->
createQueryBuilder()->
select('jo')->
addSelect('DATE_FORMAT(DATE_ADD(jo.createdAt, INTERVAL 14 DAY), "%Y-%m-%d") as deleteDate')->
from(JobOfferEntity::class, 'jo')->
where('jo.isDeleted = :isDeleted')->
setParameter('isDeleted', 0);

I’m getting floow error:

[Syntax Error] line 0, col 55: Error: Expected DoctrineORMQueryLexer::T_COMMA, got '14'

Can anybody help me?

Validation error message do not match log error message in Laravel excel validation

How can I resolve an issue where my log error messages are correct, but the validation error messages displayed to the user show a different dose number than expected? Here’s my code for logging and validating doses for vaccines, but the row number in the validation errors doesn’t match the log output.


public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            $data = $validator->getData();

            foreach ($data as $key => $row) {
                $vaccine = $row['vaccine'];
                Log::info('$vaccine'.$vaccine);
                $inventory = Inventory::where('name', $vaccine)->where('inventory_type_id', 15)->first();

                if (!$inventory) {
                    Log::error("The vaccine '{$vaccine}' does not exist.");
                    $validator->errors()->add("vaccine", "The vaccine '{$vaccine}' does not exist.");
                } else if (isset($row['given_doses']) && (int)$row['given_doses'] > (int)$inventory->dose_numbers) {
                    $totalDoses=$inventory->dose_numbers;
                    $message="The DOSE set for '$inventory->name.' is  '$totalDoses' any dose given above '{$totalDoses}' should not be added.";
                    Log::info("Dose numbers for '{$inventory->name}': {$totalDoses}");
                    Log::info("Processing row {$key}: Vaccine ' {$vaccine}', Given Doses: '{$row['given_doses']}', Inventory Dose Numbers: '{$inventory->dose_numbers}'");

                    Log::error($message);
                    $validator->errors()->add($key, $message);
                }
            }
        });
    }

Here is the output of my log

[2024-09-05 13:59:08] local.INFO: Dose numbers for ‘FMD’: 25
[2024-09-05 13:59:08] local.INFO: Processing row 2: Vaccine ‘ FMD’, Given Doses: ’30’, Inventory Dose Numbers: ’25’
[2024-09-05 13:59:08] local.ERROR: The DOSE set for ‘.FMD.’ is ‘.25.’ any dose given above ’25’ should not be added.

and here is the message displayed in the view
There was an error on row 2. The DOSE set for ‘FMD.’ is ‘5’ any dose given above ‘5’ should not be added.

It should print the exact numbers of doses in both messages. Log is displaying corrext values and view is not.

how i learn node js after working with laravel for 2 years

Title: How can I transition from Laravel PHP to building production-level applications with Node.js?

Question: I’ve been working with Laravel and PHP for a while, but now I’m looking to switch my tech stack to Node.js. While I have a basic understanding of Node.js and Vue.js, I’m aiming to build production-level applications.

Could you suggest a learning path and key steps to follow for mastering Node.js? Specifically, I want to learn:

Best practices for building scalable, maintainable Node.js applications.
How to structure large Node.js projects, especially in the context of full-stack applications.
Essential tools and libraries (e.g., Express.js, authentication, security, etc.) for building production-level systems.
Tips on transitioning from Laravel to a Node.js ecosystem and how I can leverage my existing knowledge.

Any recommended resources, courses, or guidelines for this transition would be appreciated!

How to map exceptions to repsonse http status code in PHP [closed]

While API development I tried to guess the response status code of requests in a error handler. In most of the known frameworks in the PHP universe there is an error handler, where I get a Throwable and there is a Throwable::getCode() (documentation).

From my point of view this code is more an identifier, than a status code. My best practice is using the current timestamp as code, so I can find the corresponding place in my source code very fast. If I need a return status code I would extend the exception and add a statusCode property.

After a research I saw so many solutions, where developers use the code as return status code. So I am interested in a something like a default PHP exception mapper to status code without using the existing code as status code or at least a best practice to do so. Is there a open source solution or am I on the wrong path?

Laravel error with php artisan migrate in mysql

Can you help me with this error? I can’t migrate my file in mysql.
I’m running the latest version of laravel when i migrate in the terminal.

When i run:

php artisan migrate

I get the following error:
SQLSTATE[HY000]: General error: 1005 Can’t create table agricultures1.archives (errno: 150 “Foreign key constraint is incorrectly formed”) (Connection: mysql, SQL: alter table archives add constraint archives_farmers_id_foreign foreign key (farmers_id) references farmers (id) on delete cascade)

Auto Update Not Working On Filament Table Widget

I’m using a service that makes an API call to return data for me. I would like this data to be updated every 60 seconds. I’m aware that by default, widgets update every 10 seconds, however, my data doesn’t seem to ever update after it’s initial load.

I currently have this within my TopPages widget:

public function table(TablesTable $table): TablesTable
    {
        return $table
            ->query(TopPage::query())
            ->columns([
                TextColumn::make('page')
                    ->label('Page')
                    ->getStateUsing(fn ($record) => $record['page']),
                TextColumn::make('visitors')
                    ->label('Visitors')
                    ->getStateUsing(fn ($record) => number_format($record['visitors'])),
                TextColumn::make('pageviews')
                    ->label('Page Views')
                    ->getStateUsing(fn ($record) => number_format($record['pageviews'])),
            ]);
    }

and this within my TopPage model:

use Sushi;

    protected $rows;

    public function getRows(): array
    {
        $plausibleAnalyticsService = new PlausibleAnalyticsService();

        $topPages = $plausibleAnalyticsService->fetchTopPages();

        Log::info('TopPage model getRows method called');

        return $topPages;
    }

How can I have my data update every 60 seconds? I’ve tried adding the following, but it doesn’t seem to make the api call ever again:

->poll('60s');

Delete messages in a telegram bot

I’m writing a telegram bot to delete spam from a channel where the bot is administrator (with permission to delete messages)

I’m doing some tests using PHP and telegram-bot-sdk 2.0

I’m able to answer to messages using the bot, but if I try to delete a specific message nothing happens, and the method always returns false

require 'vendor/autoload.php';
use TelegramBotApi;
$client = new Api('[api key here]');
$last_update_id=0;
while(true){
    $response = $client->getUpdates(['offset'=>$last_update_id, 'timeout'=>5]);
    if (count($response)<=0) continue;
    foreach ($response as $r){

        //Get the message somebody sent
        $last_update_id=$r->getUpdateId()+1;
    $message=$r->getMessage();
        $messageId = $message['message_id'];
    $chat = $message['chat'];
    $chatId = $chat['id'];
        
        //Log to console the message received
        echo "Somebody said: ".$message['text']." with message id: ".$messageId." on chat ".$chatId."n";
        
        //Answering works
        $ret = $client->sendMessage(['chat_id' => $chatId, 'text' => 'I'm deleting your message!']);
    
        //Deleting doesn't work
    $ret = $client->deleteMessage([ 'chat_id' => $chatId, 'message_id' => $messageId]);
    echo "ret:".($ret?"true":"false");
    }
}

Any Advice?

I’m not even 100% sure deleteMessage() is a method of $client (according the documentation it seems so, but it’s not totally clear) because if it mispell the method on purposes like deleteMessagx() I get false and no error.

Trying to use MAMP and accessing phpMyAdmin returns en error “mysqli is missing” [duplicate]

It all started a couple days ago trying to setup Hesk via MAMP. It was giving me an error during installation I honestly cannot remember, so I decided to try reinstalling MAMP and see if it weould fix the problem.

Now it’s worse than before, I; ve done multiple clean reainstall (also tried re-downloading the setup) but every time I try to access phpMyAdmin it gives me always the same error, which is:

“The mysqli extension is missing. Please check your PHP configuration. See our documentation for more information.”

I’m pretty new to this, so I have honestly no clue on where I can even start looking for a solution in a case like that.

The fact that disturbs me more is that before all that it was working, maybe I was using an older MAMP version? I honestly dont know.
I’ve also done a clean unistall helping me with Revo to remove every possible thing left, and it didnt help either.