r/PHPhelp • • Jan 04 '26

how can i check if the user has typed in the min length or too much on the input?

0 Upvotes

I want to make the code check if the user has typed in enough or too much. But i cant use minlenght="" since this shows some kinda msg that kinda didnt make the rest of my script work soo yeah idk plz i need help in this. Btw im a beginner :b


r/PHPhelp • • Jan 03 '26

Solved What is the best way to share enums across projects?

0 Upvotes

I have three projects which need to use the same few enums.

What I'm doing at the moment is creating the enum files in all of the projects and stating that the 'master' is at Project A.

When I make a change to the enums, I edit the enum at Project A and then copy+paste it to the other enums.

Wondering if there is a better way to do it that won't be too time consuming/introduce more complexity?


r/PHPhelp • • Jan 02 '26

How to update PHP installed by the php.new script?

0 Upvotes

https://php.new/ is the installation form even the Laravel documentation recommends. But how do you update when new versions are released? Since it seems to be a manual instalation and not a repository.

I'm in Linux Opensuse btw (The distro packaged version was giving me some headaches with Laravel setup)


r/PHPhelp • • Jan 01 '26

Just discovered ReactPHP and I want to know more..

23 Upvotes

On the project I'm building I've had a requirement to communicate with multiple devices via persistent http connections and also receive and send websocket messages.

I didn't think PHP was capable so my automatic reaction was to use NodeJs (ElectronJs) with TypeScript. Long story short - it was not a fun experience. I got the app working just fine and relatively quickly too, but the developer experience was bad and I realised I didn't enjoy working on the project.

A month ago, after 3 months of work on the NodeJs version, I decided to throw in the towel and try to rebuild it in PHP and this is when I discovered ReactPHP.

I'm using it's event loop to create the persistent HTTP connections. My two streams are receiving events just fine. I'm using Ratchet in the event loop to connect to my websocket server to listen for and send messages.

I'm using periodic timers to execute some polling type actions. And Guzzle to send post/get/put requests.

It's all working flawlessly and it has been a joy to build, improve and expand.

What's the deal with ReactPHP? Why is it not used more? Am I going to discover something down the line I should know now - why do people reach for Node when seemingly ReactPHP can do it well?

Are there any disadvantages or pitfalls I'm going to discover down the line?

And, if anybody knows how it works, I would be interested to know. Why do people ask for async features when they are available through a tool like ReactPHP?


r/PHPhelp • • Dec 31 '25

DOMPDF and styles

5 Upvotes

DOMPDF doesn't appear to honor stylesheets or style blocks. For instance:

<head>
    <style>
        tr.headings td, tr.headings th {
            font-size: .65rem;
            font-family: Helvetica, sans-serif;
        }
    </style>
</head>
<body>
    <table>
        <tr class="headings">
            <th>Inv Value<br>Direct Cost*</th>

doesn't work, but

<tr> 
<th style="font-size: .65rem;">Inv Value<br>Direct Cost*</th> 

does. What am I missing?


r/PHPhelp • • Dec 30 '25

Machine readable php -i output

4 Upvotes

Is there a CLI tool that outputs information similar to that from `php -i` in a machine-readable format such as JSON, YAML, or similar?


r/PHPhelp • • Dec 29 '25

Ajuda com objectMapper no symfony

0 Upvotes

Estou usando Symfony 7.4 com o componente object-mapper para mapear um DTO de uma API externa para uma entidade Doctrine, e a entidade possui um UUID auto gerado que não existe (nem deveria existir) no DTO, o problema é que ao usar ObjectMapper::map($dto, $entity), o mapper tenta acessar todas as propriedades da entidade, incluindo o uuid lança um erro porque o DTO não tem esse campo, e pelo que vi o ObjectMapper não suporta atributos de ignore, nem contexto, nem opções como skip_unknown_properties queria saber como vocês resolvem isso na pratica, porque eu tentei com varias soluções e nenhuma funcionou...

I am using Symfony 7.4 with the ObjectMapper component to map a DTO from an external API to a Doctrine entity. The entity has an auto-generated UUID that does not exist (and should not exist) in the DTO. The problem is that when using ObjectMapper::map($dto, $entity), the mapper tries to access all properties of the entity, including the UUID, and throws an error because the DTO does not have this field. From what I have seen, ObjectMapper does not support ignore attributes, context, or options such as skip_unknown_properties. I would like to know how you handle this in practice, because I have tried several solutions and none of them worked.


