How to set up CORS in Laravel to allow credentials and specific origins?

I’m working on a Laravel application that needs to handle CORS for requests coming from a Vue 3 frontend. I am encountering a CORS error related to credentials, and I need help configuring CORS correctly in my Laravel backend.

I receive the following error when trying to make an XMLHttpRequest from my Vue application to my Laravel backend:

Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/oauth/token' from origin 'http://127.0.0.1:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'.

Sylius override AvailableProductOptionValuesResolver

With sylius 1.13 i wan’t to override AvailableProductOptionValuesResolver.php

I’ve copied the original class in src/Component/Product/Resolver/AvailableProductOptionValuesResolver.php

and change the namespace and add debug:

<?php

namespace AppComponentProductResolver;
class AvailableProductOptionValuesResolver implements AvailableProductOptionValuesResolverInterface
{
    public function resolve(ProductInterface $product, ProductOptionInterface $productOption): Collection
    {
        dd('modify');

What other changes need to be made for this class to be used? Because here it’s always the file in /vendor/…/AvailableProductOptionValuesResolver that’s used.

ICMPv6 solicitation request in PHP

$socket = socket_create(AF_INET6, SOCK_RAW, 58);
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 1, 'usec' => 0));
$type = chr(135);
$code = chr(0);
$check = chr(0);
$check .= chr(0);

$reserverd = chr(0) . chr(0) . chr(0) . chr(0);
$distMul = "ff02::1:ff26:13dc"; //solicitation node multicast address
$target = "fe80::3b40:f032:5726:13dc";
$id = inet_pton($target);
socket_set_option($socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, 255);
$package = $type . $code . $check . $reserverd . $id;
socket_connect($socket, $distMul, 0);
socket_send($socket, $package, strlen($package), 0);
$str = socket_read($socket, 2048);
socket_close($socket);

Above is a script to send ICMPv6 solicitation request.
here is Wireshark capture.

enter image description here

the problem is , the request never get any reply, according to the IPV6 doc, the script should get a “Neighbor Advertisement (Type 136)” reply, but this is not happening.

Can I debug PHP with shared hosting?

I have VS Code installed on my client (laptop).

PHP is installed on the server. However, since its shared hosting, I can’t install anything myself (like Xdebug). Is possible to debug PHP (set breakpoints, step through code)? For example, can I use the Interactive PHP Debugger?

NuSphere PhpED IDE says that the debugger works with shared hosting. I found a tutorial on how to set it up. I’m hoping the same can be done with VS Code.

I’m trying to insert data into new created mySql table [closed]

So I created a page where the details a product can be stored.
Here is how it works:

  1. When the window loads 2 IDs are created (ABC and DEF).
  2. The user can insert any data and values in the site.
  3. After that they can click “SEND”.
  4. After clicking that button, there is a table in mySql named ‘Details’ where details such as ID1, ID2, time, and date are stored.
  5. Alongside that, a new table is created name “ABC_DEF” (ID1_ID2), and the data written by sender is stored in it.
  6. Then the site creates a link to share which contains only ID2. For example, https://www.example.com/Data/?share?ID2=DEF
  7. After sending this to the other person, when they try to open it, the site identifies the ?share and text after ?ID2 and searches for that row in the ‘Details’ table in mySql. Then it identifies the ID1 and ID2 and goes to retrieve the data in table ID1_ID2 to display to the user as output.

But the problem is the at all times the data is being stored in ‘Details’ and a table is being created by ID1_ID2. But at random times the data written is not being stored in the created table.
I don’t know if this is because of cache issue or what. And it’s very confusing since it works sometimes and it doesn’t. And it’s completely random on when it works and when it doesn’t.

The link is being created, the details in the ‘Details’ table are always being inserted correctly, and the table is being created every single time. But the data to be stored in the table is uncertain.

Is there any way to resolve and fix this?
I’ve used the languages HTML, CSS, jQuery, PHP, and mySql commands in PHP.

Restrict payment gateways based on applied coupons in WooCommerce checkout displaying a message

I would like to only show e.g. Stripe if coupon code 123 is used. So, I have come up with the code which is working, but I would also like to show a message at the top of the checkout, where the woo notices show. My message isn’t showing correctly.

