简体   繁体   中英

PHP: Save file to a specific directory

I have this diretorio.php file that grabs the user id in Joomla and creates a directory with that id (if it doesn't exist yet):

/* 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);
};

Now, I want to save a file with data in an object, using an Ajax that triggers another PHP file to the same directory created above:

$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);

However, the file isn't created. If I replace the first line to:

$myFile = "dados.json";

It will create the file in the same directory where this PHP script is stored.

I would recommend using Joomla coding standards like so:

$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 is the root of your Joomla site

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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