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.

How to exclude certain styling in page2 in pagination

I have followed Jeffery Way in Laravel 8 from scratch amazing series but I’m having a trouble in pagination. In the index page we’re making our latest post to have a specific styling and then first 2 posts comes after with a different styling and then rest of posts in different styling. The problem is that these styles are carrying over with us to page2 and 3 and …etc

I want to make this to only posts in page1 or homepage and when I go to page 2 I should have a default styling for all posts.

This is the index

<x-bloglayout>

    @include('posts.__header')

    @if ($posts->count())
        <x-featuredCard :post="$posts[0]" />

        @if ($posts->count() > 1)

            <div class="lg:grid lg:grid-cols-2">

                <x-postCard :post="$posts[1]" />
                <x-postCard :post="$posts[2]" />

            </div>

            <div class="lg:grid lg:grid-cols-3">
                @foreach ($posts->skip(3) as $post)
                    <x-postCard :post="$post" />
                @endforeach
            </div>

        @endif

        {{ $posts->links() }}

    @else
        <p class="text-center">No posts matches your search, please check back later</p>
    @endif



</x-bloglayout>

I tried to use if directive to say if route is home or ?/page1 do this if not do that but it doesn’t seem to work.

This is my pagination:

    public function index()
    {
        return view('posts.index', [
            'posts' => Post::latest()->filter(request(['search', 'category', 'author']))->paginate(6)->withQueryString(),
        ]);
    }

Thanks

What would be the best approach to fetch calculated cells from a JS generated Excel file?

I am building a React web app that asks the user to fill out some inputs that are directly sent into an complex template excel file using ExcelJS. Everything’s working like a charm except that I must open the generated file so MS Excel or LibreOffice recalculates all the formulas, that means I can’t just call a cell getter from JS to fetch a calculated formula.

Unfortunately the file is far too complex to be re written in a simple formula directly in JS, it’s using matrices, graphs, references to other sheets, etc. It’s an old system that has not been reworked since back then and that I’m not permitted to change.

What would be the best approach to treat this case ? I would just like to fetch a single cell from that file, I know PHPSpreadsheet does that because I’ve already done it, would it be OK to create a PHP API that get the generated excel into parameters to fetch the desired cell and store it in a database so that I can get access to it via my react app ? It seems like an overcomplicated, or overcharged solution for what I want to do. I’m not against using something else that ExcelJS if you can provide me another library that can handle with complex excel formulas

Thanks in advance

How to order a Select query in MySQL based on the most occurrence of another table

I have a product table and a memory table. The product table contains product ID and product name:

product_id product
1 RAM
2 HDD
3 SSD

The memory table contains different memory as below:

memory_id memory
1 128 GB
2 256 GB
3 512 GB
4 1 TB
5 8 GB
6 16 GB
7 32 GB

I have created two drop-down select options for products and for memory and save them in a cart table as below:

order_id product_id memory_id
1 1 1
2 1 2
3 1 1
4 2 3
5 2 4
6 2 3

I am wondering is there any way to do DESC order the select options for memory based on the occurrence of that specific product_id in cart table?
My target is to order the select options of the memory with the most used cases.

How to Get Data from YT-DLP to Browser Using PHP

I’m trying to Get YT-DLP data using PHP
Using SSH yt-dlp BaW_jenozKc I’m able to generate download codes, however same thing for PHP is not working on browser.

Have tried this code

<?php
$proc = popen('yt-dlp -o - BaW_jenozKc', 'r');
header("Content-Type: video/mp4");
while (!feof($proc))
{
    echo fread($proc, 4096);
}
pclose($proc);
?>

The above code expect to generate streaming link but its giving me error with no video with supported format and mime type found

On the other side when I use this PHP code

<?php
echo shell_exec("wget -O speedtest.py https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py && chmod +x speedtest.py && ./speedtest.py");
?>

It works great, can anybody tell me what’s wrong with the code or is there any permission issue for displaying data on browser?

unable to get session username to insert to database [closed]

Unable to insert session id to database. I Want to get the session username and insert it to database and display the current session username content.

<?php
require("session.php");
require ("include.php");

if (isset($_POST['save'])) {

    if (
        !empty($_POST['name']) && !empty($_POST['subject']) && !empty($_POST['sender']) &&
        !empty($_POST['to'])) 
    {
        $session_id = $_SESSION["user"];  
        $name = $_POST['name'];
        $subject = $_POST['subject'];
        $sender = $_POST['sender'];
        $to = $_POST['to'];
        $time = date("Y-m-d H:i:sa");

        foreach ($name as $key => $names) {
            $s_name = $names;
            $s_subject =  $subject[$key];
            $s_sender = $sender[$key];
            $s_to = $to[$key];
            $save = mysqli_query($link,"INSERT INTO `incomings`( `name`, `subject`,`sender`, `to_`,
`session_id`,  `time`) VALUES ('$s_name','$s_subject','$s_sender',  
'$s_to','$session_id', '$time' )");
            $save_q = mysqli_query($link,$save);
        } 

        if (!$save) {
            echo " Mails Not Submitted!";
            header("Location:insert_incoming.php");
            exit(0);} 
    }
}
?>

Change the date by one day on date picker

Hello I have created a booking form with html and can’t find how to make it so that the check out datepicker value always be the next day that is selected on the check in datepicker.