// restrict coupon codes payment method
add_filter('woocommerce_available_payment_gateways', 'unset_gateway_by_applied_coupons');

function unset_gateway_by_applied_coupons($available_gateways) {
    // prevents coupon error in admin
    if( is_admin() ) 
        return $available_gateways;
    
    global $woocommerce;
    $unset = false; // the norm
    
    // names of coupons
    $coupon_codes = array('test123', 'check123');
            
    foreach($coupon_codes as $coupon_code) {
        
        // if code is used in cart
        if(in_array($coupon_code, WC()->cart->get_applied_coupons() )){
            //echo 'found =' .$coupon_code;
            unset($available_gateways['bacs']);
            unset($available_gateways['invoice']);
            // $message = sprintf( __('<br><p class="coupon-code">The coupon code  "%s" can only use the Credit Card payment method.</p>'), $coupon_code);  // <<<<< not working
        }
            
    }
    return $available_gateways;
}

About php and react jsx file [closed]

“I created a form in React JSX, which has some input fields like name, email, age, etc. All the data from these fields is being saved in a PHP database, but the CV file is not uploading to the specified path. The path should be like ‘uploads/filename’, but it’s showing ‘C:/fake/filename’. There are no errors in the PHP code.”

I would try that my react jsx form all input fields data should be svae in php database

Property [$selectedBookingStatuses.0] Not Found on Livewire Component in Laravel 10

I’m working on a Laravel 10 project using Livewire 3, where I’m building a booking management system. In this system, users can filter bookings by various statuses using a multiple select dropdown or a series of checkboxes. However, I encountered the following error while trying to bind the checkboxes to an array in my Livewire component:

Context:

Objective:

The goal is to allow users to filter bookings by their statuses, such as “Open,” “Closed,” “In Progress,” etc. Users should be able to select multiple statuses to filter the results. This is implemented using checkboxes within a dropdown-like structure that is toggled by a button.

Property [$selectedBookingStatuses.0] not found on component: [test-bookings-list]

TestBookingsList.php

<?php

namespace AppLivewire;

use LivewireComponent;
use LivewireWithPagination;
use AppModelsBookingModel;
use AppModelsUser;
use AppModelsJSVillas;
use IlluminateSupportFacadesSession;
use IlluminateSupportFacadesLog;

class TestBookingsList extends Component
{
    use WithPagination;

    public $start_date;
    public $end_date;
    public $booked_by;
    public $villa_id;
    public $search_query;
    public $selectedPaymentStatuses = [];
    public $selectedBookingStatuses = [];

    public $searchTerm = '';
    public $date_type;
    public $booking_division = '';

    public $users;
    public $villas;

    public function mount()
    {
        // Initializing properties from session or default values
        $this->start_date = session('testing_start_date');
        $this->end_date = session('testing_end_date');
        $this->villa_id = session('testing_villa_id');
        $this->booked_by = session('testing_booked_by');
        $this->searchTerm = session('testing_searchTerm');
        $this->selectedPaymentStatuses = session('testing_selectedPaymentStatuses', []);
        $this->selectedBookingStatuses = session('testing_selectedBookingStatuses', []);
        $this->date_type = session('testing_date_type');
        $this->booking_division = session('testing_booking_division');
    }

    public function updated($propertyName)
    {
        // Logging and updating session
        Log::debug("Updated Property: $propertyName", ['value' => $this->$propertyName]);
        session(['testing_' . $propertyName => $this->$propertyName]);
        $this->resetPage();
    }