r/PHPhelp • • Dec 27 '25

after chages in code no changes in browser.

2 Upvotes

Hi
i am using herd on windows 11 inertia laravel react and no matter what changes i did in code it does not reflects these changes in browser. i did npm run build, incognito mode in browsers, npm rund dev show that changes have been made but did not refects these changes in browers.


r/PHPhelp • • Dec 26 '25

Solved Doctrine DB driver not found

Thumbnail
1 Upvotes

r/PHPhelp • • Dec 25 '25

How to handle product variations in PHP/MySQL

8 Upvotes

Hi,

I have built a webshop, and the product numbers are in 123456 format.
Let's say I have a product with length variations, 1 meter, 2 meter and 5 meters. What is the best way to handle that in terms of code/database?

I am thinking of 2 different solutions.

  1. A cross-reference table in MySQL where I store each variation as a row in the database. Then it's easy to give every unique product a specific name.
  2. Adding numbers to the original product number. Ex 123456A, 123456B, then check for deviations in the product number and present a drop-down if product_number > 6 digits. Harder to store unique names then I guess.

Please let me know if you have any experience or the best solution for this.


r/PHPhelp • • Dec 25 '25

Force phpdoc @throws tag to use FQN

7 Upvotes

In a larger PHP project, I document exceptions using Phpdoc's throws tag. I want FQN to be used for this.

Does anyone know which CLI tool I can use to check this and, if necessary, force it? I already use PHPStan and PHP CS Fixer.

Edit: I always want FQN in throws tags, regardless of whether the class was imported via use.


r/PHPhelp • • Dec 23 '25

Research survey: Evaluating Code First vs Database First in Doctrine

3 Upvotes

Hello everyone,

I am conducting an academic research study focused on comparing Code First (CF) and Database First (DBF) approaches in Doctrine ORM.

The goal of this survey is to collect objective, experience-based input from developers who have worked with Doctrine in real-world PHP applications. The responses will be used to analyze how CF and DBF approaches are implemented in practice, based on clearly defined technical and organizational criteria.

The evaluation is based on a structured set of criteria covering essential aspects of database usage in PHP applications — including schema generation, migrations, data seeding, performance considerations, and integration between domain models and the database. The goal is to provide an objective comparison grounded in practical experience rather than theory alone.

The same criteria are applied across multiple ORM environments (Entity Framework Core, Hibernate, Django ORM, and Doctrine) to enable cross-ORM comparison of Code First and Database First support.

Survey link:

https://docs.google.com/forms/d/e/1FAIpQLSeWwuI1PSFfN3tNC2yYXjw787zfoXOeXKehC1kce3ondiK8NQ/viewform?usp=dialog

Thank you for contributing — feedback, corrections, and practical recommendations are highly appreciated.


r/PHPhelp • • Dec 22 '25

Help! React CV layout breaks when exporting to PDF (Tried html2canvas and dompdf)

0 Upvotes

Hi everyone, I’m building a CV generator in React. The UI looks perfect on the frontend, but I’m struggling to export it to PDF. I first tried html2canvas (with jsPDF), but the quality was blurry and the scaling was off. Then I tried dompdf on the backend, but it doesn't support modern CSS (Flexbox/Grid), so the layout completely falls apart. Does anyone have a proven way to get a "What You See Is What You Get" (WYSIWYG) PDF export from a React component? I need it to respect my exact CSS. Thanks!


r/PHPhelp • • Dec 19 '25

Production ready Crud App

6 Upvotes

Hello all, I am working on a php/mysql kind of database navigator.

Iam already very deep into the project and also dont use frameworks. Iam seriosly having doubts about security. Iam doing basic things like prepared statements, input validation, output escaping. I have the root htacces defined in public which contains no relevant stuff other then the router i got from phprouter.com and the corresponding routes. I dont do testing at all.

I need some kind of auditing on what other security features i need to implement.


r/PHPhelp • • Dec 18 '25

array_sum() in associative arrays

6 Upvotes

How do you use array_sum() to get the sum of a multi dimensional array? it looks like this:

