How to use headers_sent($filename, $linenum) in php?

I’m new to PHP, i wrote this:

<?php
header("Content-type: application/json");
flush();
// Note that $filename and $linenum are passed in for later use.
// Do not assign them values beforehand.
if (!headers_sent($filename, $linenum)) {
    header('Location: http://www.example.com/');
    exit;

// You would most likely trigger an error here.
} else {

    echo "Headers already sent in $filename on line $linenumn" .
          "Cannot redirect, for now please click this <a " .
          "href="http://www.example.com">link</a> insteadn";
    exit;
} 

And the output is:

Headers already sent in  on line 0
Cannot redirect, for now please click this <a href="http://www.example.com">link</a> instead

As you can see, there is an empty string instead of the file name and the line is 0. How can I get the file name and line number where the headers were sent?

WooCommerce Orders to CSV Export

I am trying to add all new WooCommerce orders to a CSV called orders.csv. All works great but cant get each order to be on a new line. It merges with header, ie Products12345. Any ideas why this could be happening? I’ve tried using /n and PHP_EOL.

            add_action('woocommerce_checkout_order_processed', 'ppd_append_order_to_csv_full', 10, 1);

            function ppd_append_order_to_csv_full($order_id) {
                if (!$order_id) return;

                $order = wc_get_order($order_id);
                if (!$order) return;

                $folder_path = ABSPATH . 'ppd/';
                $csv_path = $folder_path . 'orders.csv';

                if (!file_exists($folder_path)) {
                    mkdir($folder_path, 0755, true);
                }

                $need_headers = !file_exists($csv_path) || filesize($csv_path) === 0;

                if ($need_headers) {
                    $file = fopen($csv_path, 'wb');
                    fwrite($file, "xEFxBBxBF"); // UTF-8 BOM for Excel

                    fputcsv($file, [
                        'Order ID',
                        'Shipping Method',
                        'Products'
                    ]);

                    fwrite($file, PHP_EOL);
                } else {
                    $file = fopen($csv_path, 'ab');
                }

                // Products
                $items = [];
                foreach ($order->get_items('line_item') as $item_id => $item) {
                    $product = $item->get_product();
                    $name = $item->get_name();
                    $sku = $product ? $product->get_sku() : '';
                    $qty = $item->get_quantity();
                    $unit_price = $qty > 0 ? number_format($item->get_total() / $qty, 2, '.', '') : '0.00';
                    $items[] = "{$name} (SKU: {$sku}) x {$qty} - £{$unit_price}";
                }

                $shipping_method_names = [];
                foreach ($order->get_shipping_methods() as $shipping_item) {
                    $shipping_method_names[] = $shipping_item->get_method_title();
                }

                $formatted_phone = $order->get_billing_phone() ? "'" . $order->get_billing_phone() : '';

                // Row data
                $data = [
                    $order->get_id(),
                    implode(' | ', $shipping_method_names),
                    implode(' | ', $items) // <- this often has commas
                ];

                fputcsv($file, $data);
                fwrite($file, PHP_EOL);
                fclose($file);
            }

Laravel Auditing Not Logging old_values and new_values When Using Observer

I’m working with Laravel Filament where I’m using audits package for audits the activity of laravel model. I’ve laravel model like:

<?php

namespace AppModels;

use AppCastsMoney;
use AppObserversInventoryObserver;
use IlluminateDatabaseEloquentAttributesObservedBy;
use IlluminateDatabaseEloquentBuilder;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentRelationsBelongsTo;
use IlluminateDatabaseEloquentRelationsHasOne;
use IlluminateDatabaseEloquentSoftDeletes;
use OwenItAuditingContractsAuditable;

#[ObservedBy(InventoryObserver::class)]
class Inventory extends Model implements Auditable
{
    use OwenItAuditingAuditable;
    use HasFactory, SoftDeletes;

    protected $guarded = [];
}

And InventoryObserver.php

<?php

namespace AppObservers;

use AppEventsRefreshInventories;
use AppEventsRefreshProducts;
use AppModelsInventory;
use AppServicesTaxCalculatorService;