    public function render()
    {
        // Query logic based on filters
        $query = BookingModel::where('status', 0)->with(['villa', 'user'])->orderBy('id', 'desc');

        if ($this->date_type == "range") {
            if ($this->start_date) {
                $query->where('start_date', '>=', $this->start_date);
            }
            if ($this->end_date) {
                $query->where('end_date', '<=', $this->end_date);
            }
        } else {
            if ($this->start_date) {
                $query->where('start_date', $this->start_date);
            }
            if ($this->end_date) {
                $query->where('end_date', $this->end_date);
            }
        }

        if ($this->booking_division) {
            $query->where('booking_division', $this->booking_division);
        }

        if ($this->booked_by) {
            $query->where('booked_by', $this->booked_by);
        }

        if ($this->searchTerm) {
            if (is_numeric($this->searchTerm)) {
                $query->where(function ($q) {
                    $q->where('id', $this->searchTerm)
                        ->orWhere('mobile_no', 'like', '%' . $this->searchTerm . '%')
                        ->orWhere('id', 'like', '%' . $this->searchTerm . '%');
                });

                // Prioritize exact matches for numeric search terms
                $query->orderByRaw("FIELD(id, ?) DESC", [$this->searchTerm]);
            } else {
                $query->where('booking_name', 'like', '%' . $this->searchTerm . '%');
            }
        }

        if ($this->villa_id) {
            $query->where('villa_id', $this->villa_id);
        }

        if (!empty($this->selectedPaymentStatuses)) {
            $query->whereIn('payment_status_text', $this->selectedPaymentStatuses);
        }
        if (!empty($this->selectedBookingStatuses)) {
            $query->whereIn('booking_status_text', $this->selectedBookingStatuses);
        }

        $bookings = $query->paginate(20);

        return view('livewire.test-bookings-list', [
            'bookings' => $bookings,
            'users' => User::whereIn('role', [1, 2])->orderBy('name', 'ASC')->pluck('name', 'id'),
            'villas' => JSVillas::orderBy('name', 'ASC')->pluck('name', 'id'),
        ]);
    }
}

resources/views/livewire/test-bookings-list.blade.php

<div class="mb-4">
                <!-- Booking Status -->
                <label class="block text-sm font-medium mb-1" for="booking_status">Status</label>
                <div class="relative inline-flex" x-data="{ open: false }">
                    <button id="booking_status" class="btn w-60 bg-white dark:bg-slate-800 border-slate-200 hover:border-slate-300 dark:border-slate-700 dark:hover:border-slate-600 text-slate-500 hover:text-slate-600 dark:text-slate-400 dark:hover:text-slate-300" aria-haspopup="true" @click.prevent="open = !open" :aria-expanded="open">
                        <span class="sr-only">Booking Status</span>
                        <span class="ml-2">Booking Status</span>
                    </button>
                    <div class="origin-top-right z-10 absolute top-full left-0 min-w-56 bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 pt-1.5 rounded shadow-lg overflow-hidden mt-1" @click.outside="open = false" @keydown.escape.window="open = false" x-show="open" x-transition:enter="transition ease-out duration-200 transform" x-transition:enter-start="opacity-0 -translate-y-2" x-transition:enter-end="opacity-100 translate-y-0" x-transition:leave="transition ease-out duration-200" x-transition:leave-start="opacity-100" x-transition:leave-end="opacity-0" x-cloak>
                        <ul class="mb-4">
                            <li class="py-1 px-3">
                                <label class="flex items-center">
                                    <input type="checkbox" class="form-checkbox" wire:model.live="selectedBookingStatuses" value="Open" />
                                    <span class="text-sm font-medium ml-2">Open</span>
                                </label>
                            </li>
                            <li class="py-1 px-3">
                                <label class="flex items-center">
                                    <input type="checkbox" class="form-checkbox" wire:model.live="selectedBookingStatuses" value="Closed" />
                                    <span class="text-sm font-medium ml-2">Closed</span>
                                </label>
                            </li>
                            <li class="py-1 px-3">
                                <label class="flex items-center">
                                    <input type="checkbox" class="form-checkbox" wire:model.live="selectedBookingStatuses" value="In Progress" />
                                    <span class="text-sm font-medium ml-2">In Progress</span>
                                </label>
                            </li>
                            <li class="py-1 px-3">
                                <label class="flex items-center">
                                    <input type="checkbox" class="form-checkbox" wire:model.live="selectedBookingStatuses" value="Menu Done" />
                                    <span class="text-sm font-medium ml-2">Menu Done</span>
                                </label>
                            </li>
                            <li class="py-1 px-3">
                                <label class="flex items-center">
                                    <input type="checkbox" class="form-checkbox" wire:model.live="selectedBookingStatuses" value="No Food" />
                                    <span class="text-sm font-medium ml-2">No Food</span>
                                </label>
                            </li>
                            <li class="py-1 px-3">
                                <label class="flex items-center">
                                    <input type="checkbox" class="form-checkbox" wire:model.live="selectedBookingStatuses" value="Accounts Pending" />
                                    <span class="text-sm font-medium ml-2">Accounts Pending</span>
                                </label>
                            </li>
                            <li class="py-1 px-3">
                                <label class="flex items-center">
                                    <input type="checkbox" class="form-checkbox" wire:model.live="selectedBookingStatuses" value="Cancelled" />
                                    <span class="text-sm font-medium ml-2">Cancelled</span>
                                </label>
                            </li>
                        </ul>
                    </div>

                </div>
                <!-- End -->
            </div>

