Is shift and pop reliably in an php associative array? [closed]

I have a litte program that seems to reliably use push, pop and shift in PHP on an associative array. It works on the elements in the order. But… is it reliable that is has to work this way? I need an associative array that can reliably add elements after the last one and can reliably remove the oldest element.

<?php

$a = [];
$a['first'] = '1';
$a['second'] = '2';
$a[8] = '3';
$a['forth'] = '4';
print_r($a);

print "-- now push two values --n";
$a[] = '1st pushed value';
$a[] = '2nd pushed value';
print_r($a);

print "-- now pop last --n";
array_pop($a);
print_r($a);

print "-- now shift --n";
array_shift($a);
print_r($a);

print "-- now pop last --n";
array_pop($a);
print_r($a);

?>

To clarify: yes, I’ve read the documentation, but what is the first element of an array [‘test’ => ‘t’, 0 => ‘e’]? Is it ‘test’ or is it 0? Can I rely that ‘first’ is the first element put into an array when it comes to those functions? reliable means that it is no quirk but so intended. And no, I find the documentation very vague on that.

Laravel 12 & Sanctum

im using Laravel 12 with sanctum and try to get a login via Angular Frontend.
Until now, im able to register and also get a positive response for the csrf token.
For the login, I got an 500er error with the “message”: “Session store not set on request.”

I tried with the previous hints for this error message, but didnt helped. Does anybody have some hints for me?

my request inside of angular looks like this:

login(data: { email: string; password: string }): Observable<User> {
  const headers = new HttpHeaders({
  'Accept': 'application/json',
  'Content-Type': 'application/json'
});
return this.http.get("http://localhost:8000/sanctum/csrf-cookie", { headers: headers, withCredentials: true }).pipe(
  switchMap(() =>
    this.http.post<User>(`${this.baseUrl}/login`, data, {
      headers: headers,
      withCredentials: true,
    })
  )
);}

This is my laravel api.php router

Route::post('/login', function (Request $request) {
$credentials = $request->only('email', 'password');

if (Auth::attempt($credentials)) {
    $request->session()->regenerate();

    return response()->json([
        'message' => 'Login erfolgreich',
        'user' => Auth::user() // Aktuell eingeloggter User
    ]);
}

return response()->json(['message' => 'Unauthorized'], 401);
});

This is my middleware inside of app.php

->withMiddleware(function () {


    return [

        // 1. Laravel interner Support für Precognitive-Requests
        IlluminateFoundationHttpMiddlewareHandlePrecognitiveRequests::class,

        // 2. Session starten (wichtig für Sanctum + Login)
        IlluminateSessionMiddlewareStartSession::class,

        // 3. Sanctum Middleware, die API-Requests als "stateful" behandelt
        LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,



        // 5. Eigene globale Middleware (z. B. zusätzliche CORS Header)
        function (IlluminateHttpRequest $request, Closure $next) {
            $response = $next($request);

            $response->headers->set('Access-Control-Allow-Origin', 'http://spa.localhost:4200');
            $response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
            $response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
            $response->headers->set('Access-Control-Allow-Credentials', 'true');

            return $response;
        },
    ];
})

My cors.php

<?php
return [

// Erlaube nur relevante Pfade
'paths' => ['api/*', 'sanctum/csrf-cookie'],
// Erlaube alle HTTP-Methoden (GET, POST, etc.)
'allowed_methods' => ['*'],
// Erlaube nur deine Angular-App
'allowed_origins' => ['http://spa.localhost:4200'],
// Kein Pattern nötig, da Origin explizit erlaubt
'allowed_origins_patterns' => [],
// Alle Header erlauben (z. B. Content-Type, X-XSRF-TOKEN, etc.)
'allowed_headers' => ['*'],
// Keine speziellen Header müssen offengelegt werden
'exposed_headers' => [],
// Preflight-Caching (kann bei Bedarf höher gesetzt werden)
'max_age' => 0,
// Damit Cookies (Sessions) mitgeschickt werden dürfen
'supports_credentials' => true,
];

And my env:

SANCTUM_STATEFUL_DOMAINS=spa.localhost:4200
SESSION_DRIVER=cookie
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=.localhost

php function that downloads empty files [closed]

I have a problem with a function that is supposed to download. Why are empty files being downloaded? Where am I going wrong? Thank you all.

I pass the name of the file I need to download to the function.

function downloadAttachmentKb($filesDownload)
{
    if (empty($filesDownload)){
        return false;
    }
    
    set_time_limit(0);
    $DownloadDir = "./files/kbfiles/".$filesDownload ;
    $DownloadFiles = basename( $filesDownload);
    $DovnloadSize = filesize( $DownloadDir);
    
    if (!file_exists($DownloadDir) && !is_writable($DownloadDir)){
        die("errore");
    }
    
    $MimeFile = mime_content_type($DownloadDir);
    
    if ($MimeFile === false){
        header("Content-Type: application/force-download");
    }else{
        header(header: "Content-Type:".$MimeFile."");
    }
    
    if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE")){
        header("Content-Disposition: inline ; filename="". $DownloadFiles.""");
    } else{
        header(header: "Content-Disposition: attachment; filename="". $DownloadFiles .""");
    }
    
    header(header: "Content-Length: ". filesize($DownloadDir));
    header("Content-Description: File Transfer");
    header("Content-Transfer-Encoding: binary");
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: public");
    ob_clean();
    flush();
        
    echo file_get_contents($DownloadDir);
    
}
?>

Unable to open a browser when call is accepted [closed]

I am triggering a call from postman to mobile phone using twilio. I am able to call successfully. It rings on my phone. When I click accept, a message is prompted on the call. When I press 1, it says something error and does not redirect or open a website link.

How should I open a browser and display the url as passed?

 <?php

 namespace AppHttpControllers;

 use IlluminateHttpRequest;
 use TwilioRestClient;

class TwilioController extends Controller
{
public function makeCall(Request $request)
{
    $sid    = env('TWILIO_ACCOUNT_SID');
    $token  = env('TWILIO_AUTH_TOKEN');
    $twilio = new Client($sid, $token);

    $call = $twilio->calls->create(
        $request->input('to'), // User's phone number in E.164 format
        env('TWILIO_PHONE_NUMBER'), // Your Twilio number
        [
            'url' => 'http://testing.domain.tech/twilio/voice-prompt'
        ]
    );

    return response()->json(['status' => 'Call initiated', 'sid' => $call->sid]);
}

public function voicePrompt()
{
    $response = new TwilioTwiMLVoiceResponse();

    $gather = $response->gather([
        'numDigits' => 1,
        'action' => url('/twilio/handle-key-press'),
        'method' => 'POST'
    ]);
    $gather->say('Press 1 to receive a link via SMS.');

    // If no input, Twilio will call this after gather timeout
    $response->say('No input received. Goodbye!');
    
    return response($response)->header('Content-Type', 'text/xml');
}


public function handleKeyPress(Request $request)
{
    $digits = $request->input('Digits');
    $from = $request->input('From');
    $response = new TwilioTwiMLVoiceResponse();

    if ($digits == '1') {
        try {
            $sid    = env('TWILIO_ACCOUNT_SID');
            $token  = env('TWILIO_AUTH_TOKEN');
            $twilio = new Client($sid, $token);

            $twilio->messages->create(
                $from,
                [
                    'from' => env('TWILIO_PHONE_NUMBER'),
                    'body' => 'Here is your link: ' . url('/')
                ]
            );
            $response->say('A link has been sent to your phone via SMS. Thank you!');
        } catch (Exception $e) {
            Log::error('Twilio SMS error: ' . $e->getMessage());
            $response->say('Sorry, there was an error. Please try again later.');
        }
    } else {
        $response->say('Invalid option. Goodbye!');
    }

    return response($response)->header('Content-Type', 'text/xml');
 }
}

// web.php

Route::post('/twilio/voice-prompt', [TwilioController::class, 'voicePrompt'])->name('twilio.voicePrompt');
Route::post('/twilio/handle-key-press', [TwilioController::class, 'handleKeyPress'])->name('twilio.handleKeyPress');

