I am trying to send an email with attachment when I used var_dump($filename)it returns the filename and gettype($filename) it returns string. but when I am trying to send an attachment it still returns Unable to open file for reading [filename.pdf] even if $file_attachment was looped I tried to change UploadedFile::getInstancesByName('file_attachment'); to UploadedFile::getInstanceByName('file_attachment'); but nothing happened. Please help me.
This is my controller
if(Yii::$app->request->isPost){
$email = Yii::$app->request->post('email');
$message = Yii::$app->request->post('message');
$file_attachment = UploadedFile::getInstancesByName('file_attachment');
if($file_attachment){
$mail = Yii::$app->mailer->compose()
->setFrom(['myemail#gmail.com' => 'My Email'])
->setTo($email)
->setSubject('My Subject')
->setHtmlBody($message);
foreach ($file_attachment as $file) {
$filename = $file->baseName. '.' . $file->extension;
$mail->attach($filename);
}
//$mail->send();
//echo gettype($filename);
// var_dump($filename);
$mail->send();
}else{
$mail = Yii::$app->mailer->compose()
->setFrom(['myemail#gmail.com' => 'My Email'])
->setTo($email)
->setSubject('My Subject')
->setHtmlBody($message)
->send();
}
}
This is the view
<?php
echo FileInput::widget([
'name' => 'file_attachment',
'attribute' => 'file_attachment',
'options' => ['multiple' => true]
]);
?>
The baseName property of yii\web\UploadedFile contains the original filename but the file is not present on the server under its original filename. You need to use tempName property that contains path to the uploaded file on server.
Your for each cycle that attaches files to mail should look like:
foreach ($file_attachment as $file) {
$filename = $file->baseName. '.' . $file->extension;
$mail->attach(
$file->tempName,
['fileName' => $filename]
);
}
It might also be a good idea to check hasError property of yii\web\UploadedFile before attempting to attach file to see if the upload was successful.
Also make sure that you've set 'enctype' => 'multipart/form-data' in you form options when you are not using ActiveForm with ActiveField::fileInput() otherwise the files might not be uploaded.
Related
i'm facing problems into cURL. here i can get the json data from another source code and also i got some ideas. but really i can't save the json data into my own server in sql database. i wanna to retrieve the data from
url: https://jamuna.tv/wp-json/wp/v2/posts
and wanna to save into my server (mysql).
here is the $url json data i wanna to save in mysql server:
id
date
link
title
content
author
categories
wp:attachment
and i want to save them into mysql database. my table name is "news" and i want to save them into my table columns.
id [id]
title [title]
description [content]
date [date]
category [categories]
thumbnail [wp:attachment]
admin [author]
here i'm mark the json from url and replaced into my sql columns name. if anyone can give me the instructions about how i can fetch the data from user and save into mysql.
thanks advance.
There is an implementation of your desired with PHP. You must check if values are valid or not or if the array members exist or not. This is just a primitive implementation of your example.
<!DOCTYPE html>
<html>
<body>
<?php
// db connection
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$db = new PDO('mysql:host=localhost;dbname=test;', 'user', 'pass', $options);
// download json from url
$json = file_get_contents('https://jamuna.tv/wp-json/wp/v2/posts');
echo '<br/>';
$sql = "INSERT INTO `mytable` (`id`,`title`,`description`,`date`,`category`,`thumbnail`,`admin`)
VALUES (:id, :title, :content , :date, :categories, :attachment, :author)";
$stm = $db->prepare($sql);
// parse JSON
$arr = json_decode($json, true);
$i = 0;
foreach ($arr as $record) {
echo "==================Insert record " . $i ++ . "<br>";
$data = array(
':id' => $record['id'],
':title' => $record['title']['rendered'],
':content' => $record['content']['rendered'],
':date' => $record['date'],
':categories' => $record['categories'][0],
':attachment' => $record['_links']['wp:attachment'][0]['href'],
':author' => $record['author']
);
var_dump($data);
// inserting a record
$stm->execute($data);
}
?>
</body>
</html>
I want to upload a .csv file into a database but in 3 different table. I mean like in the .csv file have three columns then I want to insert each column into different table. How can I do it? Can anyone give any example or idea to do this.
Here is an example if you wish to upload csv file in db
public function upload(Request $request){ //upload csv
$file = $request->file('file');
$csvData = file_get_contents($file);
$rows = array_map("str_getcsv", explode("\n", $csvData));
//CSV headers
$header = array_shift($rows);
$escapedHeader=[];
//to converting lowercase and remove spaces
foreach ($header as $key => $value) {
$lheader=strtolower($value);
$escapedItem=preg_replace('/[^a-z]/', '', $lheader);
array_push($escapedHeader, $escapedItem);
}
//storing data to database
foreach($rows as $row) {
if (count($header) != count($row)) {
continue;
}
//This will generate a associate array with headers.
$row = array_combine($escapedHeader, $row);//dd($row);
// if there are 3 tables named - student, course, grade
Student::create([
'fname' => $row['firstname'],
'lname' => $row['lastname'],
]);
Course::create([
'course' => $row['course'],
]);
Grade::create([
'grade' => $row['score'],
]);
}
Session::flash('message', 'CSV file imported!');
return response()->json('success');
}
I'm trying to load the list of network interface configuration files on Linux into the hash of hashes and further encode them into JSON. This is the code that I'm using:
#!/usr/bin/env perl
use strict;
use diagnostics;
use JSON;
use Data::Dumper qw(Dumper);
opendir (DIR, "/etc/sysconfig/network-scripts/");
my #configs =grep(/^ifcfg-*/, readdir(DIR));
my $output = "metadata/json_no_comment";
my %configuration;
my $key;
my $value;
my %temp_hash;
foreach my $input ( #configs) {
$input= "/var/tmp/rhel6.8/" . $input;
open (my $JH, '<', $input) or die "Cannot open the input file $!\n";
while (<$JH>) {
s/#.*$//g;
next if /^\s*#/;
next if /^$/;
for my $field (split ) {
($key, $value) = split /\s*=\s*/, $field;
$temp_hash{$key} = $value;
}
$configuration{$input} = \%temp_hash;
}
close $JH;
}
print "-----------------------\n";
print Dumper \%configuration;
print "-----------------------\n";
my $json = encode_json \%configuration;
open (my $JNH, '>', $output) or die "Cannot open the output file $!\n";
print $JNH $json;
close $JNH;
The data structure, that I'm getting is following:
$VAR1 = {
'/etc/sysconfig/network-scripts/ifcfg-lo' => {
'BOOTPROTO' => 'dhcp',
'NAME' => 'loopback',
'TYPE' => 'Ethernet',
'IPV6INIT' => 'yes',
'HWADDR' => '"52:54:00:65:e7:8c"',
'DEVICE' => 'lo',
'NETBOOT' => 'yes',
'NETMASK' => '255.0.0.0',
'BROADCAST' => '127.255.255.255',
'IPADDR' => '127.0.0.1',
'NETWORK' => '127.0.0.0',
'ONBOOT' => 'yes'
},
'/etc/sysconfig/network-scripts/ifcfg-eth0' => $VAR1->{'/etc/sysconfig/network-scripts/ifcfg-lo'}
};
The data structure, I'm looking for is the following:
$VAR1 = {
'/etc/sysconfig/network-scripts/ifcfg-lo' => {
'BOOTPROTO' => 'dhcp',
'NAME' => 'loopback',
'TYPE' => 'Ethernet',
'IPV6INIT' => 'yes',
'HWADDR' => '"52:54:00:65:e7:8c"',
'DEVICE' => 'lo',
'NETBOOT' => 'yes',
'NETMASK' => '255.0.0.0',
'BROADCAST' => '127.255.255.255',
'IPADDR' => '127.0.0.1',
'NETWORK' => '127.0.0.0',
'ONBOOT' => 'yes'
},
'/etc/sysconfig/network-scripts/ifcfg-eth0' => {
'BOOTPROTO' => 'dhcp',
'NAME' => '"eth0"',
'TYPE' => 'Ethernet',
'IPV6INIT' => 'yes',
'HWADDR' => '"52:54:00:65:e7:8c"',
'NETBOOT' => 'yes',
'ONBOOT' => 'yes'
}
};
Any idea what am I doing wrong? Why the first nested hash is created correctly and the second one is not? I suspect, that it has something to do with reading the files line by line, but I have to do it, because I need to filter out the commented lines before JSON conversion.
Thanks for any help.
Edit: I have modified the script as suggested by Borodin and it works. Thanks!
The problem is that $configuration{$input} always refers to the same hash %temp_hash because you have declared it at file level. You need to created a new hash for each config file by declaring %temp_hash inside the for loop
Also note that next if /^\s*#/ can have no effect because you just deleted any hashes in the line. Your sanitisation should look like
s/#.*//;
next unless /\S/;
I have a JSON file that I would like to load into a controller in Laravel so that I can use the data into my application.
The files path is /storage/app/calendar_Ids.json.
What is the correct way to go about doing this?
Here, this should help you get sorted.
use Storage;
$json = Storage::disk('local')->get('calendar_Ids.json');
$json = json_decode($json, true);
Try this
$path = '/storage/app/calendar_Ids.json';
$content = json_decode(file_get_contents($path), true);`
Then just dd($content); to see if it works.
You can try this too:
$json = file_get_contents('your json file path here.....');
//converting json object to php associative array
$data = json_decode($json, true);
foreach($data as $item){
DB::table('table name')->insert(
array(
'clientId' => $item['clientId'],
'socialMediaLinkId' => $item['socialMediaLinkId'],
'link' => $item['link'],
'isEnabled' => $item['isEnabled'],
'created_at' => $item['created_at'],
'updated_at' => $item['updated_at'],
'isSelectedByDefault' =>$item['isSelectedByDefault'],
'showOnNegativePage' =>$item['showOnNegativePage']
)
);
}
You can try this too:
$json = storage_path('folder/filename.json');
I am facing some unknown issues with wordpress featured image. When I update a featured image from the website; it gets displayed in the app via json.
http://indiafastener.com/api/?json=get_post&post_type=listing-item&id=1377
however when I upload an image via json into the wordpress db; the output is NULL in the image field.
http://indiafastener.com/api/?json=get_post&post_type=listing-item&id=1380
when I see the db; it has the image path and the path does not lead to 404.
Image Path:
http://www.indiafastener.com/webservices/listing/uploads/2017-04-01_12-01-40IMG-20150715-WA0004.jpg
Could it be because the image is not there in the wp-content/uploads/2016/02/ folder?
Code to upload the image
require_once('../../wp-config.php');
require_once('../../wp-admin/includes/image.php');
$dirname = "../../wp-content/uploads/2017/01/";
$filename = $_FILES["file"]["name"];
$attachment = array(
'post_mime_type' => 'image/jpeg',
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $dirname.basename($filename)
//'wp-content/uploads/2017/01/' . basename($filename)
);
$your_post_id = 1392;
$attach_id = wp_insert_attachment( $attachment, $filename,'$your_post_id' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
//$id=1385;
update_post_meta($id, '_thumbnail_id', $attach_id);
echo "success";
Any help on this will be highly appreciated.
Screenshots
DB post_type attachment of image uploaded via app
DB Post linked to the image Id
Missing Image Preview:
I am not sure about your code but my below piece of code is working perfectly for assign image as feature image for post. please go through it.
attachment id should be assign to particulate post, check your post meta '_thumbnail_id' for post as well.
require_once(ABSPATH . 'wp-admin/includes/image.php');
$filename = 'your file name';
$attachment = array(
'post_mime_type' => 'your mime type',
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $wp_upload_dir['url'] . '/' . basename($filename)
);
$attach_id = wp_insert_attachment( $attachment, $filename,'your_post_id' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
update_post_meta($id, '_thumbnail_id', $attach_id);