Swift_IoException Unable to open file for reading yii2 - yii2

I am developing a web application in Yii2. I have attached a file while sending the email. But after attaching the file in email I am facing this error.
error Image
My code for sending email with attachment goes like this
Yii::$app->mailer->compose()
->setFrom('sender email')
->setTo('reciever email')
->setSubject('test')
->setHtmlBody('test')
->attach('path of attachment file')
->send();
I am really facing a big problem please help.

According to this link http://www.yiiframework.com/doc-2.0/guide-tutorial-mailing.html#file-attachment , the attach() method expects the filename (string) as parameter. To fix your code:
$model->attachment = UploadedFile::getInstances($model, 'attachment');
if($model->attachment) {
$message = Yii::$app->mailer->compose()
->setFrom([ Yii::$app->user->identity->email => 'Sample Mail'])
->setTo($model->email)
->setSubject($model->subject)
->setHtmlBody($model->content);
foreach ($model->attachment as $file) {
$filename = 'emailattachments/' .$file->baseName. '.' . $file->extension; # i'd suggest adding an absolute path here, not a relative.
$file->saveAs($filename);
$message->attach($filename);
}
$message->send();
}

Related

How can I embed external content in a WordPress widget?

I want to display a download link inside a WordPress widget. The file to be downloaded is located in the download subfolder of the site root, so that it can be uploaded via FTP. The name of the file and the text to be displayed for the download link shall be stored in a simple text file in the same folder.
Assuming WordPress is installed on www.mysite.com. The file name is setup_1_0.zip and the link display is Setup 1.0.
I am open to the file format how this information is stored as long as I can upload that file via FTP, too.
How can I embed this information inside a Custom HTML widget to get a valid download link with the text taken from that file?
How to automate the process of uploading latest software's build and download link creation in WordPress?
Based on your logic.
You are trying to automate the download process of your latest software version.
You don't want to update things manually and you just want to upload your latest build in the /download/ folder. (Only drop your latest version using FTP; that's all)
This is how I would do it:
Referencing those questions:
Get the latest file addition in a directory
How to force file download with PHP
I propose two solutions: First two separte codes, Second One inline code.
Just for educational purpose
First solution: Quick and short usage:
(You might need a way or a plugin to activate running PHP in Widget; this plugin helps PHP Code Widget)
<?php
$path = "download/";
$latest_ctime = 0;
$latest_filename = '';
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
// could do also other checks than just checking whether the entry is a file
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
}
}
echo 'Download '. $latest_filename . '';
?>
Second solution:
(Again, you might need a way or a plugin to activate running PHP in Widget; this plugin helps PHP Code Widget)
A) Create download.php in http://www.example.com/download.php
Add the following code:
<?php
$path = "download";
$latest_ctime = 0; //ctime stands for creation time.
$latest_filename = '';
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
// could do also other checks than just checking whether the entry is a file
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
}
}
// echo $latest_filename; un-comment to debug
$file_url = 'http://www.example.com/download/'.$latest_filename;
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url); // do the double-download-dance (dirty but worky)
?>
B) in your WordPress HTML Widget add the following code
<?php
$path = "download";
$latest_ctime = 0;
$latest_filename = '';
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
// could do also other checks than just checking whether the entry is a file
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
}
}
echo 'Download '. $latest_filename . '';
?>
Further explanation:
A) is responsiple for downloading the latest software build automatically.
B) is responsiple for displaying Latest build name and Creating the link.
Now, You only need to upload one file to your /download/ folder which is your latest build (setup_1_0.zip, setup_1_1.zip, setup_1_2.zip ...etc. The proposed solution will check creation date regardless of file's name.)
Important note: You can see that the latest file checker function is repeated twice; once in download.php and once in WordPress Widget. Because if we combine in one file we will get header already sent error.
Dose this answer your question please? Kindly feedback.

Yii2: refresh() not working after sending response content

I have a ActiveForm which I use to get some data from and when I click the send button it will run the model (in this case a csv file generator) but the refresh is not working, when I remove the method it will refresh.
After some testing it seems that fputcsv() will stop the script, so that everything that comes after this will not run.
view
public function actionIndex()
{
$model = new Export();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$fields = Yii::$app->request->post('Export');
\backend\models\Export::generate();//this prevents the refresh
Yii::$app->session->setFlash();
return $this->refresh();
} else {
return $this->render('index' , ['model' => $model]);
}
}
model
static public function generate()
{
header('Content-Encoding: UTF-8');
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="sample.csv"');
header("Pragma: no-cache");
header("Expires: 0");
$data = [array comes here];
$fp = fopen('php://output', 'w') or die("Unable to open file!");
fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
foreach ( $data as $line ) {
fputcsv($fp , $line , ';' );
}
stream_get_contents($fp);
fclose($fp);
}
Controller::refresh() uses Location header to reload page. Since headers need to precede the content, you cannot add new header after content was sent. Your Export::generate() method sends content, so you cannot add any header after that, thus $this->refresh() do not work.
Prior to Yii 2.0.14 there was a bug and framework simply ignored that you're trying to send header after content has been send. If you upgrade Yii, you should get "nice" Exception in this case.
If you're trying to display nice page after downloading file, your approach is incorrect. You can't really return file and then redirect to different page. You should first display nice HTML page and inside of it redirect user to download page (for example by using <meta http-equiv="refresh" content="0; url=http://example.com/" /> in head or creating hidden form and submitting it by JavaScript). After downloading the file user will stay at this nice page, so from UX perspective everything should be OK.