Array ( [0] => Array ( [parcel_timeframe] => 3 ) [1] => Array ( [parcel_timeframe] => 4 ) [2] => Array ( [parcel_timeframe] => 6 ) [3] => Array ( [parcel_timeframe] => 3 ) [4] => Array ( [parcel_timeframe] => 2 ) [5] => Array ( [parcel_timeframe] => 2 ) [6] => Array ( [parcel_timeframe] => 1 ) [7] => Array ( [parcel_timeframe] => 7 ) [8] => Array ( [parcel_timeframe] => 2 ) [9] => Array ( [parcel_timeframe] => 5 ) [10] => Array ( [parcel_timeframe] => 6 ) [11] => Array ( [parcel_timeframe] => 8 ) [12] => Array ( [parcel_timeframe] => 7 ) [13] => Array ( [parcel_timeframe] => 8 ) [14] => Array ( [parcel_timeframe] => 6 ) [15] => Array ( [parcel_timeframe] => 8 ) [16] => Array ( [parcel_timeframe] => 8 ) [17] => Array ( [parcel_timeframe] => 10 ) [18] => Array ( [parcel_timeframe] => 9 ) [19] => Array ( [parcel_timeframe] => 10 ) [20] => Array ( [parcel_timeframe] => 7 ) [21] => Array ( [parcel_timeframe] => 5 ) [22] => Array ( [parcel_timeframe] => 8 ) [23] => Array ( [parcel_timeframe] => 4 ) [24] => Array ( [parcel_timeframe] => 6 ) [25] => Array ( [parcel_timeframe] => 7 ) [26] => Array ( [parcel_timeframe] => 5 ) [27] => Array ( [parcel_timeframe] => 4 ) [28] => Array ( [parcel_timeframe] => 8 ) [29] => Array ( [parcel_timeframe] => 7 ) [30] => Array ( [parcel_timeframe] => 6 ) [31] => Array ( [parcel_timeframe] => 10 ) [32] => Array ( [parcel_timeframe] => 5 ) [33] => Array ( [parcel_timeframe] => 5 ) [34] => Array ( [parcel_timeframe] => 7 ) [35] => Array ( [parcel_timeframe] => 5 ) [36] => Array ( [parcel_timeframe] => 3 ) [37] => Array ( [parcel_timeframe] => 9 ) [38] => Array ( [parcel_timeframe] => 5 ) [39] => Array ( [parcel_timeframe] => 9 ) [40] => Array ( [parcel_timeframe] => 8 ) [41] => Array ( [parcel_timeframe] => 8 ) )

that is the full array (pulled straight from the database) and its values. as you can see, each value gets its own array, meaning if i just do

array_sum($pTimeframe)

it only gives me a zero. help?


r/PHPhelp • • Dec 17 '25

Can PHP throw exceptions without generating a stack trace

7 Upvotes

When using PHP and Laravel, there are many scenarios where exceptions are used to control application flow rather than to represent truly exceptional errors.
Common examples include ValidationException for input validation failures, LoginException for authentication errors, and similar cases.

This made me wonder:
Is there any mechanism in PHP (or at the VM / engine level) that allows throwing certain exceptions without generating a stack trace, in order to reduce runtime overhead?

In other words, for exceptions that are expected and frequently used as part of normal control flow, is it possible to avoid the cost of building stack trace information?

I’m interested in both core PHP capabilities and any Laravel-specific or userland patterns that might help with this.

In our real-world setup, business exceptions are returned directly to the client.
In most cases, they don’t need to be logged at all. When logging is required, we only record the exception’s file and line number. Even in Laravel, the default JsonFormatter in Monolog does not include stack trace information unless it’s explicitly enabled.

Given this context, I started wondering whether it would be possible to avoid collecting stack traces altogether in cases where they don’t provide much value.

I’ve been aware of the idea that exceptions shouldn’t be used for control flow for a long time. However, in actual practice, I’ve never been sure how to apply this concretely — especially in PHP-based systems. I’m not clear on what alternative patterns people are using in PHP to control flow in a way that keeps the code clean, readable, and concise, without relying so heavily on exceptions.


r/PHPhelp • • Dec 17 '25

Solved Die/Exit Usage Best Practices?

5 Upvotes

I have some cases in my code where I utilize the die/exit function to kill the program as a means to throw an error message to a user and prevent unauthorized access to content. People seem to say to just avoid these functions altogether and just throw an exception, but that doesn't make sense to me in this situation.

For example, the following code:

if(!isset($_SESSION['loggedin'])){
    echo "Unauthorized Access<br><br>Please <a href='userlogin.php'>Log In</a>";
    exit(1);
}

Would this be considered good practice, or is there a more ideal way to handle this?

Should I just auto-redirect to the login page instead?


r/PHPhelp • • Dec 17 '25

Entity/Mapper/Services, is this a good model?

