r/PHPhelp • u/Suitable-Fuel8913 • Feb 13 '26
Beginner PHP form project – looking for feedback on structure and best practices
Olá a todos,
Estou aprendendo PHP e recentemente construí meu primeiro projeto baseado em formulários. Comecei isso depois de receber a recomendação de praticar criando algo simples, mas funcional.
Como ainda sou iniciante, usei ChatGPT como auxílio de aprendizado sempre que ficava preso ou não tinha certeza de como implementar algo. No entanto, certifiquei-me de entender o código antes de usá-lo — meu objetivo é realmente aprender, não apenas copiar e colar.
Agradeceria muito por feedbacks e sugestões, especialmente em relação a:
- Estrutura e organização do código
- Validação e sanitização
- Boas práticas de segurança
- Legibilidade e manutenibilidade
- O que devo focar em melhorar como iniciante
Estou ciente de que algumas partes podem não seguir as melhores práticas ainda, então qualquer crítica construtiva é bem-vinda.
Agradeço antecipadamente pelo seu tempo e ajuda!
https://github.com/ronaldomatheus364-collab?tab=repositories
5
u/No_Astronomer9508 Feb 13 '26
Link does not work -> 404 Error.
2
u/Big-Dragonfly-3700 Feb 14 '26
The code for any operation should be on the same page. This will allow you to display any user/validation errors, re-display the form, and repopulate appropriate fields with the submitted form data, so that the user just needs to correct any errors and can resubmit the form, without needing to navigate around on the site and keep filling in the form data upon any error(s).
The code for any page should be laid out in this general order -
A post method form should be used when performing an action on the server, such as creating/inserting/deleting database data, sending an email, ... A get method form/link(s) should be used when determining what will be displayed on a page.
Post method form processing code should -
Forget about sanitizing data. Except for trimming data (as stated above), do not modify data and use it, as this changes the meaning of the data. If data is valid, use it. If it is not, let the user know what was wrong with it, let them correct the problem, and resubmit the data.
Use prepared database queries to prevent any sql special characters in a value from being able to break the sql query syntax.
For database columns that must be unique, these columns need to be defined as a unique index. You would then have exception try/catch logic (php 8+ uses exceptions for database errors by default) for the execution of any query involving a unique index. The catch logic would test for a unique index error (number) and setup a message for the user (add it to the array holding the user/validation errors) letting them know if/what duplicate data was submitted.
1
u/cursingcucumber Feb 14 '26
Stop using ChatGPT as your primary source and follow a tutorial, any tutorial.
But before coding anything in any language for the web, you need to understand the basics of HTTP. Things like URLs (paths, query parameters, fragment, escaping), request methods like GET and POST, data formats like form-urlencoded and JSON.
Sites like MDN offer great help with that.
Only then it makes sense to dive into any programming language for the web like PHP.
1
u/-PM_me_your_recipes Feb 14 '26
Since it is a beginner test, not much to comment on.
1
u/equilni Feb 14 '26 edited Feb 14 '26
This is really beginner level, so it's difficult to note on structure YET. Best practices though...
a)
HTML.htmlcould really be namedindex.html. This is the starting file that the web server should be detecting. This could be index.html or index.php (when you get here later). If you are using Apache (XAMPP, LAMP or similar), this is set per the (docs)Your
href="http://localhost/"in the card.php likely fails, unless your webserver is set to accept html.htmlb) Forms like this should be POST vs GET requests. I linked some information for you to reference what this means.
c) This can be reduced via the Null coalescing operator - ??
Then when you call it in the template, use
htmlspecialcharshtmlspecialchars is notated later because we are deferring it to when it's needed - in the template.
d) You want to start validating the input. You should not trust this information until it passes your checks. This is in addition to just checking if the data exists.
So for your email, PHP have
filter_varfunction with an email validation example here.And this could expand further - say you don't accept reddit email addresses or only want reddit.com emails.
Runnable example here
Also note, I am returning early in each block instead of doing if/elseif/if.
e) With the above, you want to learn to collect or return the errors back to the user.
So with the above, this could be an array of data with the matching field and errors if any. Think
$errors = ['birthDate' => 'Date is not an accepted format', 'email' => 'Email not valid']f) For structure, there are a few considerations later on in your journey:
?page=register) or clean urls (/register). This gets filtered through thepublic/index.phpExample folder structure:
/public/index.php could look like:
EDIT - wth mobile reddit???
2
u/[deleted] Feb 14 '26
[removed] — view removed comment