I am not entirely sure what is causing the issue but seems to be related to the server setup.
I tried creating a fresh server in VBox with a fresh install of Ubuntu. The issue still presisted.
However, when I installed XAMPP on my Windows host machine and run the code from there, the issue is not there.
The only thing I can think of that might have caused it could be an incompatible PHP version because XAMPP PHP version is 8.2.12 and Ubuntu's version is 8.3.6.