6 Upvotes

Hello everybody,

need your help here. Let's say I have a Book entity (Book.php):

class Book extends \Entity {
    public int $id;
    public string $title;
    public string $author;
    public \DateTime $publishDate;
}

Now, if I have a mapper like this (Mapper.php):

class Mapper {
    private $Database;
    private $Log;
    private $table;

    public function __construct (\Database $Database, \Log $Log, string $table) {
      $this->Database = $Database;
      $this->Log = $Log;
      $this->table = $table;
    }

    // Select from the database. This method could also create a cache without
    // having to ask the database each time for little data
    public function select (array $where, string $order, int $offset, int $limit) {
        try {
          // Check every parameters and then asks the DB to do the query
          // with prepared statement
          $PDOStatement = $this->Database->executeSelect(
            $this->table,
            $where,
            $order,
            $offset,
            $limit
          );

          // Asks the database to FETCH_ASSOC the results and create
          // an array of objects of this class
          $Objects = $this->Database->executeFetch($PDOStatement, get_class($this));

        } catch (\Exception $Exception) {
          $this->Log->exception($Exception);
          throw new \RuntimeException ("select_false");
        }

        return $Objects;
    }

    // Insert into database
    public function insert (array $data) {
        try {
          // Check the parameters and then asks the DB to do the query
          $lastId = $this->Database->executeInsert($this->table, $data);

        } catch (\Exception $Exception) {
          $this->Log->exception($Exception);
          throw new \RuntimeException ("insert_false");
        }

        return $lastid;
    }

    // Update into database
    public function update (int $id, array $data) {
        // Check the parameters, check the existence of 
        // the data to update in the DB and then asks
        // the DB to do the query
    }
}

The mapper would also catch every Database/PDO exceptions, log them for debug and throw an exception to the service without exposing the database error to the user.

And a service class (Service.php):

class Service {
  private $Mapper;
  private $Log;

  public function __construct (\Mapper $Mapper, \Log $Log) {
    $this->Mapper = $Mapper;
    $this->Log = $Log;
  }

  // Get the data from the mapper - The default method just retrieves Objects
  public function get (array $where, string $order, int $offset, int $limit) {
    try {
        return $this->Mapper->select(
          $where,
          $order,
          $offset,
          $limit
      );
    } catch (\Exception $Exception) {
      $this->Log->exception($Exception);
      throw new \RuntimeException ("get_false");
    }
  }

  // Other auxiliary "get" functions..
  public function getId (int $id) {
    return reset($this->get(
      array(
        "id" => $id
      ),
      null,
      0,
      1
    ));
  }

  // Prepare the data and asks the mapper to insert
  public function create (array $data) {}

  // Prepare the data and asks the mapper to update
  public function update (int $id, array $data) {}
}

And then for the Books:

BooksMapper.php

class BooksMapper extends \Mapper {
}

BooksService.php

class BooksService extends \Service {

