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
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!";
}
}
?>

 

Link to comment
Share on other sites

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?

Link to comment
Share on other sites

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.

 

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.