Problem:

The error occurs because Livewire is attempting to bind a checkbox to a specific index of the selectedBookingStatuses array (e.g., selectedBookingStatuses.0), but this index does not exist or is not initialized correctly.

Change the file extension and remove the directory from the URL htaccess

I need it to

  1. http://site:8080/acc/cl.php opened in the browser as http://site:8080/cl.html
  2. http://site:8080/acc/cl-main.php?cid=1 opened in the browser as http://site:8080/cl-main.html

So far, the only rule that works for me is for files in the root of the site, where I remove php and replace it with html

RewriteEngine on
RewriteBase /

RewriteCond %{THE_REQUEST} (.*).html
RewriteRule ^(.*).html $1.php [L]

but this rule no works

RewriteCond %{THE_REQUEST} acc/(.*).html
RewriteRule ^acc/(.+).html$ acc/$1.php [L]

Convert php to mysql orders

I have some nextcloud code in php how to create a table. I want to convert it to mysql. Sounds like an easy task, but the docu and documentation is not clear to me.

This line:

$table->setPrimaryKey(['objecttype', 'objectid', 'systemtagid'], 'som_pk');

seems to use an array and a new column as index. I do not know where som_pk comes from and how to write it in mysql orders. Same goes for index.
Can someone give ma a hint?

Source of Code

if (!$schema->hasTable('systemtag_object_mapping')) {
    $table = $schema->createTable('systemtag_object_mapping');
    $table->addColumn('objectid', 'string', [
        'notnull' => true,
        'length' => 64,
        'default' => '',
    ]);
    $table->addColumn('objecttype', 'string', [
        'notnull' => true,
        'length' => 64,
        'default' => '',
    ]);
    $table->addColumn('systemtagid', 'integer', [
        'notnull' => true,
        'length' => 4,
        'default' => 0,
        'unsigned' => true,
    ]);
    $table->setPrimaryKey(['objecttype', 'objectid', 'systemtagid'], 'som_pk');
    //          $table->addUniqueIndex(['objecttype', 'objectid', 'systemtagid'], 'mapping');
    $table->addIndex(['systemtagid', 'objecttype'], 'systag_by_tagid');
}
>

This is the mysql code I created from it. I am unsure how to create the index and can not find anything about it in php tutorials. Can someone jump in and tell me how to create the index properly?

CREATE table nextcloud.oc_systemtag_object_mapping (
    objectid VARCHAR(64) NOT NULL ,
    objecttype VARCHAR(64) NOT NULL,
    systemtagid INT,
    PRIMARY KEY(objecttype, objectid, systemtagid)
); 

CREATE INDEX ??? ON nextcloud.oc_systemtag_object_mapping(???)

apache, php-fpm 100% cpu

Several times a day I see 100% CPU utilization and all processes using php-fpm. Apache logs doesn’t give me any information, because I don’t have many requests from the same adresses IP.

On server I have only one page wordpress with woocommerce which visiting about 2-3 thousand users per day, sometime in peak about 100-200 users. What I did:

  • I enabled redis, wp-fastest cache which cache page to static html
  • I changed changed default value from pm.max_children = 10 to pm.max_children = 5
  • I create swap file 4GB
  • I disabled wp-cron, xlmrpc.php
  • I enabled opcache
  • I used MySQLTuner-perl to opitimze database and I set
[mysqld]
Settings buforrer InnoDB
innodb_buffer_pool_size = 2G
innodb_log_file_size = 512M
innodb_log_buffer_size = 256M

