Mon. - Fri. 9 am - 5 pm Ask a Question
Remember me

create user directory and move uploaded file

2 weeks 4 days ago #1

  • Birger's Avatar
  • Birger
  • Posts: 79
Hello,

I have a working PHP code. When I execute root/app/submit.php, everything works:
<?php

define( '_JEXEC', 1 );
define('JPATH_BASE', dirname(__FILE__) );
define( 'DS', DIRECTORY_SEPARATOR );

$user_id = "";
$form_id = "";

$user = 'user-4';
$form = 'form-4';

$dir = 'file_upload'.DS.$form.DS.$user;

if ( !file_exists( $dir ) && !is_dir( $dir ) ) {
    mkdir( $dir );      
}

rename("file_upload/$form/test.csv", "file_upload/$form/$user/test.csv");

root/app/file_upload/form-4/user-5/test.csv

As you can see, I want to create a user-id based folder after upload and move the uploaded file into current logged in users folder. It does not work with Submit button and I can't tell why. It does work with PHP file directly.

Any help appreciated.

2 weeks 4 days ago #2

  • Birger's Avatar
  • Birger
  • Posts: 79
Code is finally working.
Uploads will be placed in a "user-id" based folder within the "form-id" folder of your "upload-root".

upload-root/form-4/user-220/test.csv

Check Joomla database prefix...
e.g. joomla_baforms_submissions_attachments
define( '_JEXEC', 1 );
define('JPATH_BASE', dirname(__FILE__) );
define( 'DS', DIRECTORY_SEPARATOR );

require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );

$user =& JFactory::getUser();
$db =& JFactory::getDBO();

$user_id = $user->get('id');
$user_dir = 'user-'.$user_id;

$form_id = '[Form ID]';
$form_dir = 'form-'.$form_id;

$dir = JPATH_BASE.DS.'app'.DS.'file_upload'.DS.$form_dir.DS.$user_dir;
$submission_id = [Submission ID];

/* create user id based directory */
if ( !file_exists( $dir ) && !is_dir( $dir ) ) {
    mkdir( $dir );      
}

/* get one or multiple filenames as array */
$query = "
	SELECT filename
	FROM joomla_baforms_submissions_attachments
	WHERE submission_id = $submission_id
";
$db->setQuery($query);
$rows = $db->loadAssocList();

/* move files in array */
foreach ($rows as $row) {
	$filename = $row['filename'];
	rename(
	JPATH_BASE.DS.'app'.DS.'file_upload'.DS.$form_dir.DS.$filename,
	JPATH_BASE.DS.'app'.DS.'file_upload'.DS.$form_dir.DS.$user_dir.DS.$filename
	);
}

/* update filepath */
$path = $user_dir . '/';

$query = "
	UPDATE joomla_baforms_submissions_attachments
	SET filename = CONCAT('$path', filename)
	WHERE submission_id = $submission_id
";
$db->setQuery($query);
$result = $db->query();
Powered by Kunena Forum