I have already tried to input the date of the check in datepicker to a var and print it to the value of the date picker but didn’t work.

I will be placed on a wordpress shortcode widget.

This is the one of the codes I have tried.

    <html>
    <body>
<form method="get">
    <script type="date/javascript">
            var indate = document.getElementById(Check_In_Date);
            var outdate = document.setElementById(Check_Out_Date);
            
            outdate.value="indate";
            </script>
    
        <font>&nbsp&nbsp&nbsp&nbsp&nbsp Check In Date &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp Check Out Date&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <br></font>
        &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
        <input type="date" name="checkin" id="Check_In_Date" value="2022-05-16" >                             
        
        <input type="date" name="checkout" id="Check_Out_Date" value="outdate">
        
            <select name="adults">
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
            </select>
            
            
        <select name="children">
            <option value="0">0</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
        </select>
        
    <input type="submit" value="Search">
</form>
    <body>
    </html>

Best way to make multiple update with PDO

I need to update my table with multiple request.
With a form, i get some values that i will take for update my table.

  $products =  [
    'prodotto1' => [
      'referenza' => $_POST['referenza1'],
      'prezzo' => $_POST['prezzo1'],
    ],
    'prodotto2' => [
      'referenza' => $_POST['referenza2'],
      'prezzo' => $_POST['prezzo2'],
    ],
    'prodotto3' => [
      'referenza' => $_POST['referenza3'],
      'prezzo' => $_POST['prezzo3'],
    ]
  ];

I thought to do this with a foreach :

function updateProducts(array $params){
$pdo = $GLOBALS["db"];
$sql = "UPDATE product SET REFERENCE=:reference, PRICE=:price WHERE REFERENCE=:reference";
$stmt= $pdo->prepare($sql);

foreach ($params as $prodotto ){
    if ($prodotto['referenza'] && $prodotto['prezzo'] ){
        $stmt->bindParam(':reference', $prodotto['referenza'], PDO::PARAM_STR);
        $stmt->bindParam(':price', $prodotto['prezzo']);
        $stmt->execute();

    }
}

}

But i’m not sure that is the best way to do this.

Can u suggest me some goods practice ?

CakePHP 3.3.9 Rest API with File not working

File uploads work when I am using postman but when I am using CAKEPHP project (Http Client) for only data it’s work but with file not working

Cakephp Client : Only Data without File ( it’s working )

Cakephp Client : Data with File ( does not work )

Postman : Data with File ( it’s working )

in /config/routes.php

$routes->extensions(['json','xml']);

Code :

 use CakeHttpClient;
 use CakeHttpClientFormData;
    
   public function add()
    {
        $client = $this->Clients->newEntity();
        if ($this->request->is('post')) {
            $client = $this->Clients->patchEntity($client, $this->request->data);
            if ($this->Clients->save($client)) {

                    $formData = new FormData();
                    $formData->addMany($this->request->data);
     
                      $file = $formData->addFile('header_file',fopen($this->request->data['header_file']['tmp_name'], 'r'));
                      $file->contentId($this->request->data['header_file']['name']);
                      $file->disposition('attachment');
                               
                    $options = [
                         'headers' => ['Content-Type' => $formData->contentType()]                   
                     ];
                
                    $http = new Client(); 
                    $url = 'http://example.com/clients/add.json';
                    $result = $http->post($url,(string)$formData,$options);
                    var_dump($result);
                    exit;
               }
}

Thanks, I use cakephp 3.3.9 sorry for bad English.

Undefined variable in php while insert to mysql [duplicate]

I am getting this error that the variable is undefined when I actually set it to the value and no matter what kind of value I set even simple $user = 1 ; doesn’t work and I got error it is undefined

<?php 

session_start();

include ('get-user-data.php');

$user = array();

if(isset($_SESSION['userID'])){
    require ('connection.php');
    $userId = $_SESSION['userID'];


    function wantToRead() {
        $query = " INSERT INTO bookshelf (id, tittle, category, thumbnail) VALUES ('$userId', ' Book', 'read')";
    }
}
?>

So I hava a small online shop project :( Uncaught Error: Call to undefined function mysql_connect() can anyone help me connect to database [duplicate]

so I do everything same with the tutorial but it’s end up getting
Uncaught Error: Call to undefined function mysql_connect()

**But I someguy told I need to change to sqli instead **
I’m not good with coding but I have to do this small project by myself

and some other php file too.
I’ll have download link for you too work with please help 🙁

http://www.mediafire.com/file/2bmmao9ibbjpwzv/plaincart.rar/file
database file is in library

WordPress shortecode

I am using myCred on my site. Specially myCred transfer. There is an existing shortcode for this particular plugin.
[mycred_transfer pay_to=1]
where pay_to is the recipient wordpress user id. I can only manually add a user id. But so I need to manually create a shortcode for every created user and it is no go :D.
so therefore I created this function to gather user id of the current post.

// Shortcode to output custom PHP
function author_id( $atts ) {
   echo $user_id = get_the_author_meta( 'ID' );
}
add_shortcode( 'my_author_id', 'author_id');

and it works for the user ID. but do not know how to replace it “1” in [mycred_transfer pay_to=1]
because if I replace “1” with a shortcode it does not work.
Thanks for ideas