// api.php

Route::post('/twilio/make-call', [TwilioController::class, 'makeCall']);

faild to install PHP 8.3 on Ubuntu 20.04 [closed]

I want to install php8.3 on Ubuntu 20.04.6. but

sudo apt-get install php8.3

returns :

E: Unable to locate package php8.3
E: Couldn't find any package by glob 'php8.3'
E: Couldn't find any package by regex 'php8.3'

what to do?

lsb_release -a

returns :

No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.6 LTS
Release:    20.04
Codename:   focal

apt policy php8.3 and apt-cache search php8.3 returns nothing


I added ppa:ondrej/php repository.

cat /etc/apt/sources.list.d/ondrej-ubuntu-php-focal.list

returns

deb http://ppa.launchpad.net/ondrej/php/ubuntu focal main
# deb-src http://ppa.launchpad.net/ondrej/php/ubuntu focal main

in fact on a machine php8.3 is installed but when trying to install extension php8.3-gmp on it ,can not find

load image in select dropdown list

I have a dropdown list, here in the option I want to load image also. I took reference from:
i want to display image in select option dynamically but not working

But the image is not loading. The path of image file is correct.

<select name="n_bundle_num" class="form-control" required>
    <option>--- select budle ---</option>
    @foreach ($bundles as $item)
        <option value="{{ $item->name }}" 
            data-subtext="<img src='/bundles/{{ $item->image_path }}'>">{{ $item->name }}
        </option>
    @endforeach
</select>

How to host the same folder in IIS using two different PHP versions?

I have a folder running a PHP application configured in IIS. Here’s the current setup:

  • Site Name: Original Website
  • PHP Manager > PHP Version: 7.0
  • Bindings: * on ports 80 and 443
  • Handler Mappings: First handler is PHPv7.0 using FastCGI

Now, I want to run the same application folder using PHP 8, accessible via a different domain (e.g., php8.example.com.local). The goal is to test the app on PHP 8 while keeping the original running on PHP 7.0.

Here’s what I tried:

Created a new IIS website (PHP 8 Website) pointing to the same folder.

Set bindings to only php8.example.com.local.

Changed the PHP version to 8 in PHP Manager for the new site.

When I change the PHP version in the new site, the original site also switches to PHP 8 (and vice versa). It seems the PHP version setting is global, even though they are separate sites.

I also tried modifying Handler Mappings at the site level to switch only the PHP 8 Website to use PHPv8.0, but that also affects the original site.

How can I configure IIS to serve the same application folder using two different PHP versions, based on the domain name?

Catching errors of model in controller method

I have a controller method which I am using to change the status of the row data in the database. But I forget to mention status field in the model file. So the status was not changing in the database. When I added status attribute in the model file, then only I can change the status of the table data.

use AppHttpControllersController;
use AppModelsAdminServicesBundle;
class BundleController extends Controller
{

    public function changeStatus($id)
      {
        try 
        {
            $bundle = Bundle::find($id);
            $bundle->update(['status' => false]);
            return redirect()->route('admin_bundle.index');
        } catch (Exception $exception) 
        {
            return response()->json(['status'=>'error', 'error'=> $exception->getMessage()]);        
        }
      }
}

Model file::

class Bundle extends Model
{
    protected $fillable = [
        'name', 'description', 'remarks', 'image_path', 'status'
    ];
}

I want to know that although I have kept try catch block in my controller method but still the error was not caught in the controller. How to catch such errors like missing attributes in the model?

php_sqlsrv.dll and php_pdo_sqlsrv.dll missing error

I am using PHP version 8.2.12 for DB am using SQL Server.

I am doing a project in laravel, but it shows

Unable to load dynamic library ‘php_sqlsrv.dll

Unable to load dynamic library ‘php_pdo_sqlsrv.dll

I tried to download the dll file from MS site, but in zip it doesn’t have these dll files, instead it has dll file with some numbers.

Please help me out to fix this error.
Is there any web site to download required dll files?

Past answers posted on site, were not having that dll files in zip.

Livewire update reload the dom

