Php 用字符串做任何事情

Php 用字符串做任何事情,php,Php,我正在制作一个php脚本,它可以打开用户的目录并在文件中写入内容。 问题在目录中。目录名不是固定的,它每次在名称“dir+一些随机数”中都会更改 有没有办法做这样的东西 我需要“任何”功能 当然可以。。。首先检查您想要的目录是否存在。如果没有,创建它 <?php // check if dir exists, if not create it if(!is_dir("files/dir".anything()."/other..")) mkdir("file

我正在制作一个php脚本,它可以打开用户的目录并在文件中写入内容。 问题在目录中。目录名不是固定的,它每次在名称“dir+一些随机数”中都会更改

有没有办法做这样的东西 我需要“任何”功能


当然可以。。。首先检查您想要的目录是否存在。如果没有,创建它

<?php
    // check if dir exists, if not create it
    if(!is_dir("files/dir".anything()."/other.."))
        mkdir("files/dir".anything()."/other..");

    // ... rest of code here
    $directory = "files/dir".anything()."/other..";
?>

我是不是遗漏了什么


编写一个函数
anything
,它返回一个您想要的任意值。这是非常基本的PHP编码。

除非我遗漏了一些东西,否则您不能这样做

function anything(this $str){}

在混乱之后,您似乎想要创建一个函数,创建一个唯一的文件名,然后将其应用于目录路径,使用rand()将无法获得唯一的id,因为有时并不是如此rand,而且每次创建一个新文件都会降低生成新随机文件的机会。使用md5,它将从uniqid/microtime创建一个128位alpha-numeric散列,返回相同散列的可能性非常小,甚至为零:

所以你应该做一些类似的事情:

<?php 
/**
 * Function to create 128bit unique hash string.
 * 
 * @return string
 */
function anything(){
    return md5(uniqid(rand(), true));
}

/*
You should store value in a variable if you need to use it further along
or in the future.
*/
$uniq_token = anything();

$directory = "files/".$uniq_token."/other..";
?>


您需要将
$uniq_token
存储在数据库中的某个位置,否则在尝试检索ect时,您将失去对该文件/文件夹的引用。

因此,问题是您无法将文件写入目录,因为它可能不存在,正确吗?…或者问题是您需要一种方法来确保新目录名是唯一的?请更具体一些,你会得到错误的答案。如果可能的话,再展示一些代码来演示您的问题。好的,这里再次说明:我有一个名为“dir和一些随机数”的目录,我需要知道该目录中的随机数是什么。您应该在/files/dir/randomname/other中列出目录,与@Frankie在一起。我认为我们应该开始对最简单的问题给出最简单的回答。不幸的是,它们可能都是“RTFM.做一些研究”我不知道“我想要什么”,因为目录名不是固定的,它总是变化的..但是你想做什么呢?您想创建一个随机数,它构成目录名的一部分吗?然后创建一个返回随机字符串(
(md5(microtime())
?)的函数,并将其存储在一个变量中,然后您可以使用该变量创建、使用和删除目录。如果
anything()
每次都发生更改,那么如果您不将返回值存储在variableble中,您将遇到问题。但是,如何使函数成为“anything”你不能。没有像c#这样的扩展。我不知道你想要什么。你没有很好地指出你的困难。。。
function anything(this $str){}
<?php 
/**
 * Function to create 128bit unique hash string.
 * 
 * @return string
 */
function anything(){
    return md5(uniqid(rand(), true));
}

/*
You should store value in a variable if you need to use it further along
or in the future.
*/
$uniq_token = anything();

$directory = "files/".$uniq_token."/other..";
?>