Symfony access_token.token_handler triggers before access_control. What is the best way to skip it for public routes?

I use token_handler to validate token. But I don’t need it for PUBLIC_ACCESS routes. The thing is it triggers before access_control.

Can I check somehow for a PUBLIC_ACCESS first? Or is there a better way to make public routes avoid this token_handler? What is the best way? (Symfony 7)

# AccessTokenHandler.php

readonly class AccessTokenHandler implements AccessTokenHandlerInterface
{
    public function __construct(private ApiTokenRepository $repository)
    {
    }

    public function getUserBadgeFrom(string $accessToken): UserBadge
    {
        $accessToken = $this->repository->findOneByValue($accessToken);
        if (is_null($accessToken) || !$accessToken->isValid()) {
            throw new BadCredentialsException('Invalid credentials.');
        }

        return new UserBadge($accessToken->getUser()->getUserIdentifier());
    }
}
# security.yaml

firewalls:
    main:
        json_login:
            check_path: sign_in
            username_path: email
            password_path: password
        access_token:
            token_handler: AppSecurityAccessTokenHandler
access_control:
    - { path: ^/auth, roles: PUBLIC_ACCESS }
    - { path: ^/*, roles: ROLE_USER }

Attribute values in variable products on shop/categories WooCommerce pages

In an online store on WooCommerce, I use code that displays certain product attributes on archive/category pages.

add_action( 'woocommerce_before_shop_loop_item_title', 'new_template_loop_product_meta', 20 );
function new_template_loop_product_meta() {
    global $product;

    $attrs_by_cats = [
        20 => [ 'pa_size' ],
    ];

    $attr_list = [
        'Size' => 'pa_size',
    ];

    if ( ! is_object( $product ) ) {
        $product = wc_get_product( get_the_id() );
    }

    $cats = $product->get_category_ids();

    if ( ! is_array( $cats ) ) {
        return;
    }

    $attrs = [];

    foreach ( $cats as $cat ) {
        if ( isset( $attrs_by_cats[ $cat ] ) ) {
            $attrs[] = $attrs_by_cats[ $cat ];
        }
    }

    $allowed_attrs = array_unique( array_merge( [], ...$attrs ) );

    echo '<div class="custom-attributes">';

    foreach ( $attr_list as $attr_title => $attr_name ) {
        if ( in_array( $attr_name, $allowed_attrs, true ) ) {
            show_attribute( $product, $attr_title, $attr_name );
        }
    }

    echo '</div>';
}
/* Show attr */
function show_attribute( $product, $attr_title, $attr_name ) {
if ( 'sku' === $attr_name ) {
    $attr = (string) esc_html( $product->get_sku() );
} else {
    $attr = $product->get_attribute( $attr_name );

    if ( ! $attr ) {
        return;
    }
    $attr = explode( ', ', $attr ); // convert the coma separated string to an array

    $attr_arr = []; // Initialize

    // Loop through the term names
    foreach ( $attr as $term_name ) {
        // Embed each term in a span tag
        $attr_arr[] = sprintf('<span class="attr-term">%s</span>', $term_name);
    }
    // Convert back the array of formatted html term names to a string
    $attr = implode(' ', $attr_arr);
}

if ( '' === $attr ) {
    return;
}

printf( '<div class="custom-attributes-text">%s: %s</div>', $attr_title, $attr);
}

With simple products this code works without problems. The problem is only with the attribute in variable products.

When creating a product I added sizes S, M, L and automatically created variations. Then for each size S, M and L I manually set the stock availability to 30.

Then, the size L is all sold out and I have 0 in stock. Except that on the product list page all sizes are shown, while S and M should be shown.

How can I fix this code so that it works with variable products?

Thanks in advance for your help!

Download PDF in Laravel 9 using barryvdh/laravel-dompdf give us a pdf file corrupted

trying to download file using barryvdh/laravel-dompdf from html render view

        // Generate the PDF from the HTML content
    $pdf = PDF::loadHTML($contract_document)->setPaper('a4', 'landscape')
                        ->setOption('zoom', 1.2)
                        ->setOption('footer-center', '')
                        ->setOption('footer-font-size', 5);

   
    return $pdf->download($ad_id . '.pdf');

it download file corrupted if if I open in pdf fire fox it give me the below error :

Invalid or corrupted PDF file.

PDF.js v4.7.18 (build: 9735a840a)
Message: Invalid PDF structure. viewer.mjs:12184:13
Uncaught (in promise) 
Object { message: "Invalid PDF structure.", name: "InvalidPDFException", stack: "BaseExceptionClosure@resource://pdf.js/build/pdf.mjs:453:29n@resource://pdf.js/build/pdf.mjs:456:2n" }

can you please advice ?

Set default value in laravel views filter

Default Filter Value Not Working in Laravel Views

I’m trying to add a default value to a filter in Laravel Views, but it’s not working as expected. Here’s my current implementation:

GruposActiveFilter class:

use LaravelViewsFiltersFilter;
use IlluminateDatabaseEloquentBuilder;

class GruposActiveFilter extends Filter
{
    public function apply(Builder $query, $value, $request): Builder
    {
        return $query->where('Activo', $value);
    }

    public function options(): array
    {
        return [
            'Activo' => 1,
            'Inactivo' => 0,
        ];
    }
}

In my ListView:

protected function filters()
{
    return [
        new GruposActiveFilter,
    ];
}

What I’ve tried:

I’ve attempted to add a default() method to the filter class, but it doesn’t seem to be recognized:

public function default()
{
    return 1;
}

Expected behavior:

I expect the filter to default to ‘Activo’ (value 1) when the page is first loaded.

Actual behavior:

The filter is not applying any default value, and I have to manually select a filter option each time.

How can I set a default value for my GruposActiveFilter in Laravel Views so that it’s applied automatically when the page loads?

Any help or guidance would be greatly appreciated!

Using Php, How to change permission of Folder(and it’s files) to 755 to prevent deletion fo file from outside virus? And how to return to 777?

How to change permission of Folder(and it’s files) to 755 to prevent deletion of file from outside virus? And how to return to 777?
Want to use 777 only when necessary inside of php code.

Assuming file 333.jpg location in “image” Folder,

bellow should “not” delete file, 333.jpg?

<?php 
chmod("./image/" , 0755);
unlink("./image/333.jpg");
?>

For return to normal, bellow should delete file?

<?php
chmod("./image/" , 0777);
unlink("./image/333.jpg");
?>

BUT ABOVE CODES IS NOT WORKING..
Am running php under linux.
Thnaks in advance.

When i change permission through terminal by
“sudo chmod 755 /var/www/html/image”
it works. But not through php,,,,

My uploaded images are rotated with laravel / intervention

I am using intervention to manipulate some images with Laravel 11.

My code works fine in local environment.

When I deploy the application in production (heroku), the same code produces a surprising phenomenon: the image undergoes a rotation, sometimes by 90°, sometimes by 180°.

And the same image is not rotared locally, but is in production !

I tried to play with the “autoOrientation” parameter, without success. The image is still rotated.

My code is very simple :

$manager = new ImageManager(new Driver);
$image = $manager->read($media);
$image->save('transformed_image');

I read here and there that there is a story about “exif” data. Is this an indication ?

What could be my mistake ?

403 when downloading a file via PHP but not from browser

I have a 403 error when downloading a JSON file via PHP from a URL. I can open the file from the browser without problems (no errors in the dev tools).

This is the script (minus the actual URL), which I have verified as working with other sites:

$ch = curl_init($url);
$dir = '../sources/';
$file_name = basename($url);
$save_file_loc = $dir . $file_name;
$fp = fopen($save_file_loc, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_CAINFO, 'C:/Program Files/php/cacert.pem');
curl_exec($ch);
echo curl_errno($ch)."n";
print_r(curl_getinfo($ch));
curl_close($ch);
fclose($fp);

The certificate comes from https://curl.se/docs/caextract.html. This is the info I get:

    [url] => the/url/path/to/json/file
    [content_type] => text/html
    [http_code] => 403
    [header_size] => 183
    [request_size] => 83
    [filetime] => -1
    [ssl_verify_result] => 0
    [redirect_count] => 0
    [total_time] => 0.516273
    [namelookup_time] => 0.065622
    [connect_time] => 0.091481
    [pretransfer_time] => 0.483309
    [size_upload] => 0
    [size_download] => 418
    [speed_download] => 809
    [speed_upload] => 0
    [download_content_length] => 418
    [upload_content_length] => 0
    [starttransfer_time] => 0.516216
    [redirect_time] => 0
    [redirect_url] =>
    [primary_ip] => (the.url.primary.ip.address)
    [certinfo] => Array
        (
        )

    [primary_port] => 443
    [local_ip] => (my.local.ip)
    [local_port] => 65046
    [http_version] => 3
    [protocol] => 2
    [ssl_verifyresult] => 0
    [scheme] => HTTPS
    [appconnect_time_us] => 483121
    [connect_time_us] => 91481
    [namelookup_time_us] => 65622
    [pretransfer_time_us] => 483309
    [redirect_time_us] => 0
    [starttransfer_time_us] => 516216
    [total_time_us] => 516273
    [effective_method] => GET

Of course I tried setting a user agent as well, but no chance.

What am I missing?

Session change in php not caught in while loop

Trying to implement Server Side Events – On the server side (php), the below while loop doesn’t catch when the session is changed from another php script. It does catch it when the whole web page is reloaded. The second code without the loop catches the session change. Any clues to why and how to handle?

Not working code

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
    
function sendEvent($event, $data) {
    echo "event: $eventn";
    echo "data: $datann";
    ob_flush();
    flush();
}

// Check signing status and send events
while (true) {
    session_start();  // Reopen the session to get the latest data
    $status = $_SESSION['signing_status'];
    session_write_close(); // Immediately close the session to avoid locks
    
    sendEvent("event",$status);
    // Wait for a few seconds before checking again
    sleep(4);
}

?>

Working code

<?php
session_start();
$status = $_SESSION['signing_status'];
session_write_close();

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');

$eventId = 0;  // Initialize event ID

sendEvent("event", $_SESSION['signing_status']);

function sendEvent($event, $data) {
    echo "event: $eventn";
    echo "data: $datann";
    ob_flush();
    flush();
}
?>

Hello, I have the following code, it is displaying data from the database but not adding data into the database [closed]

I have tried the code but not working. The select statement is working fine but the UPDATE And INSERT statements are not making any changes in the database.
Even the DELETE query made is not working. There is also a javascript file that contains code which then connects to this file below.

<?php

    include("db_connect.php");
    // handle a GET
    // add the header line to specify that the content type is JSON
    header("Content-type: application/json");

    // determine the request type
    $verb = $_SERVER["REQUEST_METHOD"];

    if ($verb == "GET") {
        $arr = array();

        $rs = mysqli_query($link,"SELECT s.id, s.name, s.local_church_id as l_id, l.name as local_church_name, l.id as local_church_id from small_christian_community s, local_church l WHERE s.local_church_id = l.id ORDER BY l.name ASC");
        while($obj = mysqli_fetch_object($rs)) {
            $arr[] = $obj;
        }

        // add the header line to specify that the content type is JSON
        header("Content-type: application/json");

        echo "{"data":" .json_encode($arr). "}";
    }

    if ($verb == "PUT") {

            $request_vars = Array();
            parse_str(file_get_contents('php://input'), $request_vars );
            $name = mysql_real_escape_string($request_vars["name"]);
            $local_church_id = mysql_real_escape_string($request_vars["local_church_id"]);



            // INSERT COMMAND
            $insert_query = "INSERT INTO small_christian_community(name, local_church_id) VALUES ('".$name."','".$local_church_id."')";

          $rs = mysqli_query($link,$insert_query);

          if ($rs) {
            echo json_encode($rs);
          }
          else {
            header("HTTP/1.1 500 Internal Server Error");
            echo false;
          }
    }
    if ($verb == "POST") {
            $name = mysql_real_escape_string($_POST["name"]);
            $local_church_id = mysql_real_escape_string($_POST["local_church_id"]);
            $id = mysql_real_escape_string($_POST["id"]);

            $rs = mysqli_query($link,"UPDATE small_christian_community SET name = '" .$name ."',local_church_id = '" .$local_church_id ."' WHERE id = " .$id);

            if ($rs) {
                echo json_encode($rs);
            }
            else {
                header("HTTP/1.1 500 Internal Server Error");
                echo "Update failed for church: " .$id;
            }
    }

    if ($verb == "DELETE") {
        parse_str(file_get_contents('php://input'), $_DELETE);
        $id = mysql_real_escape_string($_DELETE["id"]);

        $rs = mysqli_query($link,"DELETE FROM small_christian_community WHERE id = " .$id);

        if ($rs) {
            echo true;
        }
        else {
            header("HTTP/1.1 500 Internal Server Error");
            echo false;
        }
    }

?>

Someone please help

Send data from next js react hook form to php backend [duplicate]

I am trying to send data from a next js frontend to a php backend to populate my mysql database. I am trying to get it to connect but I am stuck as I am noob at php.

This is my next js form

const onSubmit = async (data: ShopFormValues) => {
        setLoading(true)
        try {        
            const response = await fetch("https://***********.com/register.php", {
                method: "POST",
                body: JSON.stringify({ firstname: "example" }),
                // ...
            });
            
            console.log(response)
        } catch (error: any) {
            console.log('Network error!')
        }
        finally {
            setLoading(false)
        }

    };

and this is my register.php file

<?php

    header("Access-Control-Allow-0rigin: *");
    header("Access-Control-Allow-Headers: *");

    $servername = "localhost";
    $database = "*********";
    $username = "************";
    $password = "************";
    $conn = new mysqli($servername, $username, $password, $database);
    
    if(isset($_POST['firstname'])){
        echo 'hello';
    }
    else {
        echo 'wa';
    }
?>

How can i confirm that the register.php file is receiving the data and send back a response?

wp event manager- stripe split pay issue connecting

I’m having issues with stripe split pay.
the website is a hub for organisers to come and post their events and sell tickets. the platform will take a percentage of the ticket sale and the rest will go to the event organiser. this was the main reason I bought the All Events Manager Pro.
Currently
-im getting a blank screen for the connect stripe as the organiser
stripe connect user/organiser interface to setup stripe connect and receive payouts from ticket sales

it should look like this:
this is from their website

-and the ‘you are not allowed’ as you are an admin as admin which is expected
this is the admin view of the stripe connect page

I am working in test mode and the stripe is connected. All the payment comes to my stripe account minus the stripe fees.
but they do not go to the organiser as there is no way to connect to the plaform.
stripe test mode dashbaord - demonstrating a correct api setup

I made a ticket and got a responce saying to “reinstall the wp event manager” but that would delete a lot of work….
please help me find a solution.

Many thanks

some resources from the themes website:

https://wp-eventmanager.com/knowledge-base/stripe-split-payment/#articleTOC_1
https://wp-eventmanager.com/set-up-stripe-wordpress/?srsltid=AfmBOopgkljGaAD5_1XUB73Cbd3HL06MynTiexOn8dMRzCNg4usoUAp7

How to make nuxt multiselect work properly with data from Laravel API?

I’m using the USelectMenu component from the Nuxt UI library, and I need to ensure that all the options that the user can select are displayed. I have that covered with my mapped_looking_for method, and the options are bound correctly. Then, I need to display all the options that the user has already selected, which I also have working to some extent.

The problem is that the select should work in such a way that if an option is selected, there should be a tick next to it on the right indicating that it is indeed selected. However, even though it shows that 5 options are selected, I don’t see the tick next to them. I am also unable to interact with them in such a way that I could remove options. Essentially, it doesn’t work for me; I would have to manually delete them from the database.

Could anyone offer some advice? I’m relatively new to working with APIs, and I might be passing the data incorrectly. Thank you.

This is frontend.

 <USelectMenu v-model="looking_fors" :options="mapped_looking_for" multiple
                    :placeholder="getLookingForPlaceholder" />

<script>
const mapped_looking_for = ref([]);

const looking_for = ref([]);

const fetchLookingFor = async () => {
    try {
        const { data } = await api.get('/api/lookingFor');
        mapped_looking_for.value = data.data.map(item => ({
            label: item.name,
            value: item.id
        }));
        console.log('Mapped looking_for:', mapped_looking_for.value);
    } catch (error) {
        console.error('Error fetching looking for options:', error);
    }
};

const getLookingForPlaceholder = computed(() => {
    const count = profile.value.looking_fors?.length || 0;
    return count > 0 ? `${count} selected` : 'None';
});

const fetchProfile = async () => {
    try {
        const { data } = await api.get('/api/profiles/show');
        profile.value = data.profile;
        user.value = data.user;
        looking_for.value = data.profile.looking_fors.map(item => item.id); 
    } catch (error) {
        console.error('Error fetching profile:', error);
    }
};

const updateProfile = async () => {
    try {
        const looking_for_ids = looking_for.value.map(item => item.value);

       
        await api.put(`/api/profiles/${profile.value.id}/looking-for`, {
            looking_for: looking_for_ids
        });
        console.log('Profile updated successfully');
    } catch (error) {
        console.error('Error updating profile:', error);
    }
};
</script>

This is what I have on backend.

 public function updateLookingFor(Request $request): JsonResponse
{
    $user = $request->user();
    $profile = $user->profile;
    $validated = $request->validate([
        'looking_for' => 'array',
        'looking_for.*' => 'exists:looking_fors,id',
    ]);

    $profile->lookingFors()->syncWithoutDetaching($validated['looking_for']);

    return response()->json(['message' => 'Looking for updated successfully']);
}

// And route
    Route::put('/profiles/{id}/looking-for', [ProfileController::class, 'updateLookingFor']);

URL navigation behaving strange

I am working on my website. I have separate PHP files that handle rendering and are pointed to by an .htaccess configuration.

Options All -Indexes

RewriteEngine On
RewriteBase /alix

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^essays/?$ essay.php [QSA,NC,L]
RewriteRule ^essays/([^/]*)?$ essay.php?title=$1 [QSA,NC,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^books/?$ book.php [QSA,NC,L]
RewriteRule ^books/([^/]*)?$ book.php?title=$1 [QSA,NC,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ index.php [R=301,L]

In the book.html, I have the following link:

<a href="books/hackers-and-painters-big-ideas-from-the-computer-age">Hackers & Painters: Big Ideas from the Computer Age</a>

When I access my page:

enter image description here

Then I try to navigate:

enter image description here

To open a specific URL under the books/ URL. Upon clicking, I get this in Firefox:

http://127.0.0.1/alix/books/books/hackers-and-painters-big-ideas-from-the-computer-age

This same behavior happens when I try to navigate between subpages as well:

E.g., navigating back to Essays from Books URL:

enter image description here

Main navigation is constructed from this:

$navigation_menu = array(
    "home" => "/alix",
    "essays" => "essays",
    "books" => "books",
);

Manage custom stock conflict WooCommerce

I have created custom bookings tables.

Table Structure

wp_et_bk_bookings
    id - PK
    order_id - FK
    from_time
    to_time
    booking_date
    user_id - FK
    product_id - FK
    status

wp_et_bk_bookings_details
    id - PK
    et_bk_bookings_id - FK
    et_bk_event_ticket_types_dates_id - FK
    ticket_type_name
    quantity

I have two hooks used for block the stock exausts

In process_woocommerce_checkout_order_processed() once order confirmed I have added the booking.

But when user clicked place order for same ticket at same time it conflict and my stock gone in minus.

<?php
add_action('woocommerce_before_checkout_process', 'custom_remove_exhausted_booking_items');
add_action('woocommerce_checkout_order_processed', 'process_woocommerce_checkout_order_processed', 10, 1);

function custom_remove_exhausted_booking_items()
{
   global $wpdb;

   $wpdb->query('START TRANSACTION');

   $exhausted = false;
   foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
      $current_quantity = $cart_item['quantity'];

      $time_slot_id = isset($cart_item['time_slot_id']) ? $cart_item['time_slot_id'] : null;
      $et_bk_event_ticket_types_dates_id = isset($cart_item['et_bk_event_ticket_types_dates_id']) ? $cart_item['et_bk_event_ticket_types_dates_id'] : null;

      if (! $time_slot_id || ! $et_bk_event_ticket_types_dates_id) {
         continue;
      }

      $ticket_types = $wpdb->get_results("
            SELECT tt.*, ttd.id AS et_bk_event_ticket_types_dates_id, ttd.date, ttd.price AS date_price, ttd.quantity AS date_quantity, ttd.deposit_amount AS date_deposit 
            FROM {$wpdb->prefix}et_bk_event_ticket_types tt
            LEFT JOIN {$wpdb->prefix}et_bk_event_ticket_types_dates ttd ON tt.id = ttd.et_bk_event_ticket_types_id
            WHERE tt.et_bk_event_timeslots_id = $time_slot_id
            AND ttd.id = $et_bk_event_ticket_types_dates_id
            ORDER BY tt.sort_order ASC
        ");

      if (empty($ticket_types)) {
         continue;
      }

      foreach ($ticket_types as $ticket) {
         $booked_quantity = $wpdb->get_var("
                SELECT SUM(bd.quantity)
                FROM {$wpdb->prefix}et_bk_bookings b
                INNER JOIN {$wpdb->prefix}et_bk_bookings_details bd ON b.id = bd.et_bk_bookings_id
                WHERE bd.et_bk_event_ticket_types_dates_id = {$ticket->et_bk_event_ticket_types_dates_id}
                AND b.status IN ('pending', 'processing', 'on-hold', 'completed')
            ");
         $booked_quantity += $current_quantity;
         if ($booked_quantity > $ticket->date_quantity) {
            WC()->cart->remove_cart_item($cart_item_key);
            $exhausted = true;
         }
      }
   }
   if ($exhausted) {
      $wpdb->query('ROLLBACK');
      throw new Exception('Some items in your cart are no longer available for booking. Please review your cart and try again. <script>setTimeout(() => { location.reload(); }, 1000);</script>');
   } else {
      $wpdb->query('COMMIT');
   }
}

function process_woocommerce_checkout_order_processed($order_id)
{
$inserted = $wpdb->insert(
         $wpdb->prefix . 'et_bk_bookings',
         array(
            'order_id'     => $order_id,
            'time_slot_id' => $time_slot_id,
            'time_slot'    => $time_slot,
            'booking_date' => date('Y-m-d', strtotime($booking_date)),
            'user_id'      => $user_id,
            'product_id'   => $product_id,
            'from_time'    => $time_slot_details->from_time,
            'to_time'      => $time_slot_details->to_time,
            'status'       => $status
         ),
         array(
            '%d',
            '%d',
            '%s',
            '%s',
            '%d',
            '%d',
            '%s',
            '%s',
            '%s',
         )
      );
      if ($inserted) {
         $booking_id = $wpdb->insert_id;

         $future_payment_total = 0;

         foreach ($original_order->get_items() as $item_id => $item) {
            $ticket_type_name = $item->get_meta('ticket_type_name');
            $et_bk_event_ticket_types_dates_id = $item->get_meta('et_bk_event_ticket_types_dates_id');

            // Insert multiple entries in event_ticket_bookings_details
            $wpdb->insert(
               $wpdb->prefix . 'et_bk_bookings_details',
               array(
                  'et_bk_bookings_id'         => $booking_id,
                  'et_bk_event_ticket_types_dates_id' => $et_bk_event_ticket_types_dates_id,
                  'ticket_type_name'          => $ticket_type_name,
                  'quantity'                  => $item->get_quantity()
               ),
               array(
                  '%d',
                  '%d',
                  '%s',
                  '%d'
               )
            );

            // Retrieve future payment from meta and convert to float
            $future_payment = $item->get_meta('future_payment');
            $future_payment = preg_replace('/[^d.]/', '', $future_payment); // Clean up the future payment value
            $future_payment = floatval($future_payment);

            if ($future_payment) {
               $future_payment_total += $future_payment * $item->get_quantity();
            }
         }

Note – If user at different time only added in cart and then try to place order then it wont allowed.