There’s nothing wrong with the form and form processing code being on the same page. What is a problem is directly using portions of the current url to do so, since it could contain html/css/javascript that would allow cross site scripting if you output it on a web page, without applying htmlentities() to it.
In html5, you can leave the action=’…’ attribute out of the form tag and the browser will submit to the same page.
To get an array of just the file’s filenames, use some of php’s array functions to operate on the data as a set -
$pattern = "../img/*.*";
$files = glob($pattern);
// break the filename into its various parts - i.e. apply the pathinfo() function to each element in the $files array
$files = array_map('pathinfo',$files);
// get an array of just the filename column values
$filenames = array_column($files,'filename');
// examine the result
echo '<pre>'; print_r($filenames);
This will give you an array of the permitted filename values. You should use a foreach(){} loop when looping over an array. You would use this same array with an in_array() statement to validate that the submitted form value is one of the permitted choices.
In your code posted above, if the use of strtolower() is because there can be ‘random’ letter cases used in the files, you should lowercase them when the files are uploaded to the server. If you are filtering the files using the jpg and jpeg extensions because there are other extensions present or files other than background images are in the folder, if possible, just store the background images in the folder. The glob() function would then return only the permitted background images.
If you cannot do the above, you can filter the $files array by writing a call-back function and using array_filter(). The call-back function would strtolower() the ‘extension’ element and use in_array() to identify array entries to keep. This would look like -
// call-back function to filter by extension
function _filter_ext($var)
{
$ext = ['jpg','jpeg'];
return in_array(strtolower($var['extension']),$ext);
}
// filter the array by the extension value
$files = array_filter($files, '_filter_ext');
The above would be used before the array_column() statement.
Other than trimming data, so that you can detect if all white-space characters were entered, you should NOT modify user submitted data. You validate that it is either an expected format or value, then safely use it in whatever context it is being used in. In an sql query context, use a prepared query to supply the data when the query is executed. In a html context, use htmlentities() when outputting it onto a web page/email.