Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

niiwill's avatar

Read file and santize input requst

Hi developers, can you help me?

I have a task to make some logic in the Comments Controller in my Level 10.0 project.

In the task, they gave me a text file with bed words on each new line inside the file, named bad_words.txt.

I should implement logic in the Laravel controller before storing a new comment so that every bad word from the file that exists in the input request that is named comment, to be replaced with stars before storing comments in the database.

I am confused about where in the project should I put that file and how to read it and sanitize the comment before storing it in the database if any word from the file is present in the comment input request.

0 likes
4 replies
Snapey's avatar
Snapey
Best Answer
Level 122

before you save the comment to the database, you can string replace against an array of 'bad words'.

So you have to first read the bad words into an array from the file system. You can use file_get_contents() to read the file to a string then use explode() to create an array, splitting on the new line.

then you can use str_replace (https://www.php.net/manual/en/function.str-replace.php)

The first parameter is the array of bad words, the second is the replacement (the stars), and the third parameter is the comment from the form.

I think thats enough coaching for what is an assignment

(Bear in mind that you might need to think about upper and lowercase letters)

1 like
niiwill's avatar

@Snapey Great, thank you for your answer, but what makes me confused still, is where I should put that bad_words.txt file in the root of the Laravel project like .env and etc file or somewhere else. How to load it with file_get_content how to get the path?

Snapey's avatar

@niiwill you could put it in the storage folder and use storage_path('bad_words.txt')

niiwill's avatar

@Snapey But files in the storage folder are in git ignore, so I can not submit them on GitHub, is it good to change gitignore for that file?

Please or to participate in this conversation.