the question is how can i create new folder in my filesystem ?
I know how to add file, but how to create an empty folder in specified path ?
I'm using the Amazon S3 adaptor, and am able to create a directory using the following:
use Gaufrette\Filesystem;
use Gaufrette\Adapter\AwsS3;
use Aws\S3\S3Client;
$s3Service = S3Client::factory(array("key" => "Your Key Here", "secret" => "Your AWS Secret Here" ));
$adapter = new AwsS3($s3Service,"yourBucketNameHere");
$filesystem = new Filesystem($adapter);
$filesystem->write("new-directory-here/", "");
Then you call write apapter ensure that directory exist. For example Ftp
public function write($key, $content)
{
$this->ensureDirectoryExists($this->directory, $this->create);
$path = $this->computePath($key);
$directory = dirname($path);
$this->ensureDirectoryExists($directory, true);
...
}
/**
* Ensures the specified directory exists. If it does not, and the create
* parameter is set to TRUE, it tries to create it
*/
protected function ensureDirectoryExists($directory, $create = false)
{
...
}
Simply pass true to the Local adapter:
use Gaufrette\Adapter\Local as LocalAdapter;
...
$adapter = new LocalAdapter(__DIR__ . '/your-new-dir', true);
$filesystem = new Filesystem($adapter);
Related
It's evidently a little more complicated to create a file dynamically in SS4
$folder = Folder::find_or_make('Cards');
$filename = 'myimage.jpg';
$contents = file_get_contents('http://example.com/image.jpg');
$pathToFile = Controller::join_links(Director::baseFolder(), ASSETS_DIR, $folder->Title, $filename);
file_put_contents($pathToFile, $contents);
$image = Image::create();
$image->ParentID = $folder->ID;
$image->Title = "My title";
$image->Name = $filename;
$image->FileFilename = 'Cards/' . $filename;
$image->write();
Member::actAs(Member::get()->first(), function() use ($image, $folder) {
if (!$image->isPublished()) {
$image->publishFile();
$image->publishSingle();
}
if (!$folder->isPublished()) {
$folder->publishSingle();
}
});
The above, creates the file as expected in /assets/Cards/myimage.jpg and publishes it fine
However all previews are blank, so it's obviously not finding the file:
Any idea what I missed in creating the Image object?
This should work:
$folder = Folder::find_or_make('Cards');
$contents = file_get_contents('http://example.com/image.jpg');
$img = Image::create();
$img->setFromString($contents, 'image.jpg');
$img->ParentID = $parent->ID;
$img->write();
// This is needed to build the thumbnails
\SilverStripe\AssetAdmin\Controller\AssetAdmin::create()->generateThumbnails($img);
$img->publishSingle();
FYI: $img->Filename no longer exists. An Image or File object have a File property, which is a composite field of type DBFile. This composite fields contains the filename, hash and a variant…
So you should use the composite field to address these fields.
I'm making a Silverstripe build task to get many images from an external gallery, and create/upload them into the /assets/images/gallery folder with the necessary database links to the GalleryPage.
So I load the list of Urls, display the images to the browser, now how do I save an image into the assets folder with the necessary GalleryPage database links?
class ImportGalleryTask extends BuildTask {
public function writeImage($data) {
//$data->Title
//$data->Filename
//$data->Url
//this is the external url that I can output as an image to the browser
//
// folder to save image is 'assets/images/gallery'
//
// ? save into folder and database and associate to PageImageBelongsToID ?
}
}
You can use copy to copy a remote file to your local filesystem. PHP must be configured to support allow_url_fopen though.
So, your resulting function might look like this:
/**
* #param $data
* #return null|Image return written Image object or `null` if failed
*/
public function writeImage($data)
{
// The target folder for the image
$folder = Folder::find_or_make('images/gallery');
// assuming that $data->Filename contains just the file-name without path
$targetPath = $folder->getFullPath() . $data->Filename;
// Check if an image with this name already exists
// ATTENTION: This will overwrite existing images!
// If you don't want this, you need to implement this differently
if(
file_exists($targetPath) &&
$image = Image::get()->where(array(
'"Name" = ?' => $data->Filename,
'"ParentID" = ?' => $folder->ID
))->first()
){
// just copy the new file over…
copy($data->Url, $targetPath);
// … and delete all cached images
$image->deleteFormattedImages();
// and we're done
return $image;
}
// Try to copy the file
if (!copy($data->Url, $targetPath)) {
return null;
}
// Write the file to the DB
$image = Image::create(array(
'Name' => $data->Filename,
'ParentID' => $folder->ID,
'Filename' => $folder->getRelativePath() . $data->Filename
));
$image->write();
return $image;
}
I want to parse an ini file placed under the vendor directory.
How can I get the path to this file?
For Example:
In src/Acme/TestBundle/Repository/UserRepository.php I have
$file = parse_ini_file(FILE_PATH);
How do I set FILE_PATH to reach vendor/test/lib/conf.ini?
The other solution is correct but it can be even shorter (plus this should be the way to go in the current symfony version):
public function setup()
{
$rootDir = $this->container->getParameter('kernel.root_dir');
$filePath = $rootDir.'/../vendor/test/lib/conf.ini';
$file = parse_ini_file($filePath);
...
}
You didn't provided info what kind of test do you use, but you need to get the container and get kernel.root_dir from there
For WebTestCase:
public function setUp()
{
$kernel = static::createKernel();
$kernel->boot();
$rootDirectory = $kernel->getContainer()->getParameter('kernel.root_dir');
$filePath = $rootDirectory.'/../vendor/test/lib/conf.ini;
...
}
Please kindliy help out.Am using php excel with laravel but whenever i try to import excel file into database i get error "Error loading file "update.xlsx": Could not open localhost:9090/xls/update.xlsx for reading! File does not exist.".
My xls folder is placed in my public directory and am loading phpexcel with composer.Kindly help out i ddont know what am doing wrong.thanks in advance
Here is my code:
<?php
/************************ YOUR DATABASE CONNECTION START HERE ****************************/
define ("DB_HOST", "lhost"); // set database host
define ("DB_USER", "root"); // set database user
define ("DB_PASS",""); // set database password
define ("DB_NAME","name"); // set database name
// $link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
// $db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");
$databasetable = "applicant";
$con = new mysqli(DB_HOST, DB_USER,DB_PASS,DB_NAME);
/************************ YOUR DATABASE CONNECTION END HERE ****************************/
set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
// This is the file path to be uploaded.
$inputFileName = asset("xls/".$filename);;
try {
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$arrayCount = count($allDataInSheet); // Here get total count of row in that Excel sheet
for($i=2;$i<=$arrayCount;$i++)
{
$surname = trim(strtoupper($allDataInSheet[$i]["A"]));
$othernames = trim(strtoupper($allDataInSheet[$i]["B"]));
$address = strtoupper($allDataInSheet[$i]["C"]);
$lga = trim(strtoupper($allDataInSheet[$i]["D"]));
$sex = trim(strtoupper($allDataInSheet[$i]["E"]));
$dob = trim(strtoupper($allDataInSheet[$i]["F"]));
$genotype = trim(strtoupper($allDataInSheet[$i]["G"]));
$blood_grp = trim(strtoupper($allDataInSheet[$i]["H"]));
$phone = trim(strtoupper($allDataInSheet[$i]["I"]));
$email = trim(strtoupper($allDataInSheet[$i]["J"]));
$occupation = trim(strtoupper($allDataInSheet[$i]["K"]));
$place_emp = trim(strtoupper($allDataInSheet[$i]["L"]));
$facility = trim(strtoupper($allDataInSheet[$i]["M"]));
$medical_his = trim(strtoupper($allDataInSheet[$i]["N"]));
$allergy = trim(strtoupper($allDataInSheet[$i]["O"]));
$reg_frm = trim(strtoupper($allDataInSheet[$i]["P"]));
$reg_to = trim(strtoupper($allDataInSheet[$i]["Q"]));
$collector = trim(strtoupper($allDataInSheet[$i]["R"]));
$form_no = trim(strtoupper($allDataInSheet[$i]["S"]));
$tell_no = trim(strtoupper($allDataInSheet[$i]["T"]));
$amt_paid = trim(strtoupper($allDataInSheet[$i]["U"]));
$query = "SELECT surname FROM `applicant` WHERE `surname` = '$surname' and `othernames` = '$othernames'";
$sql = $con->query($query);
$recResult = mysqli_fetch_array($sql);
$existName = $recResult["surname"];
if($existName=="") {
$insertTable= $con->query("insert into `applicant` (surname, othernames,address,lga,sex,dob,genotype,blood_grp,phone,email,occupation,place_emp,facility,medical_his,allergy,reg_frm,reg_to,collector,form_no,tell_no,amt_paid)
values('".$surname."', '".$othernames."','".$address."','".$lga."','".$sex."','".$dob."',
'".$genotype."','".$blood_grp."','".$phone."','".$email."','".$occupation."',
'".$place_emp."','".$facility."','".$medical_his."','".$allergy."','".$reg_frm."',
'".$reg_to."','".$collector."','".$form_no."','".$tell_no."','".$amt_paid."');");
$msg = 'Record has been added';
}
else
{
$msg = 'Record already exist';
}
}
echo "<div class='alert alert-info'>".$msg."</div>";
?>
I'm not sure what is "composer" and what the asset() function is supposed to be doing, but normally for file uploads to a PHP script you'd use a "mime/multipart" web form with a file input, and then the PHP runtime will consume the file and make it available in the $_FILES array. Read the PHP manual on handling file uploads for more information.
PHPExcel cannot open a file from a URL, only from the local filesystem. As the url that you're using (localhost)suggests that file is on the server's filesystem, us a full filesystem path instead
I have an excel list of 600 users with name, email, and role - that I need to add to the drupal site I'm building.
There are 2 roles distributed among the users.
As an added complication, the site is using the Content Profile module, so it would be a great help if for each new user account created, a corresponding profile node was also auto-created.
Any ideas how to batch-create the new users?
How about the user_import module?
I had the same thing, and created a module for this.
Basically, it reads the user and what role to get from a file; in my case it was a CSV file with emailadres, name, role and stuff needed for the content profile.
Let's say you want user x#mail.com and fill out automatically his content profile data Name, Sirname and City or something.
In your module:
read the line from the file
create a new user
create a new node, (stdClass object, give it the correct type ('profile_data' or whatever your content profile type is) and fill the rest of yout node and save.
A sample:
<?php
//create a form with a button to read the CSV file
function bulk_users_submit() {
$users = 0;
$handle = fopen(drupal_get_path('module', 'bulk_users') .'/'.DATAFILE, "r");
if (!$handle) {
return $users;
}
while (($data = fgetcsv($handle)) !== FALSE) {
//this is similar to what the users.module does
if (bulk_users_create_user($data)) {
$users++;
bulk_users_create_profile($data);
}
}
fclose($handle);
return $users;
}
function bulk_users_create_profile($user, $data) {
$node = new stdClass();
$node->title = t('First and Last Name');
$node->body = "";
$node->type = 'first_and_last_name';
$node->created = time();
$node->changed = $node->created;
$node->status = 1;
$node->promote = 0;
$node->sticky = 0;
$node->format = 0;
$node->uid = $data['uid'];
$node->language = 'en';
$node->field_firstname[0]['value'] = $data['firstname'];
$node->field_lastname[0]['value'] = $data['lastname'];
node_save($node);
}
?>
not tested, but the idea is clear i hope.