Display sql query result (from textarea input) into a table without knowing the number of columns

It starts off with the user having to input their query from a textarea.

<div class="querybar">
        <div class="form-item">
            <form action="" method="POST" class="simple-form">
            <textarea id="sqlquery" name="sqlquery" rows="3" cols="120" placeholder="Type your query here"></textarea>
        </div>
        <div class="form-item">
            <input type="submit" name="submit" value="Submit">
            </form>
        </div>
    </div>

and then it should display the result of the query–if its a select statement–into a table regardless of the number of columns
(example: I have productlist table which has 4 columns, and orders table with 8 columns, and it should be able to display all columns whether I query for ‘productlist’ or ‘orders’)
otherwise it just displays a success message

if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit']))
{                 
        $sql = $_POST['sqlquery'];
        $trimmedSQL = trim($sql);
        
        if(!empty($trimmedSQL)) 
        {  
            $stmt = $db-> prepare($trimmedSQL);
            $stmt = execute();
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

            if ( strstr( strtoupper($trimmedSQL), 'SELECT' ) )
            {
                //print all the results into a table
            } 
            else
            {
                echo "<div class = 'success-msg'><div><i class='fa-solid fa-circle-check'></i><b> Success!</b> Processed SQL query.</div></div>";
            }
        }
        else
        {
                echo "No query!";
        }
}

what should I place in place of the comment, for this to happen? or is it completely wrong?
I’m sorry if this may sound like its already been answered before, but the answer I found didn’t seem to work for my case.

Laravel 5.8 Adding Multiple Middleware Directly To Route

I’m using Laravel 5.8 and I have a route like this:

Route::get("certs","CertController@index")->name('certificate.front')->middleware('auth');

Now I wanted to add another middleware to this route, so I tried this:

Route::get("certs", "CertController@index")->name('certificate.front')->middleware('prevent-back-history','auth');

Now I don’t get any error and it works But I wonder is this way better or not:

Route::get("certs", "CertController@index")->name('certificate.front')->middleware(['prevent-back-history','auth']);

So which is better and correct in this case?

Note that I don’t want to use Route groups and needed to specify the middleware name directly to the route.

How To Get Value from three tables in mysql

I have three tables namely employees, company_cars, and delivery_locations
Each of these tables have two elements in common

for employees and company_cars we have employee_id, where employee_id is the driver of the car in company_cars table
employees table   cars table

for company_cars and delivery_locations we have car_id where car_id is the car used for delivering employees for a certain location….

Now I want to display the name of The driver the employees table from a car selected for a particular location.

I have tried the following but I can only get the employees id