So I loop through user notifications like so, in my Livewire Volt component:

#[Computed]
public function notifications()
{
    return auth()->user()->fresh()->unreadNotifications;
}

Then in blade:

@forelse($this->notifications as $notification)
    //Display notifications
@empty
    No notifications
@endforelse

I have a little x icon to mark a notification as read:

markAsRead('{{ $notification->id }}')

public function markAsRead(string $notificationId): void
{
    auth()->user()->unreadNotifications()
        ->where('id', $notificationId)
        ->update(['read_at' => now()]);
}

Everything works. However, after the last notification has been marked as read, the text “No notifications” does not display. I first need a refresh. I’m trying to understand why I cannot get this to work.

Things I’ve tried:

public function markAsRead(string $notificationId): void
{
    auth()->user()->unreadNotifications()
        ->where('id', $notificationId)
        ->update(['read_at' => now()]);

    $this->dispatch('notificationsUpdated'); (or $this->dispatch('$refresh');)
}

And in the volt component:

protected $listeners = ['notificationsUpdated' => '$refresh'];

Also tried this instead:

public array $notifications = [];

public function mount()
{
    $this->loadNotifications();
}

public function loadNotifications()
{
    $this->notifications = auth()->user()->unreadNotifications;
}

public function markAsRead(string $notificationId): void
{
    auth()->user()->unreadNotifications()
        ->where('id', $notificationId)
        ->update(['read_at' => now()]);

    $this->loadNotifications();
}

Lastly I’ve tried:

public function loadNotifications()
{
    $this->notifications = auth()->user()->fresh()->unreadNotifications;
}

Thinking this would reload a fresh user instance or something.

But the same “issue” keeps happening. I don’t want to show the user an empty block once the last notification has been marked as read, but I want it to show directly “No notifications” as stated in the @empty of the @forelse.

First and foremost I want to understand why this does not work. Any solution is of course a bonus.

How to safely override Laravel’s CacheManager to support tenant-aware cache in Stancl Tenancy?

I’m using the stancl/tenancy package in a Laravel v12 application and need to apply tenant-specific scoping to cached values. By default, the package overrides Laravel’s CacheManager to apply tags() based on the tenant ID.

However, this approach crashes when using cache drivers like database that don’t support tagging, throwing:

BadMethodCallException: This cache store does not support tagging.

I tried overriding the CacheManager using app()->extend('cache', ...) in my service provider, but it gets initialized before tenancy is bootstrapped, making tenant() return null, which leads to:

Call to a member function getTenantKey() on null

What I need:

  • A reliable way to override or wrap Laravel’s cache manager to add tenant-based scoping only when a tenant is resolved, and only when the store supports tagging.
  • A fallback solution for stores that do not support tagging (e.g., prefixing the cache key manually).

What’s the best approach to achieve this without breaking Laravel’s cache system or the tenancy lifecycle?

Any guidance or best practices would be greatly appreciated.

I created a custom TenantCacheManager that checks if the underlying store supports tags (supportsTags()) and falls back to manually prefixing the cache key when it doesn’t. I expected this to allow seamless tenant-specific cache usage without errors, regardless of the store driver.

However, the custom manager was still instantiated too early, before the tenant was resolved, causing tenant() to return null and crash. I also attempted to conditionally override the binding inside the service provider, but it was too late or ineffective.

XDebug & Netbeans – Works on some projects but not on others

Wondering if anyone can explain this. I have Netbeans 23, using XDebug 3. I find that it works on some of my projects but not on others. What I mean by that is when you hit “Run” (F5) on the projects that it works in the status bar you can see “Connected” and it launches the home page of the project (localhost).

On the ones that don’t work it sits there “Waiting for connection”. I’ve checked all of the proxy settings and there’s nothing different… but clearly something is different.

Anyone had this issue and been able to work out the problem? Running PHP 8.3.14 with WAMP Server.

Flatten JSON array with multiple items – how to fit to a single csv cell?

I must get some data via API using curl and save it to a CSV file. Example JSON data set I’m getting when connected via API:

