I'm currently creatting a mailer and embed image. So when I set a specific directory ( ./upload/tmp_logo_company_upload/company_logo_resized.jpg ) for image it successfully send to my email and it shows the image that i embed.
But I want is to get all the image in the upload directory so whenever I run the script all images from upload folder will send to me. Can someone help me out for this, Below you will see my code. Thanks.
if( !defined('sugarEntry') ) define( 'sugarEntry',true );
// Set required classes
require_once('include/entryPoint.php');
// Get access to globals
global $db, $current_user, $timedate;
$arRecipientsId = array();
$objDefaultMail = new Email();
$objDefault = $objDefaultMail->getSystemDefaultEmail();
$objMail = new SugarPHPMailer();
$objMail->setMailerForSystem();
$objMail->From = $objDefault['email'];
$objMail->FromName = $objDefault['name'];
$objMail->Subject = "";
// Set the Location of photo
$strLocation = './upload/tmp_logo_company_upload/company_logo_resized.jpg';
// Add image
$objMail->AddEmbeddedImage($strLocation, 'company_logo_resized.jpg');
//
$objMail->Body = "Here. <img src='cid:company_logo_resized.jpg'>";
// Send as HTML
$objMail->IsHTML(true);
// Clear previous email data
$objMail->ClearAllRecipients();
$objMail->ClearReplyTos();
$objMail->prepForOutbound();
// Store recipients
$arRecipientsId[] = "1"; //crmonline
// Add as BCC
$objMail->AddBCC('email#gmail.com');
// Mail sent?
if( $objMail->send() ) {
// echo "Email Has Been Sent";
$GLOBALS['log']->fatal("WORKING");
}
// }
There's no need to call ClearAllRecipients or ClearReplyTos - the things those clear are already empty because you have a new instance.
To iterate over all the files in a folder, use a DirectoryIterator - that will get all the filenames you need, so you just need to call addEmbeddedImage for each and add <img src="cid:xxx"> tags for each image you want to embed.
$dir = './upload/tmp_logo_company_upload';
$cidn = 0;
foreach (new DirectoryIterator($dir) as $fileInfo) {
if($fileInfo->isDot() or $fileInfo->isDir()) continue;
$objMail->addEmbeddedImage($dir . DIRECTORY_SEPARATOR . $fileInfo->getFilename(), "img_$cidn");
$mailObj->Body .= "<img src=\"cid:img_$cidn\">";
++$cidn;
}
That said, this is an inefficient way of using images in email - it is much better to use HTTP links to the images - that way they are only loaded when the recipients ask for them, rather than sending them regardless.
Its pretty simple , you are missing complete image public path
change this to following
$objMail->Body = "Here. <img src='cid:company_logo_resized.jpg'>";
To (Image Public Path including http)
$objMail->Body = "Here. <img src='http://example.com/publicppath /company_logo_resized.jpg'>";
Adding code for Reading the Image from dir
//path to the dir
$dir = '/upload';
$files = scandir($dir);
foreach ($files as $image) {
$all_img .= " <img src='http://example.com/imagepath/".$image."'><br>";
}
//for embeding image
foreach ($files as $image) {
$im = file_get_contents($image);
$em_img .="<img src='data:image/jpg;base64,".base64_encode($im)."'> <br>"
}
//via public path
$objMail->Body = "Here ".$all_img;
//or embed sending
$objMail->Body = "Here ".$em_img;
it should work
Related
I am trying to prevent from uploading image before form submit using summernote editor.
The code I was using (jquery/ajax) worked well for uploading image, but it was uploading image instantly when I add it to editor.
This was not desired behavior for me, 'couse if user add image to editor and then decide to close tab/close browser or go to another address, image will be stored on server - so I would like to upload image only when submit button is clicked (until then, it should be there only as preview).
I use following code which is parsing base64 coded image from editor, decoding and uploading to server.
it works fine when adding new article or updating article without adding new image into it.
Example : if article has 2 old images allready, and I add 1 more image then its trying to reupload that old images again, but old images are decoded so it doesn't upload them and inserting an undefined link into the editor.
I tried to validate with the server using :
if(file_exists($filename)){
echo 'Already exist';
}
But had no luck to make it work.
Here is my code :
if(strpos($submitted_content, '<img') !== false && strpos($submitted_content, ';base64') !== false) {
$doc = new DOMDocument();
$doc->loadHTML($submitted_content);
$tags = $doc->getElementsByTagName('img');
foreach($tags as $tag) {
// Get base64 encoded string
$srcStr = $tag->getAttribute('src');
$base64EncData = substr($srcStr, ($pos = strpos($srcStr, 'base64,')) !== false ? $pos + 7 : 0);
$base64EncData = substr($base64EncData, 0, -1);
// Get an image file
$img = base64_decode($base64EncData);
// Get file type
$dataInfo = explode(";", $srcStr)[0];
$fileExt = str_replace('data:image/', '', $dataInfo);
// Create a new filename for the image
$newImageName = str_replace(".", "", uniqid("img_", true));
$filename = $newImageName . '.' . $fileExt;
$file = '../uploads/large/' . $filename;
// Save the image to disk
$success = file_put_contents($file, $img);
$imgUrl = 'http://localhost/haber/uploads/large/' . $filename;
// Update the forum thread text with an img tag for the new image
$newImgTag = '<img src="' . $imgUrl . '" />';
$tag->setAttribute('src', $imgUrl);
$tag->setAttribute('data-original-filename', $tag->getAttribute('data-filename'));
$tag->removeAttribute('data-filename');
$submitted_text = $doc->saveHTML(); //This is the result of the editor to add database
}
Any help will be appricated! Thanks.
Solution :
I just needed to add if statement under foreach and take $submitted_text = $doc->saveHTML(); out of foreach, it works like a charm now.
if(preg_match('/data:image/', $srcStr)){}
if you want to add images to database, you can collect $filename to array $arr = array(); and implode or foreach in to database.
Can be used for all editors.
So I am using this script to upload a file to a directory and show it live.
<?php
function UploadImage($settings = false)
{
// Input allows you to change where your file is coming from so you can port this code easily
$inputname = (isset($settings['input']) && !empty($settings['input']))? $settings['input'] : "fileToUpload";
// Sets your document root for easy uploading reference
$root_dir = (isset($settings['root']) && !empty($settings['root']))? $settings['root'] : $_SERVER['DOCUMENT_ROOT'];
// Allows you to set a folder where your file will be dropped, good for porting elsewhere
$target_dir = (isset($settings['dir']) && !empty($settings['dir']))? $settings['dir'] : "/uploads/";
// Check the file is not empty (if you want to change the name of the file are uploading)
if(isset($settings['filename']) && !empty($settings['filename']))
$filename = $settings['filename'] . "sss";
// Use the default upload name
else
$filename = preg_replace('/[^a-zA-Z0-9\.\_\-]/',"",$_FILES[$inputname]["name"]);
// If empty name, just return false and end the process
if(empty($filename))
return false;
// Check if the upload spot is a real folder
if(!is_dir($root_dir.$target_dir))
// If not, create the folder recursively
mkdir($root_dir.$target_dir,0755,true);
// Create a root-based upload path
$target_file = $root_dir.$target_dir.$filename;
// If the file is uploaded successfully...
if(move_uploaded_file($_FILES[$inputname]["tmp_name"],$target_file)) {
// Save out all the stats of the upload
$stats['filename'] = $filename;
$stats['fullpath'] = $target_file;
$stats['localpath'] = $target_dir.$filename;
$stats['filesize'] = filesize($target_file);
// Return the stats
return $stats;
}
// Return false
return false;
}
?>
<?php
// Make sure the above function is included...
// Check file is uploaded
if(isset($_FILES["fileToUpload"]["name"]) && !empty($_FILES["fileToUpload"]["name"])) {
// Process and return results
$file = UploadImage();
// If success, show image
if($file != false) { ?>
<img src="<?php echo $file['localpath']; ?>" />
<?php
}
}
?>
The thing I am worried about is that if a person uploads a file with the same name as another person, it will overwrite it. How would I go along scraping the filename from the url and just adding a random string in place of the file name.
Explanation: When someone uploads a picture, it currently shows up as
www.example.com/%filename%.png.
I would like it to show up as
www.example.com/randomstring.png
to make it almost impossible for images to overwrite each other.
Thank you for the help,
A php noob
As contributed in the comments, I added a timestamp to the end of the filename like so:
if(isset($settings['filename']) && !empty($settings['filename']))
$filename = $settings['filename'] . "sss";
// Use the default upload name
else
$filename = preg_replace('/[^a-zA-Z0-9\.\_\-]/',"",$_FILES[$inputname]["name"]) . date('YmdHis');
Thank you for the help
I have the following PHP code to display the content of a directory in my website:
<?php
$conn = ftp_connect("host") or die("Could not connect");
ftp_login($conn,"username","password");
if ($_GET['dir'] != null) {
ftp_chdir($conn, "logs/{$_GET['dir']}");
}
else
{
ftp_chdir($conn, "logs");
}
$files = ftp_nlist($conn,"");
foreach($files as $value) {
echo "{$value}";
}
ftp_close($conn);
?>
This is my webpage
When I click on the subdirectory1 or subdirectory2, I get the content of it (some images). Then when I click on one of the images, I get the content of the root directory of my website.
How can I display only the image when a visitor clicks on it? Note that I don't want to download it or anything - I just want to display it in the browser when a visitor clicks on it.
You need to establish which of the returned items are files and which are directories. For that you are better of using ftp_rawlist as it allows to extract more data. Then create links for each case and so you can process them appropriately. Here's a possible implementation:
$ftpHost = 'hostname';
$ftpUser = 'username';
$ftpPass = 'password';
$startDir = 'logs';
if (isset($_GET['file'])) {
// Get file contents (can also be fetched with cURL)
$contents = file_get_contents("ftp://$ftpUser:$ftpPass#$ftpHost/$startDir/" . urldecode($_GET['file']));
// Get mime type (requires PHP 5.3+)
$finfo = new finfo(FILEINFO_MIME);
$mimeType = $finfo->buffer($contents);
// Set content type header and output file
header("Content-type: $mimeType");
echo $contents;
}
else {
$dir = (isset($_GET['dir'])) ? $_GET['dir'] : '';
$conn = ftp_connect($ftpHost) or die("Could not connect");
ftp_login($conn, $ftpUser, $ftpPass);
// change dir to avoid ftp_rawlist bug for directory names with spaces in them
ftp_chdir($conn, "$startDir/$dir");
// fetch the raw list
$list = ftp_rawlist($conn, '');
foreach ($list as $item) {
if(!empty($item)) {
// Split raw result into pieces
$pieces = preg_split("/[\s]+/", $item, 9);
// Get item name
$name = $pieces[8];
// Skip parent and current dots
if ($name == '.' || $name == '..')
continue;
// Is directory
if ($pieces[0]{0} == 'd') {
echo "<a href='?dir={$dir}/{$name}'><strong>{$name}</strong></a><br />";
}
// Is file
else {
echo "<a href='?file={$dir}/{$name}'>{$name}</a><br />";
}
}
}
ftp_close($conn);
}
You'll need to add a function which checks which type of file we're handling.
If it's a directory show the regular link (the one you're using now) and if it's an image
show a link with the path of the image.
Because $value contains the name of the file you can use end(explode('.',$value)); to find the ext. of the file (php , jpg , gif , png).
Use another condition with the piece of information and you can identify if it's a picture or not.
In order to build the path of the image you'll need to use the $_GET['dir'] variable's value.
For instance:
<a href='<?=$_GET['dir']?>/Flower.gif'>Flower.gif</a>
I hope you got the idea.
I have a function that takes uploaded files (WORDPRESS) and adds them to a (newly created) zip file.
every new file is added to the zip (if is not yet created - the first file will create one ) and also to a comment with the list of the files.
function Ob99_generate_zip_file($meta) {
// we always need post_id , right ?
if( isset($_GET['post_id']) ) {
$post_id = $_GET['post_id'];
} elseif( isset($_POST['post_id']) ) {
$post_id = $_POST['post_id'];
}
//setting some more variables.
$file = wp_upload_dir();// take array
$file2 = wp_upload_dir();//debug
$zipname = $file['path'].'file.zip'; // set zip file name
$file = trailingslashit($file['basedir']).$meta['file'];// construct real path
// Without this next condition the function dies. WHY ??
list($orig_w, $orig_h, $orig_type) = #getimagesize($file); // not help to comment
if (!$orig_type == IMAGETYPE_GIF || !$orig_type == IMAGETYPE_PNG|| !$orig_type == IMAGETYPE_JPEG) {
//why other filetypes not working ??
return ;
}
$zip = new ZipArchive; // initiatte class
$zip->open($zipname , ZipArchive::CREATE); // open buffer
$new_filename = substr($file,strrpos($file,'/') + 1); //we do not need nested folders
$zip->addFile($file,$sitename.'/'.$new_filename); // we add the file to the zip
if (file_exists($zipname)){
$comment = $zip->getArchiveComment(); // if the file already exist read the comment
}
else { // if not - let´s give it a cool retro header
$comment_head = '*********************************'. PHP_EOL ;
$comment_head .= '****** <<< FILE CONTENT >>> *****'. PHP_EOL ;
$comment_head .= '*********************************'. PHP_EOL ;
}
$comment = $comment_head . $comment ;// add header before comment
$comment = $comment . PHP_EOL . PHP_EOL . $meta['file'] ; // add new file name
$zip->setArchiveComment($comment); // and comment
$zip->addFromString('filelist.txt', $comment); // create txt file with the same list
$zip->close()or die('can not create zip file'.$file.print_r($meta).'---- DEBUG SEPERATOR ---- '.print_r($file2)); // FINISHED or DIE with debug
}
My problem : if I try to upload any file other than an image - the function will DIE .
I have added a condition for checking imagetype - but I would like to know why it is crashing and how to make it work without said condition ...
Does the zip function have any problems with PDF , doc or anyother ? is that a wordpress problem ?
The problem section seems to be where you're asking PDFs, etc. their image size. Why don't you try:
$image_size = getimagesize($file);
if($image_size===false)
{
// This is not an image
// Do what you want to PDFs, etc.
}
else
{
// This is an image
// Find out image type, dimensions, etc.
}
The script below takes a named file that resides in the "myplugin" folder (the folder that the script itself resides in) and runs file_get_contents() on it to load the contents into memory, then does some preprocessing on the contents before finally inserting it as a post into the WordPress database via the wp_insert_post method.
$my_post3 = array();
$my_post3['post_title'] = 'Privacy Policy';
if(file_exists(ABSPATH.'/wp-content/plugins/myplugin/pages/privacy_policy.txt'))
{
$my_privacy_policy = file_get_contents(ABSPATH.'/wp-content/plugins/myplugin/pages/privacy_policy.txt');
}
else
{
$my_privacy_policy = "";
}
$my_post3['post_content'] = addslashes($my_post3_replace);
$my_post3['post_type'] = 'page';
$my_post3['post_status'] = 'publish';
wp_insert_post($my_post3);
This method works pretty good. However, this method forces me to write a different routine for every file I want to use as the basis of a new page.
What I would like to do instead, is create a folder called "pages" and place my .txt files in that, then run a for loop on the contents of the folder, creating a new page for each file in the folder. I'd like to use the file name (minus the .txt extension) as the name of the page.
For example, the pages folder may have these files:
About Us.txt
Contact Us.txt
And the routine would result in the creation of two new pages in WordPress site, one called "About Us" containing the content found in that file. The other page would of course be "Contact Us" with the contents of that file.
In this way, I can just drop an unlimited number of named and prepopulated .txt files into that folder and when I activate my plugin, it creates those pages.
I just need some help with the for loop and how to reference the folder and files.
I will also have a folder called "posts", which will do the same for posts that this routine does for pages.
Thanks in advance for your help and suggestions.
Update based on #clientbucket answer:
DEFINE ('PAGES', './pages/');
$directory_pages = new DirectoryIterator(PAGES);
foreach ($directory_pages as $files) {
if ($files_pages->isFile()) {
$file_name_page = $files_pages->getFilename();
$my_page_content = file_get_contents(PAGES. $file_name_page);
$my_page['post_content'] = addslashes($my_page_content);
$my_page['post_title'] = $file_name_page;
$my_page['post_type'] = 'page';
$my_page['post_status'] = 'publish';
wp_insert_post($my_page);
}
}
DEFINE ('POSTS', './posts/');
$directory_posts = new DirectoryIterator(POSTS);
foreach ($directory_posts as $files_posts) {
if ($files_posts->isFile()) {
$file_name_post = $files_posts->getFilename();
$my_post_content = file_get_contents(POSTS. $file_name_post);
$my_post['post_content'] = addslashes($my_post_content);
$my_post['post_title'] = $file_name_post;
$my_post['post_type'] = 'post';
$my_post['post_status'] = 'publish';
$post_id = wp_insert_post($my_post);
stick_post($post_id);
}
}
Fatal error: Uncaught exception 'UnexpectedValueException' with message 'DirectoryIterator::__construct(./pages/) [directoryiterator.--construct]: failed to open dir: No such file or directory' in C:\xampplite\htdocs\mytestsite\wp-content\plugins\myplugindirectory\myplugin.php:339
Line 339 is here > $directory_pages = new DirectoryIterator(PAGES);
Here is another way you could try.
DEFINE ('PAGES', './pages/'); //Define the directory path
$directory = new DirectoryIterator(PAGES); //Get all the contents in the directory
foreach ($directory as $files) { //Check that the contents of the directory are each files and then do what you want with them after you have the name of the file.
if ($files->isFile()) {
$file_name = $files->getFilename();
$my_page = file_get_contents(PAGES. $file_name); //Collect the content of the file.
} else {
//Insert nothing into the $my_privacy_policy variable.
}
echo $my_page; // Do what you want with the contents of the file.
}
From the PHP manual here:
http://php.net/manual/en/function.glob.php
They provide this solution for finding all text files in a directory:
<?php
foreach (glob("*.txt") as $filename) {
echo $filename . "\n";
}
?>
Given this example, your actual request is to be able to create a file based on the name in another directory. I'll leave the hard work to you - but this is a simple implementation:
<?php
$source_dir = "/your/directory/with/textfiles";
$target_dir = "/directory/to/create/files/in";
foreach (glob($source_dir . DIRECTORY_SEPARATOR . "*.txt") as $filename) {
$filepart = explode('.',$filename);
file_put_contents($target_dir . DIRECTORY_SEPARATOR . $filepart[0] . ".php");
}
?>