Performance with large API endpoint files [closed]

First some background. I am creating a RESTful API using PHP to access a MySQL database where I have stored a bunch of information I need to export to other services (3rd party software). The database isn’t especially large, and the MySQL queries aren’t intensive either.

Now here is my question: Does the size of my PHP file affect the performance of the API, in regards to both response time and server runtime?

I do not have a ton of experience with this, so I want to make sure I am not doing something wrong by creating a massive endpoint file instead of splitting my endpoint up into separate files.

Specifically I want to know at what file size does this start creating concerns, if at all.

I tried searching this topic up, but didn’t find any information on the correlation (or lack thereof) of file size to performance in regards to APIs.

How do I make PHP mail form functional? [closed]

I have like two files, both are in the same and correct folder:

index.php and contactform.php

The form appears, but I want to make if fully functional, so it actually sends an email to my email address. Can someone review the code and tell me what have I done wrong and how can I make it work, so It sends an email to [email protected]?

index.php:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap" rel="stylesheet">
    <link="stylesheet" href="index.css"> <!-- zde doplnit odkaz na CSSka -->    
</head>
<body>
    <p>SEND E-MAIL</p>  
    <form class="contact-form" action="contactform.php" method="post">
        <input type="text" name="name" placeholder="Full name">
        <input type="text" name="mail" placeholder="Your-email">
        <input type="text" name="subject" placeholder="Subject">
        <textarea name="message" placeholder="Message"></textarea>
        <button type="submit" name="submit">SEND MAIL</button>
    </form>
</body>
</html>

contactform.php:

<?php

if (isset($_POST['submit'])) {
    $name = $_POST['name'];
    $subject = $_POST['subject'];
    $mailFrom = $_POST['mail'];
    $message = $_POST['message'];

    $mailTo = "[email protected]";
    $headers = "From: ".$mailFrom;
    $txt = "You have received an e-mail from ".$name.".nn".$message;


    mail($mailTo, $subject, $txt, $headers);
    header("Location: index.php?mailsend")
}

?>

Can you get CakePHP 4 to return JSON error responses automatically when writing an API?

CakePHP 4.x

We have an application which consists of a frontend web app (used by customers through a browser) and an API for some backend operations which is integrated with our other systems.

The code is in the expected places i.e. src/Controller/ has the Controller’s for the web app requests. In src/Controller/Api/V1/ we have our API.

The problem is if we get some error with the API such as a 404, CakePHP seems to automatically render a HTML error page.

My limited understanding of this is that in config/app.php you have this by default

'exceptionRenderer' => 'CakeErrorExceptionRenderer',

You can replace that with your own

'exceptionRenderer' => AppErrorApiErrorRenderer::class,

Then have your own custom class for it.

<?php
 // src/Error/ApiErrorRenderer.php
declare(strict_types=1);

namespace AppError;

use CakeErrorRendererWebExceptionRenderer;
use CakeHttpResponse;

class ApiErrorRenderer extends WebExceptionRenderer
{
    /**
     * Render the exception.
     *
     * @return CakeHttpResponse The response object.
     */
    public function render(): Response
    {
        $response = parent::render();

        // Set the content type to application/json for all API errors
        return $response->withType('application/json');
    }
}

The problem is that now returns a JSON response for all errors, including the 404’s for the web app. So it doesn’t render as HTML in the browser for customers, though the API now has JSON responses for it’s errors.

In phpunit it’s common to have tests that include checks such as $this->assertContentType('application/json'); before testing responses – which might include errors – from an API.

Without such changes above those tests fail because HTML rather than JSON is returned. But with the fix in place, that breaks the web app for customers.

This seems like something that should be simple and included in the framework as it’s so obvious that in both of those 2 different environments (web app vs API) you’d typically be using HTML and JSON responses respectively.

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.