使用输出作为文件夹名称的最佳PHP加密/编码方法


Best PHP encryption/encoding method to use the output as folder name

我有一些小于18个字符的文本。我想用这个文本作为目录名创建一个目录。有时文本将具有特殊字符,如, í, ó, ú, ü, ñ,¿,′,?因此它不能用作目录名

因此,我认为最好对测试进行加密或编码,以便它可以在文件夹名称

中使用

这是最好的加密/编码方法为我的收购?

Thanks in advance

我认为你可以使用base64编码,如果你关心重新提取原始文件夹名称:

base64_encode('Folder Name');   // results: Rm9sZGVyIE5hbWU=

如果您不想获得原始名称,您可以使用MD5:

md5('Folder Name');   // results: d89dbf99916d31a7870474d44d481ffa

如果你想使用散列,只需选择md5(),因为它非常快,而且你不需要任何加密强的东西。

或者你可以很容易地清理字符串,这是我的方法:

/**
 * Sanitizes a filename, replacing whitespace with dashes and transforming the string to lowercase.
 *
 * Removes special characters that are illegal in filenames on certain operating systems and special characters
 * requiring special escaping to manipulate at the command line. Replaces spaces and consecutive dashes with a single
 * dash. Trims period, dash und underscore from beginning and end of filename.
 *
 * @param string $filename
 *   The filename to be sanitized.
 * @return string
 *   The sanitized filename.
 * @throws 'InvalidArgumentException
 *   If <var>$filename</var> is invalid.
 */
final public static function sanitizeFilename($filename) {
  if (empty($filename)) {
    throw new 'InvalidArgumentException("A file's name cannot be empty.");
  }
  // Remove characters which aren't allowed in filenames.
  $filename = str_replace([ "?", "[", "]", "/", "''", "=", "<", ">", ":", ";", ",", "'", '"', "&", "$", "#", "*", "(", ")", "|", "~" ], "", $filename);
  // Replace whitespace characters with dashes.
  $filename = preg_replace("/['s-]+/", "-", $filename);
  // Remove characters which aren't allowed at the beginning and end of a filename.
  $filename = trim($filename, ".-_");
  // Always lowercase all filenames for better compatibility.
  return mb_strtolower($filename);
}