class InventoryObserver
{
   public function created(Inventory $inventory): void
    {
        if ($inventory->gross_amount) {
            $taxCalculatorService = TaxCalculatorService::make($inventory->gross_amount, $inventory->tax_rate);

            $inventory->net_amount = $taxCalculatorService->getNetAmount();
            $inventory->tax_amount = $taxCalculatorService->getTaxAmount();

            $inventory->saveQuietly();
        }

        $inventory->machine->updateStockPercentage();
    }

    public function updated(Inventory $inventory): void
    {
        if ($inventory->isDirty(['gross_amount', 'tax_rate'])) {
            $taxCalculatorService = TaxCalculatorService::make($inventory->gross_amount, $inventory->tax_rate);

            $inventory->net_amount = $taxCalculatorService->getNetAmount();
            $inventory->tax_amount = $taxCalculatorService->getTaxAmount();

            $inventory->saveQuietly();

            //            RefreshProducts::broadcast($inventory->machine);
        }

        if ($inventory->isDirty('quantity', 'max_quantity')) {
            $inventory->machine->updateStockPercentage();

            //            RefreshInventories::broadcast($inventory->machine);
        }
    }

When I’m saving values from form it’s auditing the values in audits database table with empty values inside old_values and new_values.
enter image description here

Can anyone help me how can I solve this problem?

Thanks…

How to check if a class has child classes without loading the whole project?

I’m writing a custom PHPStan rule that suggests marking a class as readonly (introduced in PHP 8.2) when it meets all the necessary conditions.

One of the requirements for safely applying readonly is ensuring that the class has no child classes, because in PHP 8.2, if a parent is readonly, all its child classes must be readonly too.

The problem is, PHPStan doesn’t provide a simple, reliable way to check if a class is extended within the project during static analysis.

I’ve considered the following approaches:

  • Using Composer’s autoload_classmap.php, but with PSR-4 autoloading, it often doesn’t contain project classes.
  • Forcing composer dump-autoload -o --classmap-authoritative, which solves the problem but isn’t always acceptable for development setups.
  • Writing a custom file scanner that parses PHP files to extract namespace and class names to build a class map (either via simple regex or using nikic/php-parser).

Question:
What is the recommended or common approach to reliably detect child classes in a PHPStan custom rule, considering static analysis only?
Are there any best practices for this scenario, or do people generally rely on their own project-specific class scanning logic?

Yoast SEO Stopped Working After I Uploaded My Site To Hosting [closed]

After uploading the site to the hosting, the plugin stopped working correctly. It is impossible to enter the settings page, it is impossible to add meta tags. Please tell me, what could be the reason for this? In the page settings, the SEO block is displayed empty. When clicking on the tabs, nothing happens.

screenshot from the admin panel

AbanteCart 1.4.1 login redirects back to login page — session/cookie not persisting over HTTPS

I’m using AbanteCart v1.4.1 deployed on cPanel hosting under the subdirectory /shop with HTTPS enabled.

After successful login, the customer is immediately redirected back to the login page, and the session data is lost.

Session appears to drop right after the redirect:
Even though login is successful and session data is populated, AbanteCart doesn’t retain the session and goes back to the login screen.

What could cause AbanteCart session or cookies to reset immediately after login?

Are there known issues with secure cookies, session storage, or domain/path mismatch in this version?

Any recommendations for debugging or fixing persistent login sessions in AbanteCart v1.4.1?

Laravel: Google is indexing my site with subdomains, which are now obsolete. How to redirect?

Situateion:
In my app I had c. 20 subdomains. Now they are gone and https certificates with them.
However, Google is indexing my site with use of the subdomains, which was never the intention. EExample:
Google gets to http://booktitle.domainname.com/shop
and the desired URL for the shop should be https://domainname.com/shop

My solution:

now for some URLs I have created a middleware which processes the referer URL and redirects the user to the correct URL.
Note: There is c. 20 subdomains which are involved.

if(str_contains(url()->current(), 'obsoletesubdomain.domainname') {

    return Redirect::away('https://domainname.com'.request()->getPathInfo());
}

My questions

  1. Is there a better solution to handle the issue?
  2. Where should I put the middleware in Laravel 12 in order to handle the obsolete subdomains sitewide?

Thank you.

Nginx Showing 404 in Header Despite Page Rendering Fine (CentOS, aaPanel, CodeIgniter 4)

I’m experiencing a strange issue where the page at
https://customsportswears.com/ibc52/custom-afl-uniforms-high-quality-australian-football-league-gear.html
loads fine in the browser, but when checked via developer tools or external services, the HTTP response header is 404.

Stack:

  • CentOS (aaPanel)
  • Nginx 1.24.0
  • PHP 8.3 (via PHP-FPM)
  • CodeIgniter 4

Current Nginx Configuration (Partial):

error_page 403 500 502 503 504 /index.php;
error_page 404 /404.php;

location = /404.php {
    internal;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index 404.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

location / {
    try_files $uri $uri/ /index.php$is_args$args;
    add_header Access-Control-Allow-Origin "*";
    add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
    add_header Access-Control-Allow-Headers "Content-Type, Authorization";
}

location ~ .php$ {
    include fastcgi_params;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
} ```

What's Happening:
- The actual rendered page appears correct.
- However, HTTP response header for that URL is returning a 404 status.
- Suspect CodeIgniter or nginx config may be causing this, possibly due to try_files, error_page logic, or internal redirect conflicts.
Tried:
- Confirmed that the controller and route in CI4 return content properly.
- Double-checked the file path and route configs.
- Response status mismatch suggests a misconfiguration or forced status return.
Looking for insights from anyone who's handled similar 404 header issues with CodeIgniter and nginx under aaPanel. Could it be a CI4 header override after routing logic? Or does nginx misinterpret the fallback URL?
Any help is appreciated!

Create a fake random by changing a string into a number in PHP [closed]

I would like a way to show a random image on my site, but not random each time people refresh the page, but random for each string,
For this I have differents css rules :

.random1, .random2, .random3, …, .random10

Actually I do this:

<div class="random<?= rand(1, 10 ?>">...</div>

But I don’t want this to change at each refresh, so I would like to change for example the 4 first characters of my string (the content of the div) into a number
For example, “Hello” would return “3”, or “In this article …” would return 7.

But I don’t know how to do this ?
Thanks

display image from laravel application public folder path to jquery data table

I am trying to render image from public folder to the DataTable, where the image information like path are stored in database.
When I hard code the image information, the image is rendered. But when I make it dynamic it does not appear.
I took the reference from Display images from Database in Datatables using jQuery for a Laravel app
but it’s not working for me.

My ajax code,

var table = $('.data-table').DataTable({
            processing: true,
            serverSide: true,
            ajax: "{{ route('students.index') }}",
            columns: [{
                    data: 'DT_RowIndex',
                    name: 'DT_RowIndex'
                },
                {
                    data: 'name',
                    name: 'name'
                },
                {
                    data: 'image',
                    name: 'image',
                    "render": function (data) {
                    return '<img src="{{ asset("images/' +data+'") }}" />' }
                },
                {
                    data: 'action',
                    name: 'action',
                    orderable: false,
                    searchable: false
                },
            ]
        });

In browser, when I inspect the img tag it shows::

<img src="http://127.0.0.1:8000/images/' +data+'">

When I hard code the image name, it’s showing the image.

{
                    data: 'image',
                    name: 'image',
                    "render": function (data) {
                    return '<img src="{{ asset("images/9867543cu4R.jpg") }}" />' }
                },

How to solve this issue, please help.

Doctrine not saved relation when saving child entity with setting parent entity object

Here is example of mapping:

Cateogory mapping:

<entity name="AppCoreDomainPostItem" table="post_item">
   <id name="id" type="integer" column="id">
       <generator strategy="SEQUENCE"/>
   </id>
   <field name="title" type="string" length="256" />
   <many-to-one field="category"
           target-entity="AppCoreDomainPostCategory"
           inversed-by="items"
    >
       <join-column name="category_id" />
    </many-to-one>
</entity>

Item mapping:

<entity name="AppCoreDomainPostCategory" table="post_category">
   <id name="id" type="integer" column="id">
       <generator strategy="SEQUENCE"/>
   </id>
   <field name="title" type="string" length="256" />
   <one-to-many
           field="items"
           target-entity="AppCoreDomainPostItem"
           mapped-by="category"
           fetch="EXTRA_LAZY"
        >
        <cascade><cascade-all/></cascade>
    </one-to-many>
</entity>

Im trying to save item entity with category entity:

<?php
//...
$category = $em->getRepository(Category::class)->find($categoryId);
//category exists and received as Category object
$item = new Item();
$item->setTitle('test')
$item->setCategory($category);
$em->persist($item);
$em->flush();

Getting error:

A new entity was found through the relationship 'AppCoreDomainPostItem#category' that was   
  not configured to cascade persist operations for entity: TestCategory. To solve this issue: Either explicitly call Enti  
  tyManager#persist() on this unknown entity or configure cascade persist this association in the mapping for exa  
  mple @ManyToOne(..,cascade={"persist"})

If I trying with category reference:

$category = $em->getReFerence(Category::class, $categoryId);
$item = new Item();
$item->setTitle('test')
$item->setCategory($category);
$em->persist($item);
$em->flush();

Record in database saved, but category_id field is null

What am i doing wrong?

IlluminateContractsContainerBindingResolutionException: Target class [admin] does not exist when accessing /admin/users in Laravel with Filament

I’m working on a Laravel 12.17 + Filament v3 project. I installed Filament using:

./vendor/bin/sail artisan filament:install --panels

Then i generated a resource with:

./vendor/bin/sail artisan make:filament-resource User --generate

The admin dashboard loads fine at /admin, but navigating to /admin/users throws the following error:

IlluminateContractsContainerBindingResolutionException Target class
[admin] does not exist.

Here’s what I’ve already checked:

  • I do not have a manual Route::middleware(['admin']) or similar in
    web.php anymore.
  • I verified the generated UserResource.php exists under AppFilamentAdminResources.
  • My AdminPanelProvider.php has the following line:
    ->discoverResources(in: app_path('Filament/Admin/Resources'), for: 'App\Filament\Admin\Resources')

I also ran:

./vendor/bin/sail artisan route:clear
./vendor/bin/sail artisan optimize

Still getting the same error. Any idea what’s causing Laravel to think admin is a missing class?

Also, my http://localhost/admin is running fine but in the nav bar beside it after installing the user panels, the user option to navigate did not show up on the nav bar. I’ve been running into the same issue since yesterday and I can’t figure whats causing this error:

enter image description here

Scraping IDs from two pages behind a login [closed]

So I need some help getting ID’s from page sources. They are tables that contain links.

<table id="running_freeleech" class="items_table">   
    <tr class="colhead">
        <td colspan="2">Currently Running Freeleech</td>
        <td>Ends in</td>
    </tr>
    <tr class="group_torrent row_a">
        <td class="center cats_col">
            <div title="Adventure"class="cats_games tags_adventure windows"></div>
        </td>
    <td>
    <span id="groupplatform">
        <a href="artist.php?artistname=Windows">Windows</a></span> -<a href='page.php?id=696969' title='View File'>(title)                  
    </td>
  </tr>
<a href='page.php?id=12345'>Link</a> <!- This is the ID I need. I can put them into an array for the next step.  -->
</table>
<table>

<!-- First ID I need is in the LINK : example 696969 --->

<!-- The second page I need to grab two IDs ---> 

<table>
    <tbody id="edition_1">
        <tr class="group_torrent" style="font-weight: normal;" id="torrent09876">
            <td>
                <span>[<a href="torrents.phpaction=download&amp;id=NEEDTHISID&amp;authkey=NEEDTHISAUTHKEY&amp;torrent_pass=torrentpass" title="Download">DL</a>FILES<strong class="freeleech_label">Freeleech!</strong>]</a></span>
            </td>
        </tr>
    </tbody>
</table>

I can build the URL with that data and automate it. The problem is that it is a private site and I don’t know how to automate logging in. But I can manually login if that’s how I have to do it. I figure I can use jQuery to search through elements but I need a little push in the right direction.