table_definition_cache = 600
query_cache_size = 0
local-infile = 0
max_allowed_packet=64M

slow_query_log = 1
slow_query_log_file = /var/log/mysql/mysql-slow.log
long_query_time = 5

My server configuration.

  • CPU Intel(R) Xeon(R) Gold 6150 CPU @ 4 X 2.70GHz
  • Memory 8 GB (Cached:3.71 GB/ Used: 3.71 GB, Free: 1.16 GB)
  • Disk 500GB Nvme

Custom 404 Page Not Displaying in Laravel with Nginx on Azure Hosting

I’m facing an issue where my custom 404 page is not displaying in a Laravel application hosted on Azure with Nginx. Instead, the default Nginx 404 page is shown. I’ve set up the configuration as follows:

/site/startup.sh

#!/bin/bash
cp /home/site/nginx.conf /etc/nginx/sites-available/default
service nginx reload

apt-get update -qq && apt-get install cron -yqq
(crontab -l 2>/dev/null; echo "* * * * * /usr/local/bin/php /home/site/wwwroot/artisan schedule:run >> /dev/null 2>&1")|crontab
service cron start

/site/nginx.conf

server {
    listen 8080;
    listen [::]:8080;
    listen 443 ssl;
    listen [::]:443 ssl;
    root /home/site/wwwroot/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

    index  index.php index.html index.htm;
    server_name  example.com; 
    port_in_redirect off;

    charset utf-8;

    location / {            
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ /.(?!well-known).* {
        deny all;
    }

    location ~ /.git {
        deny all;
        access_log off;
        log_not_found off;
    }

    location ~* [^/].php(/|$) {
        fastcgi_split_path_info ^(.+?.[Pp][Hh][Pp])(|/.*)$;
        fastcgi_pass 127.0.0.1:9000;
        include fastcgi_params;
        fastcgi_param HTTP_PROXY "";
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param QUERY_STRING $query_string;
        fastcgi_intercept_errors on;
        fastcgi_connect_timeout 300; 
        fastcgi_send_timeout 3600; 
        fastcgi_read_timeout 3600;
        fastcgi_buffer_size 128k;
        fastcgi_buffers 4 256k;
        fastcgi_busy_buffers_size 256k;
        fastcgi_temp_file_write_size 256k;
    }

    server_tokens off;
    client_max_body_size 256M;
}

Laravel Exception Handler:

public function render($request, Throwable $exception)
{
    if ($this->isHttpException($exception)) {
        if ($exception->getStatusCode() == 404) {
            return response()->view('frontend.test', [], 404); // If I change the status code to 200, the view can be rendered successfully.
        }
    }


    return parent::render($request, $exception);
}

What I’ve Tried:

  • Ensured error_page 404 /index.php; and fastcgi_intercept_errors on; is set in the Nginx configuration.
  • Cleared Laravel cache using php artisan config:clear, cache:clear, and view:clear.
  • Verified that the frontend.test view exists and is error-free.
  • Restarted Server.

Despite these efforts, the custom 404 page does not appear. Any insights or suggestions would be greatly appreciated!

difference of 2 dates into days/weeks using php html

I have code which needs to state the difference of 2 dates from a table and display the range from start date to end date (in days and weeks) on the same table as well. How can I execute it? I have this code but it doesnt seem to do anything with the dates.The column names of the dates are ‘date_started’ and ‘date_completed’. ex. 2024-07-01 to 2024-07-26

$datetime1 = date_create($_GET['date_started']);
$datetime2 = date_create($_GET['date_completed']);
$interval = date_diff($datetime1, $datetime2);

Then this is the echo that I put in the table:

<td>{$interval->format('%R%a days')}</td>

and the output is = +0 days

but I want the output to be = 3 weeks and 5 days

Is there a hook for WooCommerce “all products” block to change the variable product’s price range to something custom?

I’m not able to hook into WooCommerce ‘all products’ block to display a custom price range for b2b customer. I tried to look for a specific hook in the WooCommerce documentations but couldn’t figure out the correct one for it or if one exists.

This problem occurs only on a “page” which has this block. It’s working well elsewhere, such as the single product page and related products etc. I’m using Gutenberg for building the site/store.