{
  "id": 24598942,
  "created_at": "2021-08-16T15:59:25.345+01:00",
  "success": true,
  "payment_amount": 90,
  "invoice_ids": [
    1646569091
  ],
  "ref_num": "2858",
  "payment_method": "BACS"
}

My PHP code:

$url = 'https://example.com/?page='.$x;

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', $auth_key_here));
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$query = curl_exec($curl);
curl_close($curl);

$decoded = json_decode($data, true);
    
if ($x == 1) {
    $fp = fopen($csv, 'w');
    fputcsv($fp, array_keys($decoded[0]));
    fclose($fp);
}
    
$fp2 = fopen($csv, 'a');
    
foreach ($decoded as $fields) {
    fputcsv($fp2, array_flatten($fields));
    $row_count++;
}
fclose($fp2);

function array_flatten($nonFlat) {
    $flat = array();
    foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($nonFlat)) as $k=>$v) {
        $flat[$k] = $v;
    }
    return $flat;
}

This gives me “invoice_ids” array flatten so I can see actual data in CSV file rather than “Array” word. But some records contain multiple invoice ids in array:

{
  "id": 21016112,
  "created_at": "2020-08-17T16:00:55.552+01:00",
  "success": true,
  "payment_amount": 90,
  "invoice_ids": [
    1646540900,
    1646277088
  ],
  "ref_num": "ZN905TNVCNGQY",
  "payment_method": "Credit Card"
}

This messes up CSV file by moving some data into the wrong columns, as depicted here:
csv file

How to alter the PHP code so the flat array with multiple invoice ids fit to a single column in CSV file?

How to monitor db connections using classes/db/DbPDO.php

I am running into the problem where there are too many max_user_connections causing 500 errors. Since being on a shared server, these cannot be increased. I’m running Prestashop and I’m trying to find what method or functionality is causing this issue.

How can I monitor which routines are using classes/db/DbPDO.php?

*ERROR*     v1.7.8.11   2025/07/19 - 00:18:23: Link to database cannot be established: SQLSTATE[42000] [1203] User XXXXX already has more than &#039;max_user_connections&#039; active connections at line 137 in file classes/db/DbPDO.php

I have contacted the server provider and they unfortunately cannot help me with this issue.

Windows 11: Apache, php and postgreSQL installed, phppgadmin doesn’t work [closed]

I installed Apache 2.4 via the “Apache Lounge” link (i.e. no XAMPP or WAMP), PostgreSQL 17.5 via the EDB installer, and php 8.4.10 from the php.net.

Apache and PHP work fine, i also successfully ported a database dump from ny linux system and verified that PsogreSQL is working correctly (using psql.

Apache is located in C:Apache24, php is in C:php84, and postgresql is in C:Program FilesPostgreSQL

In php.ini I have the lines

extension=pdo_pgsql
extension=pgsql

I then installed phpPgAdmin 7.13.0 from the official GitHub repository and put the extracted folders under C:Apache24htdocs.

I created a file phppgadmin.conf in C:Apache24confextra with the contents

Alias /phppgadmin "C:/Apache24/htdocs/phppgadmin"
<Directory "C:/Apache24/htdocs/phppgadmin">
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

Then I added C:Apache24bin;C:php84;C:Program FilesPostgreSQL17bin to the PATH environment variable.

When i point my browser at http://localhost/phppgadmin i get a page with the contents

Your PHP installation does not support the pgsql, mbstring modules. You will need to install, enable, or compile them to use phpPgAdmin.

How can i make PHP “support the pgsql, mbstring modules”, so that i can run phppgadmin, and access my postgresql DB from php scripts?

EDIT: in C:Apache24htdocsphppgadminconfconfig.inc.php i have these lines (amongst many others):

$conf['servers'][0]['desc'] = 'PostgreSQL';
$conf['servers'][0]['host'] = 'localhost';
$conf['servers'][0]['port'] = 5432;

$conf['servers'][0]['defaultdb'] = 'postgres';
$conf['servers'][0]['username'] = 'postgres';
$conf['servers'][0]['password'] = 'MyPGPassword';