$fetch_locations=mysqli_query($con,"SELECT *,
(SELECT car_name from company_cars as d WHERE r.selected_car = f.car_id) as bus,
(SELECT car_driver from company_cars as f WHERE r.selected_car = f.car_id) as driver
from delivery_locations as r order by name_of_location ASC LIMIT $start_from, $per_page_record");

Problem: Display name of Driver

How to get activate particular conversation chat

I’m using wschat wordpress plugin. I’m passing link with the conversation id. If there is conversation id we need to get id and activate the particular user conversation.
I’m passing link as https://brookstone220.com/wp-admin/admin.php?page=wschat_chat&cid=3
and the js file will be shown below:
admin_chat.js:

import {WSChat, formatDate} from './chat';
import { AdminApiConnector } from './admin_api_connector';
import { AdminPusherConnector } from './admin_pusher_connector';
import { EVENTS } from './events';
import { EmojiButton } from '@joeattardi/emoji-button';
import UserMetaInfo from './components/user_meta_info.html'

jQuery(document).ready(function() {

    const wrapper = jQuery('.wschat-wrapper');

    if (wrapper.length === 0) {
        return;
    }
   
    const CONVERSATION_TEMPLATE = `
        <div class="friend-drawer friend-drawer--onhover" data-conversation-id="{{CONVERSATION_ID}}">
          <img class="profile-image" src="https://ui-avatars.com/api/?rounded=true&name=Guest" alt="">
          <div class="text">
            <h6>{{NAME}}</h6>
            <p class="last-message text-truncate">{{LAST_MESSAGE}}</p>
          </div>
          <span class="time small d-none">{{TIMESTAMP}}</span>
          <span class="unread-count badge rounded-pill align-self-center">{{UNREAD_COUNT}}</span>
        </div>
        <hr>`;

    const CHAT_BUBBLE_TEMPLATE = `
          <div class="row g-0 w-100 message-item" data-message-id="{{MESSAGE_ID}}">
            <div class="col-xs-10 col-md-9 col-lg-6 {{OFFSET}}">
              <div class="chat-bubble chat-bubble--{{POS}}">
                {{CONTENT}}
              </div>
              <span class="time">{{TIMESTAMP}}</span>
            </div>
          </div>`;

    const CONVERSATION_TEMPLATE_DEFAULTS = {
        '{{CONVERSATION_ID}}': '',
        '{{LAST_MESSAGE}}': 'left',
        '{{TIMESTAMP}}': '',
        '{{NAME}}': '',
    };

    const BUBBLE_TEMPLATE_DEFAULTS = {
        '{{OFFSET}}': '',
        '{{POS}}': 'left',
        '{{CONTENT}}': '',
        '{{TIMESTAMP}}': '',
        '{{MESSAGE_ID}}': '',
    };

    jQuery.ajaxSetup({
        data: {
            wschat_ajax_nonce: wschat_ajax_obj.nonce
        }
    });

    var chat = new WSChat(jQuery('.wschat-wrapper'), {
        connector: wschat_ajax_obj.settings.communication_protocol === 'pusher' ? AdminPusherConnector : AdminApiConnector,
        api: {
            endpoint: wschat_ajax_obj.ajax_url,
            interval: 3000,
            wschat_ajax_nonce: wschat_ajax_obj.nonce,
            pusher: {
                key: wschat_ajax_obj.settings.pusher.app_key,
                cluster: wschat_ajax_obj.settings.pusher.cluster,
            }
        },
        alert: {
            url: wschat_ajax_obj.settings.alert_tone_url
        },
        header: {
            status_text: wschat_ajax_obj.settings.widget_status === 'online' ? wschat_ajax_obj.settings.header_online_text : wschat_ajax_obj.settings.header_offline_text,
        }
    });

    if (wschat_ajax_obj.settings) {
        for(let key in wschat_ajax_obj.settings.colors) {
            key && chat.$el.get(0).style.setProperty(key,  '#' +wschat_ajax_obj.settings.colors[key]);
        }
    }

    setInterval(() => {
        chat.connector.start_conversation();
    }, 5000);

    const chat_panel = chat.$el.find('.chat-panel');
    const conversation_panel = chat.$el.find('.conversation-list');
    const chat_panel_header = chat.$el.find('.chat-panel-header');
    const chat_tray_box = chat.$el.find('.chat-box-tray');
    const message_input = jQuery('#wschat_message_input');
    const MESSAGE_INFO = {
        min: 0,
        max: 0,
    };
    let PAST_REQUEST_IS_PENDING = false;
    let SCROLL_PAUSED = false;
    let DISABLE_SCROLL_LOCK = false;
    const SCROLL_OFFSET = 100;


    const replaceConversation = (conversation) => {
        let item = conversation_panel.find('[data-conversation-id='+conversation.id+']');
        if (item.length === 0 ) {
            return false;
        }

        item.find('.time').text(conversation.updated_at);
        item.find('.last-message').text( conversation.recent_message ? conversation.recent_message.body.text : '');
        item.find('.unread-count').text(conversation.unread_count || '');

        if (conversation.is_user_online) {
            item.addClass('online');
        } else {
            item.removeClass('online');
        }

        return true;
    };

    const sortConversation = () => {
        const new_conversation_panel = conversation_panel.clone();
        const items = [];

        new_conversation_panel.find('[data-conversation-id]').each(function (i, item) {
            items.push(item);
        });

        items.sort((a, b) => {
            let timestamp1 = jQuery(a).find('.time').html();
            let timestamp2 = jQuery(b).find('.time').html();

            return strToDate(timestamp2) - strToDate(timestamp1);
        });

        new_conversation_panel.html('');

        items.forEach((item) => {
            new_conversation_panel.append(item);
        });

        conversation_panel.html(new_conversation_panel.html());
    };

    const strToDate = (timestamp) => {
        let [date1, time1] = timestamp.split(' ');
        date1 = date1.split('-');
        time1 = time1.split(':');

        return parseInt(date1.join('') + time1.join(''));
    };

    const showNoConversation = () => {
        const no_conversation_alert = jQuery('.no-conversation-alert');
        conversation_panel.append(no_conversation_alert.removeClass('d-none'));
    }

    chat.on(EVENTS.WSCHAT_ON_NO_CONVERSATIONS, () => {
        showNoConversation();
    });
    chat.on(EVENTS.WSCHAT_ON_FETCH_CONVERSATIONS, (conversations) => {

        conversations.forEach(conversation => {
            if (replaceConversation(conversation)) {
                return;
            }

            CONVERSATION_TEMPLATE_DEFAULTS['{{CONVERSATION_ID}}'] = conversation.id;
            CONVERSATION_TEMPLATE_DEFAULTS['{{NAME}}'] = conversation.user.meta.name;
            CONVERSATION_TEMPLATE_DEFAULTS['{{TIMESTAMP}}'] = formatDate(conversation.updated_at);
            CONVERSATION_TEMPLATE_DEFAULTS['{{LAST_MESSAGE}}'] = conversation.recent_message ? conversation.recent_message.body.text : '';
            CONVERSATION_TEMPLATE_DEFAULTS['{{UNREAD_COUNT}}'] = conversation.unread_count || '';

            let row_template = CONVERSATION_TEMPLATE;

            row_template = row_template.replace(new RegExp(Object.keys(CONVERSATION_TEMPLATE_DEFAULTS).join('|'), 'g'), match => CONVERSATION_TEMPLATE_DEFAULTS[match]);

            row_template = jQuery(row_template);

            if (conversation.is_user_online) {
                row_template = row_template.addClass('online');
            }

            if (conversation.user && conversation.user.meta.avatar) {
                row_template.find('img.profile-image').attr('src', conversation.user.meta.avatar)
            }
            conversation_panel.append(row_template);
        });

        sortConversation();

        setTimeout(() => {
            let activeItem = conversation_panel.find('.active[data-conversation-id]').length
            activeItem === 0 && conversation_panel.find('[data-conversation-id]').eq(0).click();
        }, 1000);
    });

    chat.on(EVENTS.WSCHAT_ON_SET_CONVERSATION, (data) => {
        data.user &&
            chat_panel_header.find('.username').text(data.user.meta.name);
        let info = chat.$el.find('.user-meta-info').html(UserMetaInfo);

        chat_panel_header.parent().removeClass('d-none')

        info.find('.name').html(data.user.meta.name);
        info.find('.browser').html(data.user.meta.browser);
        info.find('.os').html(data.user.meta.os);
        info.find('.device').html(data.user.meta.device);
        info.find('.url').html(data.user.meta.current_url);

        message_input.focus();
        MESSAGE_INFO.min = 0;
        MESSAGE_INFO.max = 0;
        DISABLE_SCROLL_LOCK = true;
        resizeChat();

        setTimeout(() => DISABLE_SCROLL_LOCK = false, 1000);
    });

    chat.on(EVENTS.WSCHAT_ON_FETCH_MESSAGES, (data) => {
        for (let i = 0; i < data.messages.length; i++) {
            let row = data.messages[i];

            if (row.is_agent === true) {
                BUBBLE_TEMPLATE_DEFAULTS['{{OFFSET}}'] = 'offset-lg-6 offset-md-3 offset-xs-2';
                BUBBLE_TEMPLATE_DEFAULTS['{{POS}}'] = 'right';
            } else {
                BUBBLE_TEMPLATE_DEFAULTS['{{OFFSET}}'] = '';
                BUBBLE_TEMPLATE_DEFAULTS['{{POS}}'] = 'left';
            }
            BUBBLE_TEMPLATE_DEFAULTS['{{MESSAGE_ID}}'] = row.id;
            BUBBLE_TEMPLATE_DEFAULTS['{{CONTENT}}'] = row.body.formatted_content;
            BUBBLE_TEMPLATE_DEFAULTS['{{TIMESTAMP}}'] = formatDate(row.created_at);

            let row_template = CHAT_BUBBLE_TEMPLATE;

            row_template = row_template.replace(new RegExp(Object.keys(BUBBLE_TEMPLATE_DEFAULTS).join('|'), 'g'), match => BUBBLE_TEMPLATE_DEFAULTS[match]);

            if (MESSAGE_INFO.min === 0) {
                chat_panel.append('<span data-message-id="0"></span>');
            }

            if (MESSAGE_INFO.min > row.id) {
                chat_panel.find('[data-message-id='+MESSAGE_INFO.min+']').before(row_template);
                MESSAGE_INFO.min = row.id;
            }

            if (MESSAGE_INFO.max === 0 || MESSAGE_INFO.max < row.id) {
                chat_panel.find('[data-message-id='+MESSAGE_INFO.max+']').after(row_template);
                MESSAGE_INFO.max = row.id;
                scrollIfNotPaused();
            }

            if (MESSAGE_INFO.min === 0) {
               scrollIfNotPaused();
            }

            MESSAGE_INFO.min = MESSAGE_INFO.min || row.id;
            MESSAGE_INFO.max = MESSAGE_INFO.max || row.id;
        }

        if (DISABLE_SCROLL_LOCK === true) {
            scrollIfNotPaused();
        }

    });

    chat.on(EVENTS.WSCHAT_ON_PONG, (data) => {
        let drawer = chat_panel_header.find('.friend-drawer');
        let row_template = conversation_panel.find('[data-conversation-id='+data.id+']');
        let row_unread_count = row_template.find('.unread-count');
        let header_unread_count = chat_panel_header.find('.unread-count');

        chat_panel_header.find('.status').text(data.status);
        header_unread_count.text(data.unread_count);
        row_unread_count.text(data.unread_count || '');

        if (data.unread_count) {
            header_unread_count.removeClass('d-none');
        } else {
            header_unread_count.addClass('d-none');
        }

        if (data.is_online) {
            drawer.addClass('online');
            row_template.addClass('online');
        } else {
            drawer.removeClass('online');
            row_template.removeClass('online');
        }
    });

    const scrollIfNotPaused = () => {
        if (SCROLL_PAUSED === false || DISABLE_SCROLL_LOCK === true) {
            chat_panel[0].scrollTop = chat_panel[0].scrollHeight;
        }
    }

    const send_btn = jQuery('#wschat_send_message').on('click', function() {
        let msg = message_input.val();

        if (msg.trim() === '' && chat.trigger(EVENTS.WSCHAT_CAN_SEND_EMPTY_MESSAGE, false, true) === false) {
            return false;
        }

        chat.sendMessage({
            // Type is text by default now, it needs to changed based on the selection content
            wschat_ajax_nonce: wschat_ajax_obj.nonce,
            type: 'text',
            'content[text]': message_input.val()

        });
        message_input.val('').focus();
    });

    message_input.keyup(function(e) {
        e.key === 'Enter' && send_btn.click();
    });

    message_input.on('focus', function() {
        let unread_count = chat_panel_header.find('.unread-count').text();

        if (parseInt(unread_count) > 0) {
            chat.trigger(EVENTS.WSCHAT_ON_READ_ALL_MESSAGE);
        }
    });

    chat_panel_header.on('click', '.user-meta-info-toggle', function () {
        chat.$el.find('.conversation-wrapper .user-meta-info').toggleClass('d-none');
    });

    conversation_panel.on('click', '[data-conversation-id]', function() {
        chat_panel.html('');
        let item = jQuery(this);
        let converssation_id = item.data('conversation-id');
        conversation_panel.find('[data-conversation-id]').removeClass('active');
        item.addClass('active')
        chat.connector.join_conversation(converssation_id);
    });

    chat_panel.on('scroll', function () {
        if (DISABLE_SCROLL_LOCK) {
            SCROLL_PAUSED = false;
            return;
        }
        if (this.scrollTop < SCROLL_OFFSET) {
            if (PAST_REQUEST_IS_PENDING === false) {
                PAST_REQUEST_IS_PENDING = true;
                chat.connector.get_messages({
                    after: 0,
                    before: MESSAGE_INFO.min
                });
                setTimeout(() => PAST_REQUEST_IS_PENDING = false, 500);
            }
        }

        if (this.offsetHeight + this.scrollTop >= this.scrollHeight - SCROLL_OFFSET) {
            SCROLL_PAUSED = false;
        } else {
            SCROLL_PAUSED = true;
        }
    });

    const resizeChat = () => {
        const window_height = jQuery(window).height() - chat.$el.offset().top;

        const height = window_height - (
            chat_panel_header.height()*2 + chat_tray_box.height()
        );

        conversation_panel.css({
            'min-height': height + 'px'
        });

        chat_panel.css({
            'min-height': height + 'px'
        });
    };

    jQuery(window).resize(() => resizeChat());
    resizeChat();

    const emojiPicker = document.getElementById('wschat_emoji_picker');
    const emoji = new EmojiButton({
        style: 'twemoji',
        rootElement: emojiPicker.parentElement,
        position: 'top'
    });


    emojiPicker.addEventListener('click', function() {
        emoji.togglePicker();
    });

    emoji.on('emoji', function(selection) {
        console.log(selection)
        message_input.val(message_input.val() + selection.emoji).focus();
        setTimeout(() => message_input.focus(), 500)
    });


    // Attachment toggler
    chat.$el.find('#attachment_picker').click(function (e) {
        e.preventDefault();
        chat.$el.find('.attachment-list').toggleClass('show d-none');
    });
    chat.$el.find('.attachment-list').on('click','button', function () {

        chat.$el.find('#attachment_picker').click();
    });

});

Can someone help me on this? How to activate the conversation by getting id from url?
Also, i don’t know what type of js they are used can any one let me know?

Update shipping method woocommerce

I have a site with woocommerce and several other plugins (Role Based Methods in particular)

Each user role has two shipping methods: a paid one (the price changes according to the role) and a free one (with a min_amount which also changes according to the role)

During a specific action by the administrator on an order (or an order batch), an update of the prices of the items is done and I wish to update the shipping method (only in the case where the user had a paid method and the new rates exceed the min_amount of his free method)

I manage to retrieve the order total and the shipping methods available for the role of the user

But I can’t update the shipping method.

In fact here is the var_dump of $order->get_items(‘shipping’)when it’s free shipping:
var_dump of $order->get_items('shipping')when it's free shipping

And the var_dump when isn’t free shipping
var_dump when isn't free shipping

as you can see, the shipping method name and price is in the “data” table

So I tried this code:

foreach ($actualShipping as $item_id => $item){
    $data = $item->get_data();
    $data["instance_id"] = $freeMethodForUser[0]["instance_id"];
    $data["name"] = $freeMethodForUser[0]["method_title"];
    $data["method_title"] = $freeMethodForUser[0]["method_title"];
    $data["method_id"] = $freeMethodForUser[0]["id"];
    $data["total"] = "0.00";
    $item->set_props(array(
            'method_title' => $item->get_method_title(),
        'method_id' => $item->get_method_id(),
        'total' => wc_format_decimal($item->get_total()),
        'taxes' => $item->get_total_tax(),
        'meta_data' => $item->get_meta_data(),
        'data' => $data)
    );
    $item->save();
}
$order->calculate_totals();
$order->save();

$freeMethodForUser[0] is an object of type WC_Shipping_Free_Shipping
Before the $item->set_props if I put a var_dump of $data, it’s okay my new shipping method is here

But I can’t save it

Could you please help me to update my shipping method ?

How to copy a file inside a newly created folder and rename the file?

Good day experts!

I want to copy a file inside a newly created folder and rename the file but it seems there’s something wrong with codes and I cant figure it out. Here’s my code:

<?php
$name = $_POST["newFileName"];
$folder = mkdir($name);
session_start();
$name = $_POST["newFileName2"];
$file = 'data.php';
$newfile = $folder/$_POST["newFileName2"].'.php';

file_exists($newfile) && die(" <center><br><br><br><br>The Exam name already exists.! Change it! <br><br> <a href='quiz.php'><button>GO BACK</button></a>");

if (!copy($file, $newfile)) {
    echo "Failed to create Quiz";
}else {
   echo "Created Successfully";
}
?>

Is PHP ldap_escape compatible with Microsoft Active Directory?

Here

https://social.technet.microsoft.com/wiki/contents/articles/5312.active-directory-characters-to-escape.aspx

you can see how AD requires to escape individual components of a distinguished name (a backslash in front of the character to be escaped).

The ldap_bind function, however, adopts a different escaping technique (I think according to RFC4514) so for example:

SalesEngineering would be:

Sales\Engineering according to 1

and:

Sales5cEngineering if you use ldap_bind

I know that 5c is just the xx hex sequence for , but can this create problems?

I am having troubles using ldap_bind with domainuser DNs in Active Directory that’s why I am wondering if there are compatibility issues.

Thanks

Block users from REST API endpoint while still grabbing data from it

I have created 2 REST API endpoint to store the CPT data and their custom fields:

Archive Data: xyz.com/wp-json/wl/v2/businesses
Single Business data: xyz.com/wp-json/wl/v2/businesses/<ID>

Both these endpoints have been registered with the permission callbacks;

register_rest_route( 'wl/v2', '/businesses', array(
    'methods'   => WP_REST_Server::READABLE,
    'callback'  =>  'wl_businesses_posts',
    'permission_callback'   => '__return_true'
));

It is a business directory website where a common dashboard ( xyz.com/dashboard ) for each ‘business’ client exists and this dashboard page pulls in data for that ‘business’ from the Single Business data REST API endpoint above and fills the input fields on the page.

There is also another page accessible to the non-logged in visitors( xyz.com/business1 ) that is common for all businesses and is a read-only page where visitors can check that business’ details. This page too pulls data from the Single Business data REST API endpoint mentioned above.

What I am trying to accomplish is that no one except the Admin should be able to peep into the Archive Data or the Single Business data endpoints, to avoid stealing info of all the businesses registered with the site. But at the same time, I would want these endpoints to be accessible by the wp_remote_retrieve_body( wp_remote_get( $url ) );code to populate the dashboard and single business info pages.

I tried this code but it obviously also blocks the requests made by the page code to pull and populate data in the pages.

add_filter( 'rest_authentication_errors', function( $result ) {
    if ( ! empty( $result ) ) {
      return $result;
    }
    if ( ! is_user_logged_in() ) {
      return new WP_Error( 'rest_not_logged_in', 'You are not currently logged in.', array( 'status' => 401 ) );
    }
    return $result;
  });

I am not necessarily looking for a code, just the direction about how to solve this problem.

file_exists(): open_basedir restriction in effect is checking for a file that doesn’t exist

I have a simple Laravel project, it runs just fine on my local machine, but after uploading to the server, when accessing a certain page, the following error is displayed:

file_exists(): open_basedir restriction in effect.
File(C:inetpubvhostsgoldenmedpharma.comhttpdocslaravelgoldenmedpharma.net.v4resourceslang/ar/Forgot
Your Password?.php) is not within the allowed path(s):
(C:/Inetpub/vhosts/goldenmedpharma.com;C:WindowsTemp;C:Inetpubvhostsgoldenmedpharma.comhttpdocslaravelgoldenmedpharma.net.v4public;C:WindowsTemp)
(View:
C:inetpubvhostsgoldenmedpharma.comhttpdocslaravelgoldenmedpharma.net.v4resourcesviewsauthlogin.blade.php)

I don’t have a file named (Forgot Your Password?.php)! What exactly is this?
I’m using Plesk Obsidian to manage PHP and files on the server.

if condition in Laravelll

I want to check whether the user has cv or not. I used the following expression but doesn’t work any one can help

 public function create()
      
    {   
         if (auth()->user()->cv) {
         
        return $this->edit()-with('You already have a cv!', 'info');
   }
   return view('cv.create');
   }

WordPress search only showing a few posts

I am working on a Website and am linking category links to the search page.
Now the search behaves seemingly random as seen here: https://hasel.dev/?s=dizh

The search for the post returns the post, so far so good. If I click the ‘Developer Productivity’ Tag (= search for it), however, it returns a number of posts, not including the ‘DIZH’ post. If I click the ‘papers’ tag, I don’t get any results at all, although having added the category to over 20 posts.

enter image description here

What is the issue here?

Authentication with symfony 6.1, Token sent with every request, but it returns credentials at each response, problem with session or kernel.response

I’ve set an OIDC authentication with a custom authenticator as follow:

class SsoAuthenticator  implements AuthenticatorInterface, AuthenticationEntryPointInterface
{
    private UserProviderInterface $user_provider;
    private ?LoggerInterface $logger;

    public function __construct(LdapUserRepository $ldap_user_repository, UserProviderInterface $user_provider, LoggerInterface $logger = null)
    {
        $this->user_provider = $user_provider;
        $this->logger = $logger;
        $this->ldap_user_repository = $ldap_user_repository;
    }

    public function start(Request $request, AuthenticationException $authException = null): Response
    {
        $response = new Response();
        $response->headers->set('WWW-Authenticate', sprintf('Basic realm="%s"', 'emmaus.example.com'));
        $response->setStatusCode(401);

        return $response;
    }

    public function supports(Request $request): ?bool
    {
        return $request->headers->has('Authorization') || $request->get('token');
    }

    public function authenticate(Request $request): Passport
    {
       $oidc = new Oidc($this->ldap_user_repository);
       $token = $request->get('token');
       $decoded_token = $oidc->decodeToken($token);
       $user_name = $oidc = $oidc->getUserName($decoded_token);
        if(!(is_a($this->user_provider, UserProviderInterface::class)))
        {
            throw new AuthenticationException('error forbidden buddy');
        }
        $user_badge = new UserBadge($user_name);
        $credentials = new BadgeCredentials();
        return new Passport($user_badge, $credentials);
    }

    public function createToken(Passport $passport, string $firewallName): TokenInterface
    {
        return new UsernamePasswordToken($passport->getUser(), $firewallName, $passport->getUser()->getRoles());
    }
    public function createAuthenticatedToken(PassportInterface $passport, string $firewallName): TokenInterface
    {
        return new OidcToken(['ROLE_USER'], null);
    }
    public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
    {
        $oidc = new Oidc($this->ldap_user_repository);
        $token = $request->get('token') ? $request->get('token') : $request->get('Authorization');
        $decoded_token = $oidc->decodeToken($token);
        $user_identifier = $oidc->getUserName($decoded_token);
        $user = $this->ldap_user_repository->findOneBy(['username' => $user_identifier]);
        $last_name = $user->getLastName();
        $first_name = $user->getFirstName();
        $roles = $user->getRoles();
        $email = $user->getEmail();
        $group_results = array();
        $groups = $user->getGroupBase();
        
        foreach($groups as $group)
        {
            array_push($group_results, $group->getName());
        }

        $token = $request->get('token') ? $request->get('token') : $request->headers->has('Authorization');
        $_SESSION['token_lemon_ldap'] = $token;
        $data = array(
            'roles' => $roles,
            'userName' => $user_identifier,
            'firstName' => $first_name,
            'lastName' => $last_name,
            'email' => $email,
            'token' => $token,
            'groups' => $group_results
        );
        return new Response(
            json_encode($data)
        );


    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
    {
        $oidc = new Oidc($this->ldap_user_repository);
        $decoded_token = $oidc->decodeToken($request->get('token'));
        try
        {
            return $this->start($request, $exception);
        }catch(UnexpectedValueException $exception)
        {
            throw new $exception('wrong number of segment');
        }
    }
}
?>

I’ve the authorization to access resources from API after successful authentication, but when I’m fetching response from controller, it return onAutenticationSucess() response’s data at each request, and can’t access data from controllers, do you have an idea what i’m missing? I’m looking at session or kernel.response, but can’t make my head around a proper solution.
Thanks

How to get html data-attribute string from a php variable

I am constructing an html form in php with javascript and css, the following line of code works fine and displays a textarea with the required prefix:

$form .= '<textarea class="text" data-prefix="Message from: " ></textarea>';

However I want to include a php variable i.e

$form .= '<textarea class="text" data-prefix="Message from: $foo" ></textarea>';

This show the textarea with the prefix ‘Message from $foo’.
How do I show it with the value of $foo combined into the data-prefix i.e ‘Message from Foo’?

Any advice would be appreciated, thanks.