PHPExcel file does not exsit - phpexcel

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

Related

Symfony - Doctrine - Cannot store a blob file in Oracle database

I want to store uploaded files in Oracle database .
I'm using Doctrine in Symfony 5.
I made an entity "Attachment", with a property "filename" (type string) and "filecontent" (type blob).
The following code is in controller, to get files uploaded, transform file content in stream, and store it in database
$attachments = $form->get('attachments')->getData();
if (count($attachments) > 0) {
foreach ($attachments as $attachment) {
$attach = new Attachment();
$attach->setFilename($attachment->getClientOriginalName());
$strm = fopen($attachment->getRealPath(), 'rb');
$attach->setFilecontent(stream_get_contents($strm));
$em->persist($attach);
}
}
When i submit the form, i have the error :
Warning: PDOStatement::execute(): supplied argument is not a valid stream resource
On a MySQL database, all is allright. File is correctly stored in database, no "stream ressource" issue.
I've found an old workaround here : https://groups.google.com/g/doctrine-user/c/JILLBji__MU but maybe there is a final solution to this problem.
Could you help me ?
Thanks
Oracle and doctrine have not a good compatibility.
So I do it in php and native SQL to do the trick
More information here:
https://www.php.net/manual/en/pdo.lobs.php
In your repository, it's looks like this :
$conn = $this->getEntityManager()->getConnection();
// Get Next Sequence
$sqlSeq = "SELECT DOCUMENT_FILE_id_seq.nextval FROM DUAL";
$stmtSeq = $conn->prepare($sqlSeq);
$stmtSeq->execute();
$nextId = (int)$stmtSeq->fetchFirstColumn()[0];
$fp = fopen($attachment->getRealPath(), 'rb');
// Insert file
$sql = "INSERT INTO DOCUMENT_FILE (id, file_content) VALUES (?,EMPTY_BLOB()) RETURNING file_content INTO ?";
$stmt = $conn->prepare($sql);
$stmt->bindParam(1, $nextId, \PDO::PARAM_INT);
$stmt->bindParam(2, $fp, \PDO::PARAM_LOB);
$conn->beginTransaction();
$stmt->execute();
$conn->commit();
That work for me.

Create file dynamically as File object and then publish

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.

Contactform7 passing server values to javascript

I'm using the Contact Form 7 plugin for the user to generate a pdf based on submitted (by the form) and server provided data.
I'd like to also show a "preview" after submission so I need to pass the custom fields to the client in order to get them in some js file.
This is what I have:
plugin rendering the pdf:
<?php
add_action('wpcf7_before_send_mail', 'generate_pdf');
function generate_pdf($wpcf7) {
$file_uri = 'fpdf/fpdf.php';
require_once($file_uri);
/* PDF file initialization */
$pdf = new FPDF();
$pdf->AddPage();
$pdf->AliasNbPages();
$pdf->SetFont('Arial','B',12);
$today_date = "California, " . date("d F Y");
$pdf->Cell(0, 10, $today_date, 0, 1, 'R');
$name = $data['your-name'];
$submission = WPCF7_Submission::get_instance();
$data = $submission->get_posted_data();
$pdf->Output(wp_upload_dir()['basedir'] . '/' . $name . '.pdf', 'F');
$wpcf7['custom_field'] = 'CUSTOM VALUE';
return $wpcf7;
}
?>
javascript file called on form submit:
$('.wpcf7-submit').on('click', function (e) {
var data = $('form').serializeArray();
var cleaned_data = {};
for (item in data) {
var name = data[item]['name'];
if (name[0] != '_'){
cleaned_data[name] = data[item]['value'];
}
}
var testInput = cleaned_data["your-name"];
})(jQuery);
In this last code I'd like to get the values passed by the php script, but I don't know how to do it.
Assuming that the PDF generation function is in functions.php and that you've enqueued the js, what you're looking to do is localization. You can read more about it here: Localize scripts

Symfony2 Gaufrette How to create directory?

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

batch create users?

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.

Resources