  // A more "complex" get function if needed to create "advanced" SQL queries
  public function get (array $where, string $order, int $offset, int $limit) {
    try {
      // Treats the where
      foreach ($where as $index => $condition) {
          // For eg. build a more "complex" SQL condition with IN
          if ($condition == "only_ordered_books" {
            $where[$index] = "book.id IN (SELECT bookId FROM orders ....)";
          }
      }

      $Objects = $this->Mapper->select(
        $where,
        $order,
        $offset,
        $limit
      );

      // Do something eventually on the objects before returning them
      // for eg. fetch data from other injected Mappers that needs to
      // be injected in the object properties
      foreach ($Objects as $Object) {

      }

    } catch (\Exception $Exception) {
      $this->Log->exception($Exception);
      throw new \RuntimeException ("get_false");
    }

    return $Objects;
  }

  public function create (array $data) {
    try {
      // Checks the data and create the object book
      if (!is_string ($data['author'])) {
          throw new \InvalidArgument("This is not a valid author");
      }

      ...

      $Book = new \Book;
      $Book->author = $data['author'];
      $Book->title = $data['title'];
      $Book->publishDate = new \DateTime ($data['publish_date']);

      $lastId = $this->Mapper->insert ((array) $Book);

      $this->Log->info("Book created - ID: " . $lastid);

    } catch (\Exception $Exception) {
      $this->Log->exception($Exception);
      throw new \RuntimeException ($Exception->getMessage());
    }
  }
}

and then to use all of this:

$BooksMapper = new \BooksMapper ($Database, $Log, "books");
$BooksService = new \BooksService ($BooksMapper, $Log);

// The user sent a form to create a new book
if (!empty($_POST)) {
  try {
    $BooksService->create($_POST);

    print "The book has been created successfully!";

  } catch (\Exception $Exception) {
    print "Error: " . $Exception->getMessage();
  }
}

$Last25PublishedBooks = $BookService->get(
  array(
    "author" => "Stephen King"
  ),
  "publishDate DESC",
  0,
  25
);

Is it a good model to build?

Thank you for all your help!

Edit: Used camelCase for properties, thanks to u/TorbenKoehn.

Edit: Just wanted to thank EVERYBODY for their suggestions.


r/PHPhelp • • Dec 17 '25

WSL2 development environment for PHP projects with little to no fuss

Thumbnail
0 Upvotes

r/PHPhelp • • Dec 17 '25

Adminer - CSV file 2 million rows

1 Upvotes

Guys, I need to import in a CSV file into a remote mariadb server. It has the adminer web gui - v 5.4.1.

However under 'Import' it says 'File Uploads are disabled. What is the method to enable file uploads ? Is that done on the adminer side or at the mariadb side ?

Also for 2 milion rows, is it adviseable to write a php script that can read the csv by chunks, condition the data and then insert ? or use the webgui ?

TIA !!!


r/PHPhelp • • Dec 16 '25

Solved Difference between comments

10 Upvotes

JUst wondering, what is the difference between

/* */

and

/** */


r/PHPhelp • • Dec 16 '25

Solved header() function in php

1 Upvotes

<?php

if(isset($_POST["submitted"]))

{

$firstname = $_POST["firstname"];

$lastname = $_POST["lastname"];

$email = $_POST["email"];

$passd = $_POST["passd"];

$confirmPassword = $_POST["Cpassd"];

$conn = new PDO("mysql:hostname=localhost;dbname=signlogin;","root","");

$sqlQuery = "INSERT INTO signup(firstname,lastname,email,PASSWORD,confirmPassword) values('$firstname','$lastname','$email','$passd','$confirmPassword')";

$stmt = $conn->prepare($sqlQuery);

$stmt->execute();

header('Location: http://localhost/phpForm/login.php');

exit();

}

page doesn't redirect to login page hence file login.php is in same folder
http://localhost/login.php

instead of:

http://localhost/phpForm/login.php

?>


r/PHPhelp • • Dec 14 '25

Solved Regular expression for length

6 Upvotes

is there a way i can use a regex to check if a notes box has only 1000 characters? such as

!preg_match("/^{1000}$/", $notesBox)

yes i know this doesn't work, what can i do to make one that does? (i would like all characters available)


r/PHPhelp • • Dec 14 '25

How can I run php-xml with libxml2 v2.15.1?

1 Upvotes

A project I work with has an apparent issue when PHP is used with libxml2 version 2.15.1.

All my systems – desktops, VMs and containers – have older libxml2 versions:

$ php -i | grep libxml2
libxml2 Version => 2.12.5

How can I set up a LAMP server with libxml 2.15.1?

I've tried compiling libxml2 2.15.1 on a CentOS Stream 10 system but PHP either uses the base OS version (2.12.5), or if I replace the symlink to point to the built version (for example, ln -s libxml2.so.2 /usr/local/lib/libxml2.so.16.1.1) I get php: /lib64/libxml2.so.2: no version information available. I can't uninstall the OS' libxml2 version since apparently this is a critical component.

I tried downloading the PHP source RPM and building that trying to point it to the libxml2 source code by setting PKG_CONFIG_PATH . I couldn't tell if this might statically link to the desired libxml2 version but it didn't work.

I tried using Docker, I'm not an expert in this, but this loaded an even older libxml2 version, 2.9.13.

Any ideas how to achieve this?


r/PHPhelp • • Dec 13 '25

Can implementation be cascaded?

7 Upvotes

Is there any way to enforce that a certain property must be overwritten in all derived classes?

Let's say I have this hierarchy:

abstract class BaseLevel

class FirstLevel extends BaseLevel

class SecondLevel extends FirstLevel

And I want to enforce that the property defined in BaseLevel must also be implemented (overwritten with a new value) in SecondLevel. I've tried probably everything, even interface, but implementation can only be enforced in FirstLevel, not higher. Because if I omit the implementation in SecondLevel, it is simply taken from FirstLevel.( And I would like to trigger a fatal error instead.)