PHP - Display Images
I want to display thumbnails for a picture gallery and when user clicks on image the larger image opens in a new window. I can't find a straight answer on the php.net website. Can someone help?
Similar TutorialsI have this script from http://lampload.com/...,view.download/ (I am not using a database) I can upload images fine, I can view files, but I want to delete them. When I press the delete button, nothing happens
http://www.jayg.co.u...oad_gallery.php
<form>
<?php $dir = dirname(__FILENAME__)."/images/gallery" ; $files1 = scandir($dir); foreach($files1 as $file){ if(strlen($file) >=3){ $foil = strstr($file, 'jpg'); // As of PHP 5.3.0 $foil = $file; $pos = strpos($file, 'css'); if ($foil==true){ echo '<input type="checkbox" name="filenames[]" value="'.$foil.'" />'; echo "<img width='130' height='38' src='images/gallery/$file' /><br/>"; // for live host //echo "<img width='130' height='38' src='/ABOOK/SORTING/gallery-dynamic/images/gallery/ $file' /><br/>"; } } }?> <input type="submit" name="mysubmit2" value="Delete"> </form>
any ideas please?
thanks
I'm creating a funeral home site and on the side of the page I would like to display the last 5 funeral obituaries that are in mySQL database (name and certain sized image (images are in "image" field) w/ a link to an "obituaries detail page for the individual deceased person"). I am able to do this successfully listing only the names....how can I list the image associated with the name? This is what I have so far: Code: [Select] <?php include("connect.php"); ?> Code: [Select] <?php $query = "SELECT id, deceased_name, deceased_date, DATE_FORMAT(deceased_date, '%M %D, %Y') as datetext"; $query .= " FROM scales_obits ORDER BY deceased_date DESC LIMIT 5"; $listings = mysql_query($query); if (!listings) { echo("<p>Error retrieving listings from lookup table<br>". "Error: " . mysql_error()); exit(); } echo("<table border=\"0\" width=\"100%\" class=\"obit\">"); while ($listing = mysql_fetch_array($listings)) { $deceased_name = $listing["deceased_name"]; $deceased_date = $listing["datetext"]; $id = $listing["id"]; echo("<tr><td width=\"100%\"><a href=\"obitdetail.php?id=".$id."\"><strong>".$deceased_name."</strong></a></td><td> </td>"); } echo("</table>"); ?> I am looking to display image paths in a row separated by commas. There are 6 images that goes to each user and I would like only the 6 images at be in each " " Like this: "images/listings/listing_516013019A-only.jpg,images/listings/listing_848813453A-1.jpg,images/listings/listing_664613453A-2.jpg,images/listings/listing_520313453A-3.jpg,images/listings/listing_690513453A-4.jpg,images/listings/listing_125113453A-5.jpg,images/listings/listing_641013453A-6.jpg," "images/listings/listing_736913186A-1.jpg,images/listings/listing_822713186A-2.jpg,images/listings/listing_136513186A-3.jpg,images/listings/listing_700313186A-4.jpg,images/listings/listing_716013186A-5.jpg,images/listings/listing_213113186A-6.jpg," "images/listings/listing_292113254A..-1.jpg,images/listings/listing_854413254A..-2.jpg,images/listings/listing_446013254A..-3.jpg,images/listings/listing_676313254A..-4.jpg,images/listings/listing_563413254A..-5.jpg,images/listings/listing_341513254A..-6.jpg," Right now it is displaying them like this "images/listings/listing_516013019A-only.jpg," "images/listings/listing_848813453A-1.jpg," "images/listings/listing_664613453A-2.jpg," "images/listings/listing_520313453A-3.jpg," "images/listings/listing_690513453A-4.jpg," "images/listings/listing_125113453A-5.jpg," "images/listings/listing_641013453A-6.jpg," "images/listings/listing_736913186A-1.jpg," "images/listings/listing_822713186A-2.jpg," "images/listings/listing_136513186A-3.jpg," "images/listings/listing_700313186A-4.jpg," "images/listings/listing_716013186A-5.jpg," "images/listings/listing_213113186A-6.jpg," "images/listings/listing_292113254A..-1.jpg," "images/listings/listing_854413254A..-2.jpg," "images/listings/listing_446013254A..-3.jpg," "images/listings/listing_676313254A..-4.jpg," "images/listings/listing_563413254A..-5.jpg," "images/listings/listing_341513254A..-6.jpg," Here is the code I have: Code: [Select] <?php // Make a MySQL Connection mysql_connect("localhost", "xxxxxxxx", "xxxxxxxx") or die(mysql_error()); mysql_select_db("xxxxxxxx") or die(mysql_error()); $result = mysql_query("SELECT * FROM listimages ORDER BY listimages.listingid DESC ") or die(mysql_error()); while($row = mysql_fetch_array($result)) { echo "\""; echo "$row[imagepath],"; echo "\""; echo "<br>"; } ?> My tables for the images is "listimages" and the columns a id (which are the auto_increments) imagepath (which shows the path/image1.jpg) mainimage (which just shows 0 or 1 depending on the picture that is the default for that listing, 1 being default) listingid (shows numbers 1 2 3 etc corresponding to the Id in the listings table to show what images go with what listing) There are up to 6 images for each listing. Any idea how to fix this? I read everywhere where it says not to stoe images in MYSQL but I have a code where I'm trying to display the images. They are all jpegs that are stored in the table. Here is the code Code: [Select] <?php include "dbaptsConfig.php"; include "searchaptsstyle.css"; // test id, you need to replace this with whatever id you want the result from $id = "1"; // what you want to ask the db $query = "SELECT * FROM `apartments` WHERE `id` = ".$id; // actually asking the db $res = mysql_query($query, $ms); // recieving the answer from the db (you can only use this line if there is always only one result, otherwise will give error) $result = mysql_fetch_assoc($res); // if you uncomment the next line it prints out the whole result as an array (prints out the image as weird characters) // print_r($result); // print out specific information (not the whole array) echo "<br/>"; echo "<div id='title'>".$result['title']."<br/></div>"; echo "<br/>"; echo "<div id='description'>".$result['description']."<br /></div>"; echo "<br/>"; echo "<div id='table'><tr>"; echo "<td bgcolor='#FFFFFF' style='color: #000' align='center'> Provider's Phone Number: ".$result['phone']."<br /></td>"; echo "<td bgcolor='#FFFFFF' style='color: #000' align='center'> Provider: ".$result['service']."<br /></td>"; echo "<td bgcolor='#FFFFFF' style='color: #000' align='center'> Borough: ".$result['county']."<br /></td>"; echo "<td bgcolor='#FFFFFF' style='color: #000' align='center'> Town: ".$result['town']."<br /></td>"; echo "<td bgcolor='#FFFFFF' style='color: #000' align='center'> Bedrooms: ".$result['rooms']."</td>"; echo "<td> </td>"; echo "<td bgcolor='#FFFFFF' style='color: #000' align='center'> Bathrooms: ".$result['bath']."<br /></td>"; echo "<td bgcolor='#FFFFFF' style='color: #000' align='center'> Square Footage: ".$result['square']."<br /></td>"; echo "<td bgcolor='#FFFFFF' style='color: #000' align='center'> Rent: ".$result['rent']."<br /></td>"; echo "<td bgcolor='#FFFFFF' style='color: #000' align='center'> Listed On: ".$result['time']."<br /></td>"; echo "</tr></div>"; header("Content-type: image/jpeg"); echo "<td bgcolor='#FFFFFF' style='color: #000' align='center'> Listed On: ".$result['image1']."<br /></td>"; ?> Thanks Hello everyone, I need help figuring out why im not getting images displayed. I have tried everything I could think of and narrowed down the issue. What Im doing id querying urls from DB for my images. Then using md5 to encrypting the url them before display on web page. Here is the code: Code: [Select] $img = @ md5(mysql_result(mysql_query("SELECT `url` FROM `pictures` WHERE `mls`='{$row['mls']}' ORDER BY `id` LIMIT 1",$avenu->link),0)); When html is displayed I get the hash.jpg. The image failed to be loaded. How can i display all the images in a certain directory and echo the image names. So if a new image is uploaded, it will still display without edited the gallery.php file. Cheers. Hi all, Newbie here, i am having a problem to get my images to show which are stored in mysql database as a mediumblob. I get id number to print in table ut am just getting empty square with red cross in where my image should be. Is my code incorrect or is it something else? Appreciate your help with this. I have included both of the pages codes i am using. Thanks Tony image2.php <?php include("common.php"); error_reporting(E_ALL); $link = mysql_connect(host,username,password) or die("Could not connect: " . mysql_error()); mysql_select_db(db) or die(mysql_error()); $sql = "SELECT id FROM photos"; $result = mysql_query("$sql") or die("Invalid query: " . mysql_error()); ?> <table border="1"><tr><td>id</td><td>image</td></tr> <?php while($row=mysql_fetch_assoc($result)){ print '<tr><td>'.$row['id'].'</td><td>'; print '<img src="image1.php?id='.$row['id'].'height="75" width="100"">'; } echo '</td></tr></table>' ?> image1.php <?php ob_start(); include("common.php"); mysql_connect(host,username,password) or die(mysql_error()); mysql_select_db(db) or die(mysql_error()); $query = mysql_query("SELECT imgage FROM photos WHERE id={$_GET['image_id']}"; $row = mysql_fetch_array($query); $content = $row['image']; header('Content-type: image/jpg'); echo $content; } ob_end_flush(); ?> Hi everyone!! I have looked into how the upload script works and this is what i have: Code: [Select] <?php if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; } } } else { echo "Invalid file"; } ?> Which is un-tested at the moment, but let's just say for talking sake it worked 100% what elements of this script would i be looking at to display the files uploaded on to another page, in my case my homepage? ive found as to yet, that the uploads have to be stored on a file somewhere on my server, which i've set up. But i thought it would be just as easy to have a field in my table named upload and display it within the table next to the other results? instead i just get whatever the file name is named.jpg. Any help in looking towards the answer? many thanks in advance guys! I want to retrieve an image id from a db and show the images. I cant get the syntax right for the image tag.Any help appreciated. Code: [Select] function display_covers() { global $wpdb; $query = "select * from wp_cover"; $result = mysql_query($query)or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error()); echo mysql_error(); if (!$result) return false; echo'<div class="wrap"><p>choose from one of the covers below</p></div>'; echo'<div id="main">'; echo'<table class="main" cellpadding="2">'; //echo"<caption>Please choose a book cover</caption>"; ?> <thead><tr><td colspan="5" ><h6 class="main">Book Covers</h6></td></tr> </thead> <?php $i=0; $size=3; echo "<tbody>"; echo "<tr>"; while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) { /* display picture */ ?> <td class="main"> <?php echo"<img src="/Applications/MAMP/htdocs/wordpress_3/wp-content/plugins/Authors2/jackets/"{.$row['pix'].}""/>"; echo"</td>"; $i++; if($i==$size) { echo "</tr><tr>"; $i=0; } } } Hi I tried to write a script: 1) to locate all directories in a directory (1 level) 2) with the function GetImages() I try to display the image(s) in the subfolder there are only images in the subfolder I guess I'm doing something wrong in the GetImages() with the glob function, can anyone check this ? Thanks in advance function GetImages($map) { $files = glob('$map/*.jpg'); //$files = glob("$map/*.*"); for ($i=0; $i<count($files); $i++) { $num = $files[$i]; echo '<img height="50" width="50" src="'.$num.'" />'." <br />"; } } if ($handle = opendir('mystuff')) { /* loop through directory. */ while (false !== ($dir = readdir($handle))) { if($dir != ".." && $dir != "."){ echo '<option value='.$dir.'>'.$dir.'</option><br>'; GetImages($dir); } } closedir($handle); } Hello all, I am having an issue. I have read many articles and help forums, but I cannot find a specific way to help me. My issue is this. I have a php upload form for visitors to upload an image. Now, I would like to know how to get the uploaded images to show up after the upload. Someone suggested to me to call the images. However, I am not sure how to do this. Below is the script for the image upload, which works great for uploading. <?php /* This script can send an email and/or make an entry in a log file There are two variables below - one for an email address and one for a log file Set both variables to the values you want to use If you do not want either an email or log entry, comment out the respective line For example, if you do not want an email sent, put a // in front of the $emailAddress line - same for the $logFile line */ $logFile = $_SERVER['DOCUMENT_ROOT'].'/upload.log'; // full path to your log file $emailaddress = "email@gmail.com"; $home_page = "index.html"; // used for a link to return $uploaddir = "uploads/"; // the directory where files are to be uploaded - include the trailing slash $fileTypeArray = array(".jpg",".gif",".txt"); // enter in all lower case, the script will handle a match with upper case $maxSize = 500000; // maximum file size that can be uploaded - in bytes $maxFileSpace = 50000000; // maximum space that can be used by files matching the $fileTypeArray array in the upload directory - in bytes putenv('TZ=EST5EDT'); // eastern time // change nothing below this line $maxDisplay = $maxSize / 1000; ?> <html><head></head><body> <div style="text-align: center; margin: 100px auto; border: 1px black solid; width:400px;"> <?php // print_r($_FILES); // can be used for debugging $file_name = $_FILES['file']['name']; $file_size = $_FILES['file']['size']; $file_tmp_name = $_FILES['file']['tmp_name']; if (!empty($file_name)) { unset($error); echo "<br>File Name: $file_name<br><br>"; echo "File Size: $file_size bytes<br><br>"; // file size test if ($file_size == 0 ) $error .= "<span style='color: red;'>Invalid file</span><br>"; if ($file_size > $maxSize ) $error .= "<span style='color: red;'>Your file exceeds $maxDisplay K.</span><br>"; // file type test if (!in_array(strtolower(strrchr($file_name,'.')),$fileTypeArray) ) $error .= "<span style='color: red;'>Your file is not a valid file type.</span><br>"; // max directory size test foreach(scandir($uploaddir) as $file_select) if (in_array(strtolower(strstr($file_select,'.')),$fileTypeArray)) $total_size = $total_size + filesize($uploaddir.$file_select); if (($total_size + $file_size) >= $maxFileSpace) $error .= "<span style='color: red;'>Total file space limits have been exceeded.</span><br>"; // scrub characters in the file name $file_name = stripslashes($file_name); $file_name = preg_replace("#[ ]#","_",$file_name); // change spaces to underscore $file_name = preg_replace('#[^()\.\-,\w]#','_',$file_name); //only parenthesis, underscore, letters, numbers, comma, hyphen, period - others to underscore $file_name = preg_replace('#(_)+#','_',$file_name); //eliminate duplicate underscore // check for file already exists if (file_exists($uploaddir.$file_name)) $error .= "<span style='color: red;'>File already exists.</span><br>"; // if all is valid, do the upload if (empty($error)) { if (move_uploaded_file($file_tmp_name,$uploaddir.$file_name)) { chmod($uploaddir.$file_name,0644); echo "<span style='color: green;'>Your file was successfully uploaded!</span>"; if (isset($emailAddress)) { $message = $file_name . " was uploaded by".$_SERVER['REMOTE_ADDR']."at".date('Y-m-d H:i:s'); mail($emailaddress,"You have a file upload",$message,"From: Website <>"); } if (isset($logFile)) { $logData = $file_name."||".$_SERVER['REMOTE_ADDR']."||".date('Y-m-d H:i:s')."\r\n"; @file_put_contents($logFile,$logData,FILE_APPEND|LOCK_EX); } } else { echo "<span style='color: red;'>Your file could not be uploaded.</span>"; } } echo "$error<hr>"; } ?> <p>Upload a <span style="color: blue;"> <?php foreach($fileTypeArray as $fileType) echo $fileType; ?> </span> file to our server<br> Maximum file size is <?php echo $maxDisplay; ?>K</p> <form action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method="post" enctype="multipart/form-data"> File: <input type="file" name="file" style="width: 250px;"><br> <input type="submit" name="submit" value="Upload File"></form> <a href="<?php echo $home_page; ?>">Return to the Home Page</a> </div> What is the method or process to get the images to show up or to pull the images from the folder to a webpage? I have the following code which displays images and captions from a directory. I would like the images to be displayed in the order they were created. Somebody suggested I use glob(), but I have no idea how. <?php $dir = "exclusive_images/"; if ($opendir = opendir($dir)) { //read directory while(($file = readdir($opendir)) !==FALSE) { if ( file_exists($dir.'/'.$file) && in_array( strtolower(pathinfo($file,PATHINFO_EXTENSION )), array('png','jpg','jpeg','gif'))) { if (file_exists($dir.'/'.$file. '.txt')) $caption = file_get_contents($dir.'/'.$file. '.txt'); else $caption = ucwords(str_replace(array('-','_'),' ', substr($file, 0, (strlen ($file)) - (strlen (strrchr($file,'.')))))); echo '<tr><td><img src="' . $dir.'/'.$file .'" alt="'. $file .'" title="' . $file . '" width="200"></td><td>' . $caption . '</td></tr>'; } } } ?> I am trying to display images on a html page alphabetically in descending order by their filename. This script inserts all the images in a directory on the page. Just can't figure out how to maintain this with a sorting option <?php $dir = "./plate_cache"; $handle = opendir($dir); while (($file = readdir($handle))!==false) { if (strpos($file, '.png',1)) { echo "<img id=\"plates\" src=\"/tags/plate_cache/$file\"></a><br />;"; } } closedir($handle); } ?> I have a supplement store that we'll call SiteA . On the homepage there is a list of featured and best selling products with images. I have a separate blog that we'll call SiteB. I want to get the images and the url they link to (for the product page) from SiteA and display them on SiteB. So that when a user is browsing SiteB and they click on one of the product images, it takes them to the correct product page. I have a script where I can manually accomplish this. However, since the content on the homepage of SiteA is always changing, I'd like to automate this process. For example: If you do a google search for "php", then click on "images" at the top, you will see a list of images relevant to PHP. If you click on any one of them, it takes you to that images page. That is what I want to essentially accomplish. Any suggestions? I want to display 3 clickable images in a single row which repeats as long as there is data in the database, so far it is displaying a single clickable image from the database. below is all the code.. <table width="362" border="0"> <?php $sql=mysql_query("select * from `publication` GROUP BY `catsue`") or die(mysql_error()); $num=mysql_num_rows($sql); while($rowfor=mysql_fetch_array($sql)) { $cat=$rowfor['catsue']; $pic=mysql_query("select * from `category` where `catsue`='$cat'") or die(mysql_error()); $picP=mysql_fetch_array($pic); $base=basename($picP['title']); ?> <tr> <td width="352" height="88"><table width="408" border="0"> <tr> <td width="113" rowspan="5"><a href="archive_detail.php?id=<?php echo $rowfor['id'];?>&category=<?php echo $rowfor['catsue'];?>"><img src="ad/pic/<?php echo $base;?>" width="100" height="100" border="0"/></a></td> <td width="94">Title</td> <td width="179" height="1"><?php echo $rowfor['catsue'];?> </td> </tr> <tr> <td> </td> <td width="179" height="3"> </td> </tr> <tr> <td> </td> <td width="179" height="8"> </td> </tr> <tr> <td> </td> <td width="179" height="17"> </td> </tr> <tr> <td> </td> <td width="179" height="36"> </td> </tr> </table></td> </tr> <?php }?> </table> Ok the pagination part is all working fine. but i thought id be able to create a heap variables inside the loop then display the images in a table. the only trouble is all variables are grabbing the same img. i need them to grab the 10 different records. thanks Code: [Select] $sql = "SELECT * FROM mongrels_db.gallery ORDER BY id DESC LIMIT $offset, $rowsperpage "; $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); // while there are rows to be fetched... while ($list = mysql_fetch_array($result)) { $img1=$list['img']; $img2=$list['img']; $img3=$list['img']; $img4=$list['img']; $img5=$list['img']; $img6=$list['img']; $img7=$list['img']; $img8=$list['img']; $img9=$list['img']; $img10=$list['img']; // echo data } // end while echo "<table><tr>"; echo "<td>"."<img src='../gallery/".$img1 ."' width='100' height='100''> "."</td>"; echo "<td>"."<img src='../gallery/".$img2 ."' width='100' height='100''> "."</td>"; echo "<td>"."<img src='../gallery/".$img3 ."' width='100' height='100''> "."</td>"; echo "<td>"."<img src='../gallery/".$img4 ."' width='100' height='100''> "."</td></tr>"; echo "<tr><td>"."<img src='../gallery/".$img5 ."' width='100' height='100''> "."</td>"; echo "<td>"."<img src='../gallery/".$img6 ."' width='100' height='100''> "."</td>"; echo "<td>"."<img src='../gallery/".$img7 ."' width='100' height='100''> "."</td>"; echo "<td>"."<img src='../gallery/".$img8 ."' width='100' height='100''> "."</td>"; echo "<tr><td>"."<img src='../gallery/".$img9 ."' width='100' height='100''> "."</td>"; echo "<td>"."<img src='../gallery/".$img10 ."' width='100' height='100''> "."</td></tr>"; Hi guys its me again, I am having a problem that I cant figure out... Here is my code: <?php $sqlCommand = "SELECT image FROM background"; $query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error()); $sqlCommand2 = "SELECT backgroundimage FROM site"; $query2 = mysqli_query($myConnection, $sqlCommand2) or die (mysqli_error()); while ($row = mysqli_fetch_array($query)) { while ($row2 = mysqli_fetch_array($query2)) { if($row['image'] == $row2['backgroundimage']){ echo '<img src="site_background/'.$row['image'].'" width="75px" height="75px" style="border:2px solid red;" /><br /><br />'; } if($row['image'] != $row2['backgroundimage']){ echo '<img src="site_background/'.$row['image'].'" width="50px" height="50px" style="border:2px solid black;" />'; } } } mysqli_free_result($query); mysqli_free_result($query2); ?> What is will do is get the images from the "backgrounds" table and the image from the "site" table (the current image). I am then wanting to pick out the current image and give it a red border and then display the other left over images smaller with a black border. I can get the images to all display with the black border or the current image to display with a red border but the other images dont show... I have tried mixing things around but I have not been able to get all the images to display with the formatting I want. I dont know if it is a simple syntax error or I am doing things completely wrong... I have been looking at it for so long its just become one big mess of code to me lol Any help to get this working as I want would be great! Cheers Ben Hi, i have a folder with thumbnails and original big pictures of the thumbnails, i wanna make it so that the max amount of thumbs that can be displayed on one page would be 3 Code: [Select] <body> <div id=head></div> <div id=main> <?php include("loadimages.php") ?> //<- here i take all the thumbnails that are in my thumb folder </div> <div id=foot></div> </body> i have 5 thumbnails, it displays all of them in the "main" div, i wanna add an "Next" and "Previous" buttons, i mean, i want it to show only 3 thumbs at one time, once u click "next" it would remove the first 3 thumbs and load the other 2 thumbnails.. heres a pic maybe it will explain better of what im trying to do.. Hi all,
I need some help with my code as I've a trouble with sending the emails with images attachments. I'm using Pear Mail library to send the emails so when I send the emails with attachments to gmail, I am unable to see the attached images in my gmail inbox as there is no images show on the bottom of the subject unless when I open on my email so I can see the images attachments. And I am unable to see the images on yahoo when i sent the emails, so I sent a test email on my webmail with the images as attachments and I can see the images on gmail and yahoo with no problem. I think there is a problem with my PHP script that need to be resolve. //attachments if (is_array($email_attachments)) { foreach ($email_attachments as $attachments) { $filename = str_replace('uploads/', '', $attachments); $attachment = ''; $file_path = ''; $type = ''; if (strpos($filename, '.png') !== false) { $type .= 'image/png'; } // ADD attachment(s) $attachment1 .= "--$boundary1\r\n"; $attachment1 .= "Content-Type: $type; name=\"$filename\"\r\n"; $attachment1 .= "Content-Transfer-Encoding: base64\r\n"; $attachment1 .= "Content-Disposition: attachment; filename=\"$filename\"\r\n"; $attachment1 .= "\r\n\r\n"; $attachment1 .= $attachment; $attachment1 .= "\r\n\r\n"; $body .= $attachment1; $mime->addAttachment($file_path, $type); } }
Here is the full code: <?php require_once('Mail.php'); require_once('Mail/mime.php'); require_once('Mail/IMAPv2.php'); ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); //Connect to the database include('config.php'); // Connect to the server: $username = 'myusername'; $password = 'mypassword'; $smtp_hostname = "smtp.mydomain.com"; $port = "587"; $attached_files = array(); $inline_images = array(); global $inline_images; if (isset($_POST['send_to'])) { $from = "Mark <name@mydomain.com>"; $to_email = $_POST['send_to']; $subject = $_POST['email_subject']; $message ='<div dir="ltr">' . $_POST['email_body'] . '</div>'; $email_attachments = $_POST['email_attachment']; $total_emails = count($to_email); $email_number = $_POST['email_number']; $sent_message = $message; $attachment1 = ''; $inline_id = 0.1; $success = ''; $base64 = []; $src = []; //Check if the images is base64 if (strpos($message, 'data:image/') !== false) { // read all image tags into an array preg_match_all('/<img.*?src="data:image\/.*;.*,(.*)".*?>/i', $message, $match, PREG_PATTERN_ORDER); $base64 = array_pop($match); if (is_array($src)) { foreach($base64 as $images) { $type = end(explode('/', (explode(';', $images))[0])); $filename = md5(time().uniqid()). '.' . $type; $base64_string = str_replace('data:image/png;base64,', '', $images); $base64_string = str_replace(' ', '+', $base64_string); $decoded = base64_decode($base64_string); $fp = fopen("uploads/". $filename, "w+"); fwrite($fp, $decoded); fclose($fp); } } } //check if the inline images is in the array if (strpos($message, '<img src=') !== false) { // read all image tags into an array preg_match_all('@src="([^"]+)"@' , $message, $match); $src = array_pop($match); if (is_array($src)) { foreach ($src as $key => $value) { $parsed = parse_url($src[$key]); $filename = basename($parsed['path']); $content = file_get_contents($src[$key]); if (!file_exists($filename)) { $fp = fopen("uploads/". $filename, "w+"); fwrite($fp, $content); fclose($fp); } } } } $boundary1 = '###'.md5(microtime()).'###'; $boundary2 = '###'.md5(microtime().rand(99,999)).'###'; foreach ($to_email as $to) { $name = ''; $email = ''; if (strpos($to, ' <') !== false) { $name_str = explode(' <', $to); $email_str = explode(' <', $to); $name = $name_str[0]; $email = str_replace('>', '', $email_str); $email = $email[1]; } $messageID = sprintf("<%s.%s@%s>", base_convert(microtime(), 10, 36), base_convert(bin2hex(openssl_random_pseudo_bytes(8)), 16, 36), 'mydomain.com'); $message_id = getMessageid(isset($message_id)); $now = new DateTime(); $email_id = $now->getTimestamp(); $sent_date = date('Y-m-d H:i:s'); $sent_mailbox1 = $link->prepare("SELECT * FROM sent WHERE message_id = ?"); $sent_mailbox1->execute([$message_id]); $emailID = ''; if (!$name == '' && !$email == '') { if ($name == $email) { $to = $email; } } if ($sent_mailbox1->rowCount() == 0) { $sent_mailbox1 = $link->prepare("INSERT INTO sent (from_email, to_email, message_id) VALUES (?,?,?)"); if ($sent_mailbox1->execute([$from, $to, $message_id])) { $emailID = $link->lastInsertId(); } } //check if the images is base64 if (is_array($base64)) { $sent_message .= 'http://mydomain.com/u/?id='.$email_id.'&attid='.$inline_id.'&msgid='.$message_id.'&view=attachment&display=view'; $inline_id += 0.1; } else if (!$base64 == '') { $sent_message .= 'http://mydomain.com/u/?id='.$email_id.'&attid='.$inline_id.'&msgid='.$message_id.'&view=attachment&display=view'; $inline_id += 0.1; } //check if the inline images is in the array if (is_array($src)) { $sent_message .= 'http://mydomain.com/u/?id='.$email_id.'&attid='.$inline_id.'&msgid='.$message_id.'&view=attachment&display=view'; $inline_id += 0.1; } else if (!$src == '') { $sent_message .= 'http://mydomain.com/u/?id='.$email_id.'&attid='.$inline_id.'&msgid='.$message_id.'&view=attachment&display=view'; $inline_id += 0.1; } $message .= '<img src="http://mydomain.com/track/Images/signature.gif?id='.$emailID.'&etc='.time(). '" ' . 'style="width:0;max-height:0;overflow:hidden" alt="">'; $headers = array ('From' => $from, 'To' => $to, 'Subject' => $subject, 'Reply-To' => $from, //'Content-Type' => 'Content-Type: text/plain; charset="UTF-8"', 'Content-Type' => 'Content-Type: multipart/mixed; boundary="=_d909e7abc497193ad3b6636530382391"', 'MIME-Version' => '1.0', 'Received' => 'from mail.mydomain.com', 'Date' => date("r"), 'Message-ID' => '<'.sha1(microtime(true)).'@mydomain.com>'); $crlf = "\r\n"; $mime = new Mail_mime(array('eol' => $crlf)); //$mime = new Mail_mime("\r\n"); $html = $message; $text = strip_tags($html); $body = $html; $mime->setTXTBody($text); $mime->setHTMLBody($html); //check if the img tags have url called display=view if (strpos($message, 'display=view') !== false) { $pattern = '@src="([^"]+)"@'; $message = preg_replace_callback($pattern,"setImageLinks", $message); foreach ($inline_images as $inline_image) { $file_path = $inline_image; $typeInt = imagetype($file_path); //code goes here to find the imagetype case switch ($typeInt) { case IMG_GIF: $imageType = 'image/gif'; break; case IMG_JPG: $imageType = 'image/jpg'; break; case IMG_JPEG: $imageType = 'image/jpeg'; break; case IMG_PNG: $imageType = 'image/png'; break; case IMG_WBMP: $imageType = 'image/wbmp'; break; case IMG_XPM: $imageType = 'image/xpm'; break; default: $imageType = 'unknown'; } $mime->addHTMLImage($file_path, $imageType); } } //attachments if (is_array($email_attachments)) { foreach ($email_attachments as $attachments) { $filename = str_replace('uploads/', '', $attachments); $attachment = ''; $file_path = ''; $type = ''; if (strpos($filename, '.png') !== false) { $type .= 'image/png'; } // ADD attachment(s) $attachment1 .= "--$boundary1\r\n"; $attachment1 .= "Content-Type: $type; name=\"$filename\"\r\n"; $attachment1 .= "Content-Transfer-Encoding: base64\r\n"; $attachment1 .= "Content-Disposition: attachment; filename=\"$filename\"\r\n"; $attachment1 .= "\r\n\r\n"; $attachment1 .= $attachment; $attachment1 .= "\r\n\r\n"; $body .= $attachment1; $mime->addAttachment($file_path, $type); } } // always call these methods in this order $mime_params = array( 'text_encoding' => '7bit', 'text_charset' => '"UTF-8"', 'html_charset' => '"UTF-8"', 'head_charset' => '"UTF-8"' ); //$body = $mime->get(array('text_encoding' => '8bit','html_encoding' => '8bit')); $body = $mime->get($mime_params); $headers = $mime->headers($headers); $smtp_params = array ('host' => $smtp_hostname, 'port' => $port, 'auth' => true, // Note 1 'username' => $username, 'password' => $password); $smtp = Mail::factory('smtp', $smtp_params); $mail = $smtp->send($to, $headers, $body); if (PEAR::isError($mail)) { echo("<p>" . $mail->getMessage() . "</p>"); } else { echo("<p>Email has been sent!</p>"); $response = array("success"=>$success); echo json_encode($response); } } }
Do you know why the images wont show up on yahoo and gmail when I send the images as attachment?
I have checked on the image path and i have put the correct image path so it should work fine.
Any advice would be much appreciated. Thanks in advance.
Edited June 5, 2020 by mark107 |