繁体   English   中英

PHP:将文件保存到特定目录

[英]PHP: Save file to a specific directory

我有这个diretorio.php文件,该文件在Joomla中获取用户ID并创建具有该ID的目录(如果尚不存在):

/* Get the current user id */
$user = JFactory::getUser();
$usr_id = $user->get('id');

/*Define the path to this user's directory */
$diretorio=$_SERVER['DOCUMENT_ROOT']."/Apps/files/".$usr_id;

/*Create the user's directory if it doesn't exist */
if (!file_exists($diretorio) and !is_dir($diretorio)) {
    mkdir($diretorio, 0755);
};

现在,我想使用一个Ajax将一个包含数据的文件保存在一个对象中,该Ajax会将另一个PHP文件触发到与上面创建的相同目录中:

$myFile = $diretorio."/dados.json";
$fh = fopen($myFile, 'w') or die("não é possível abrir o ficheiro");
$stringData = $_POST['data'];
$stringData='{  "data":'.json_encode($stringData).'}';
fwrite($fh, $stringData);
fclose($fh);

但是,未创建该文件。 如果我将第一行替换为:

$myFile = "dados.json";

它将在存储此PHP脚本的同一目录中创建文件。

我建议像这样使用Joomla编码标准:

$user = JFactory::getUser();
$usr_id = $user->get('id');

$diretorio = JPATH_SITE . "/Apps/files/" . $usr_id;

if (!JFolder::exists($diretorio)) {
    JFolder::create($diretorio, 0775);
}

$myFile = $diretorio."/dados.json";

$stringData = $_POST['data'];
$stringData = '{ "data":'.json_encode($stringData).'}';
JFile::write($myFile, $stringData);

JPATH_SITE是您的Joomla网站的根

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM