I’m trying to write a plugin that when a specific resource (Privacy Policy) is saved, a static file is overwritten (or created if doesn’t exist) with everything from the resource’s [[*content]] field. The point here is that this content will be included and loaded from other sites as well, but I’d rather be able to edit it once by this main resource.
I thought that file_put_contents() or fopen/fwrite/fclose would work, but I’m doing something wrong.
Also, just check that you have the right permissions. If you’re creating a PHP file you might need to add php file extension to the upload_file_types setting (although, please don’t do this on production as that’s asking to get hacked). Do you get an error in the log when the write fails?
I’m still having trouble getting this to work. I even changed the file type to html rather than PHP for security reasons.
I think part of the problem is my inexperience with writing plugins. Is there a better resource with examples than the MODX documentation on plugins? It doesn’t have much info there.
I’ve tried each of these with no success:
if ( $resource->get( ‘template’ ) == 57 ) :
$file = fopen( "/assets/elements/shared/privacy-test.html", 'w' );
if (!$file) {
$modx->log(modX::LOG_LEVEL_ERROR, 'Could not open file');
}
$newContent = $resource->get( 'content' );
fwrite( $file, $newContent );
fclose( $file );
endif;
$modx->getService(‘fileHandler’,‘modFileHandler’);
$file = $modx->fileHandler->make(‘/assets/elements/shared/privacy-test.html’);
if (!$file->create(‘Hello!’)) {
return ‘File not written.’;
}
return ‘File written.’;
if ($modx->event->name != ‘OnDocFormSave’) {return false;}
Yes, i tried them and it didn’t work. I’ve tried something new to see if i’m doing this right and it looks like I’m probably not.
I made a snippet called privpolTest and it includes:
$file = fopen( "/assets/elements/shared/test.txt" , 'w');
if (!$file) {
$modx->log(modX::LOG_LEVEL_ERROR, 'Could not open file');
}
$newContent = 'hello world';
fwrite( $file, $newContent );
fclose( $file );
Then, I created a new resource (without rich text) and just included the snippet [[privpolTest]]. Loaded that page in the browser, refreshed the files tab in the CMS, checked for the file but the file doesn’t exist.