get profile picture from instagram api

I'm trying to get profile pictures using Instagram Api. I tried the following code:
function getpho($userid)
{
$userid = "000000";
$token = "my access token";
$url = "https://api.instagram.com/v1/users/".$userid."/?access_token=".$token;
$get = file_get_contents($url);
$json = json_decode($get);
foreach($json->data as $user)
{
return $user->profile_picture;
}
}
echo getpho($userid);
But this returns a blank page. What is wrong with my code?
try
$json = json_decode($get);
return $json->data->profile_picture;
Probably you're in Sandbox mode.
In this mode you can get media only of users that you've invited (up to 10). They will doesn't receive a notification, but they shall accept the request at this address: https://www.instagram.com/developer/clients/sandbox_invites/
By using this link you can get insta user details :
https://www.instagram.com/username/?__a=1&__d=dis

AS3 ALIVEPDF saving via method.remote (PHP) no longer working

The SWF is located on a web server. I am calling the function using this code in AS3...
myPDF.save(Method.REMOTE, "http://www.example.com/generator/createpdf.php",
Download.ATTACHMENT, "line.pdf");
Here is my PHP script located on the server...
$method = $_GET['method'];
$name = $_GET['name'];
if ( isset ( $GLOBALS["HTTP_RAW_POST_DATA"] )) {
// get bytearray
$pdf = $GLOBALS["HTTP_RAW_POST_DATA"];
// add headers for download dialog-box
header('Content-Type: application/pdf');
header('Content-Length: '.strlen($pdf));
header('Content-disposition:'.$method.'; filename="'.$name.'"');
echo $pdf;
} else echo 'An error occured.';
It used to work, but stopped a while back. Any help would be greatly appreciated.
1) This stopped working for me as well, until I added the following -
if(!$HTTP_RAW_POST_DATA){
$HTTP_RAW_POST_DATA = file_get_contents(‘php://input’);
}
2) I also patched /src/org/alivepdf/pdf/PDF.as::save() per this post enter link description here

How to access bootstrap.inc on external file

I need to bootstrap Drupal. I have a php-file with all my functions and in one of those functions, I need to use a Drupal function which is located in the bootstrap.inc file.
Structure of the server:(d) drupal (sd)includes (f)bootstrap.inc(d) scripts (sb)functions (f) functions.php
So I need to include in a self-written function the "variable_set" function, located in bootstrap.inc.
A little piece of the function my college wrote (I'm terribly sorry, but I don't know how to format php on the forum. If someone does, please let me know so I can edit this mess):
function readxml()
{
echo "<br/>READING...<br/>";
$file = './config.xml';
$xml = simplexml_load_file($file);
if($xml !== false)
{
foreach($xml->config->children() as $item){
$name = $item->getName(); // GETS CHILDREN UNDER 'CONFIG'
switch($name)
{
case 'website':
foreach($xml->config->website->children() as $kid){
$childname = $kid->getName();
switch($childname)
{
case 'theme':
if(inserttheme($kid)or die ('failed to insert theme<br/>')){
echo 'theme is installed.<br/>';}
break;
case 'slogan':
if(insertslogan($kid)or die('failed to insert slogan<br/>')){
echo 'slogan is installed.<br/>';}
break;
case 'sitename':
if(insertname($kid)or die('failed to insert name<br/>')){
echo 'website name is installed.<br/>';}
break;
}
}
break;
`
So, somewhere in the theme/slogan/name section, I have to call the variable_set function which is located in the bootstrap.inc file.
Somewhere I found this (again sorry for the non-formated text):
$drupal_directory = "/home/httpdocs/drupal"; // wherever Drupal is
$current_directory = getcwd();
chdir($drupal_directory);
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
chdir($current_dir);
return;
I included it both in my function.php as well as in my final php-file (where all the functions are called) but no result... What am I doing wrong?
That code you found looks about right, what is exactly is "no result", are you getting errors or nothing or...? Also, where did you put it exactly? (If it is not in a function, you need to remove the last line (return))
Also, the proper way to fix this would be to integrate your custom code as a Drupal module, then you don't have to worry about stuff like this: http://drupal.org/developing/modules
Or if it is a CLI script, expose it as a drush command: http://drupal.org/project/drush
Answer to the question, just include the file inside the Drupal folder!