Jump to content

PHP and Linux file names


mesh2005

Recommended Posts

I have a PHP script that takes an input from the user and writes a file with the same name as the input

for example, if the user enters: this is a test a file name is created with the name this is a test.php

The problem happens when the user enters a value that contains characters not allowed in filenames on Linux distributions, how do I convert the value to make sure that it contains only allowed chars?

 

Thank you

Link to comment
https://forums.phpfreaks.com/topic/101465-php-and-linux-file-names/
Share on other sites

characters, as in alphanumeric? you can do a check like:

 

<?php
$string = "this is text";

if(ctype_alnum($string)){
echo "Alphanumeric";
}else {
echo "Not alphanumeric, doing a check...";
$n_string = str_replace(" ",NULL, $string);

if(ctype_alnum($n_string)){
	echo "<br><br>Replacing spaces caused the string to be alphanumeric";
}else {
	echo "<br><br>Replacing spaces caused the string to still be non-alphanumeric!";
}
}
?>

 

Thanks guys for your replies. I wanna allow other symbols too like +/- and all possible symbols that won't cause a problem. I usually get errors when the filename is encoded in way that is not understood by Linux, for example the character (’), this character appears as unknown code in the filename, any help?

Use regular expression:

<?php
$user_input = "this is a test";

if(preg_match("/[a-z0-9 \+_\.-]?/", $user_input)) {
  $file_name = $user_input . ".php";
}
else {
  echo "Invalid characters in filename";
}
?>

 

This will take the $user_input and make sure it only consist of a-z, 0-9, '+', '.', '-' and '_' and has a minimum length of 1.

 

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.