PHPMailer multiple attachments with one input button - php

I'm trying to make a contact form that is capable of multiple image attachments.
I got the contact form from here and everything's working fine. I really want to add the ability to attach more than one image within a single input element.
At the top of the contact form is this php:
<?PHP
require_once("./include/fgcontactform.php");
$formproc = new FGContactForm();
$formproc->AddRecipient('****#****.com');
$formproc->SetFormRandomKey('************');
$formproc->AddFileUploadField('photo','jpg,jpeg,gif,png,bmp',4000);
if(isset($_POST['submitted']))
{
if($formproc->ProcessForm())
{
$formproc->RedirectToURL("thank-you.php");
}
}
?>
This is the html for the form (I've cut it down so its only the upload portion of the form):
<html>
<head>
<script type='text/javascript' src='scripts/gen_validatorv31.js'></script>
<script type='text/javascript' src='scripts/fg_captcha_validator.js'></script>
</head>
<body>
<form id='contactus' action='<?php echo $formproc->GetSelfScript(); ?>' method='post' enctype="multipart/form-data" accept-charset='UTF-8'>
<h4><label for='photo' >Please upload your images:</label><br/>
<input type="file" name='photo' id='photo' multiple="multiple"/><br/>
<span style="color:#999999;font-size:12px;">(To select more than 1 image hold the "CTRL" key as you click. If you're on Mac hold the "cmd" key.)</span><br/></h4>
<span id='contactus_photo_errorloc' class='error'></span>
</form>
<script type='text/javascript'>
// <![CDATA[
var frmvalidator = new Validator("contactus");
frmvalidator.EnableOnPageErrorDisplay();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Please provide your name");
frmvalidator.addValidation("email","req","Please provide your email address");
frmvalidator.addValidation("email","email","Please provide a valid email address");
frmvalidator.addValidation("message","maxlen=2048","The message is too long!(more than 2KB!)");
frmvalidator.addValidation("photo","file_extn=jpg;jpeg;gif;png;bmp","Upload images only. Supported file types are: jpg,gif,png,bmp");
// ]]>
</script>
</body>
</html>
I have managed to get multiple image uploads working by adding the following to the top of the initial PHP and adding new input elements within the html with the relevant names:
$formproc->AddFileUploadField('photo2','jpg,jpeg,gif,png,bmp',4000);
$formproc->AddFileUploadField('photo3','jpg,jpeg,gif,png,bmp',4000);
$formproc->AddFileUploadField('photo4','jpg,jpeg,gif,png,bmp',4000);
$formproc->AddFileUploadField('photo5','jpg,jpeg,gif,png,bmp',4000);
Although this works I'd much prefer to have only one input button and allow people to attach multiple images with it (with a max of around 10, but that's an issue for another time).
I believe this is the php that composes the email if that helps:
<?PHP
require_once("class.phpmailer.php");
class FG_CaptchaHandler
{
function Validate() { return false;}
function GetError(){ return '';}
}
class FGContactForm
{
var $receipients;
var $errors;
var $error_message;
var $name;
var $email;
var $message;
var $from_address;
var $form_random_key;
var $conditional_field;
var $arr_conditional_receipients;
var $fileupload_fields;
var $captcha_handler;
var $mailer;
function FGContactForm()
{
$this->receipients = array();
$this->errors = array();
$this->form_random_key = 'HTgsjhartag';
$this->conditional_field='';
$this->arr_conditional_receipients=array();
$this->fileupload_fields=array();
$this->mailer = new PHPMailer();
$this->mailer->CharSet = 'utf-8';
}
function EnableCaptcha($captcha_handler)
{
$this->captcha_handler = $captcha_handler;
session_start();
}
function AddRecipient($email,$name="")
{
$this->mailer->AddAddress($email,$name);
}
function SetFromAddress($from)
{
$this->from_address = $from;
}
function SetFormRandomKey($key)
{
$this->form_random_key = $key;
}
function GetSpamTrapInputName()
{
return 'sp'.md5('KHGdnbvsgst'.$this->GetKey());
}
function SafeDisplay($value_name)
{
if(empty($_POST[$value_name]))
{
return'';
}
return htmlentities($_POST[$value_name]);
}
function GetFormIDInputName()
{
$rand = md5('TygshRt'.$this->GetKey());
$rand = substr($rand,0,20);
return 'id'.$rand;
}
function GetFormIDInputValue()
{
return md5('jhgahTsajhg'.$this->GetKey());
}
function SetConditionalField($field)
{
$this->conditional_field = $field;
}
function AddConditionalReceipent($value,$email)
{
$this->arr_conditional_receipients[$value] = $email;
}
function AddFileUploadField($file_field_name,$accepted_types,$max_size)
{
$this->fileupload_fields[] =
array("name"=>$file_field_name,
"file_types"=>$accepted_types,
"maxsize"=>$max_size);
}
function ProcessForm()
{
if(!isset($_POST['submitted']))
{
return false;
}
if(!$this->Validate())
{
$this->error_message = implode('<br/>',$this->errors);
return false;
}
$this->CollectData();
$ret = $this->SendFormSubmission();
return $ret;
}
function RedirectToURL($url)
{
header("Location: $url");
exit;
}
function GetErrorMessage()
{
return $this->error_message;
}
function GetSelfScript()
{
return htmlentities($_SERVER['PHP_SELF']);
}
function GetName()
{
return $this->name;
}
function GetEmail()
{
return $this->email;
}
function GetMessage()
{
return htmlentities($this->message,ENT_QUOTES,"UTF-8");
}
function SendFormSubmission()
{
$this->CollectConditionalReceipients();
$this->mailer->CharSet = 'utf-8';
$this->mailer->Subject = "Customer installation competition submition from $this->name";
$this->mailer->From = $this->GetFromAddress();
$this->mailer->FromName = $this->name;
$this->mailer->AddReplyTo($this->email);
$message = $this->ComposeFormtoEmail();
$textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s','',$message)));
$this->mailer->AltBody = #html_entity_decode($textMsg,ENT_QUOTES,"UTF-8");
$this->mailer->MsgHTML($message);
$this->AttachFiles();
if(!$this->mailer->Send())
{
$this->add_error("Failed sending email!");
return false;
}
return true;
}
function CollectConditionalReceipients()
{
if(count($this->arr_conditional_receipients)>0 &&
!empty($this->conditional_field) &&
!empty($_POST[$this->conditional_field]))
{
foreach($this->arr_conditional_receipients as $condn => $rec)
{
if(strcasecmp($condn,$_POST[$this->conditional_field])==0 &&
!empty($rec))
{
$this->AddRecipient($rec);
}
}
}
}
function IsInternalVariable($varname)
{
$arr_interanl_vars = array('scaptcha',
'submitted',
$this->GetSpamTrapInputName(),
$this->GetFormIDInputName()
);
if(in_array($varname,$arr_interanl_vars))
{
return true;
}
return false;
}
function FormSubmissionToMail()
{
$ret_str='';
foreach($_POST as $key=>$value)
{
if(!$this->IsInternalVariable($key))
{
$value = htmlentities($value,ENT_QUOTES,"UTF-8");
$value = nl2br($value);
$key = ucfirst($key);
$ret_str .= "<div class='label'>$key :</div><div class='value'>$value </div>\n";
}
}
foreach($this->fileupload_fields as $upload_field)
{
$field_name = $upload_field["name"];
if(!$this->IsFileUploaded($field_name))
{
continue;
}
$filename = basename($_FILES[$field_name]['name']);
$ret_str .= "<div class='label'>File upload '$field_name' :</div><div class='value'>$filename </div>\n";
}
return $ret_str;
}
function ExtraInfoToMail()
{
$ret_str='';
$ip = $_SERVER['REMOTE_ADDR'];
$ret_str = "<div class='label'>IP address of the submitter:</div><div class='value'>$ip</div>\n";
return $ret_str;
}
function GetMailStyle()
{
$retstr = "\n<style>".
"body,.label,.value { font-family:Arial,Verdana; } ".
".label {font-weight:bold; margin-top:5px; font-size:1em; color:#333;} ".
".value {margin-bottom:15px;font-size:0.8em;padding-left:5px;} ".
"</style>\n";
return $retstr;
}
function GetHTMLHeaderPart()
{
$retstr = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">'."\n".
'<html><head><title></title>'.
'<meta http-equiv=Content-Type content="text/html; charset=utf-8">';
$retstr .= $this->GetMailStyle();
$retstr .= '</head><body>';
return $retstr;
}
function GetHTMLFooterPart()
{
$retstr ='</body></html>';
return $retstr ;
}
function ComposeFormtoEmail()
{
$header = $this->GetHTMLHeaderPart();
$formsubmission = $this->FormSubmissionToMail();
$extra_info = $this->ExtraInfoToMail();
$footer = $this->GetHTMLFooterPart();
$message = $header."Submission details:<p>$formsubmission</p><hr/>$extra_info".$footer;
return $message;
}
function AttachFiles()
{
foreach($this->fileupload_fields as $upld_field)
{
$field_name = $upld_field["name"];
if(!$this->IsFileUploaded($field_name))
{
continue;
}
$filename =basename($_FILES[$field_name]['name']);
$this->mailer->AddAttachment($_FILES[$field_name]["tmp_name"],$filename);
}
}
function GetFromAddress()
{
if(!empty($this->from_address))
{
return $this->from_address;
}
$host = $_SERVER['SERVER_NAME'];
$from ="nobody#$host";
return $from;
}
function Validate()
{
$ret = true;
if(empty($_POST[$this->GetFormIDInputName()]) ||
$_POST[$this->GetFormIDInputName()] != $this->GetFormIDInputValue() )
{
$this->add_error("Automated submission prevention: case 1 failed");
$ret = false;
}
if(!empty($_POST[$this->GetSpamTrapInputName()]) )
{
$this->add_error("Automated submission prevention: case 2 failed");
$ret = false;
}
if(empty($_POST['name']))
{
$this->add_error("Please provide your name");
$ret = false;
}
else
if(strlen($_POST['name'])>50)
{
$this->add_error("Name is too big!");
$ret = false;
}
if(empty($_POST['email']))
{
$this->add_error("Please provide your email address");
$ret = false;
}
else
if(strlen($_POST['email'])>50)
{
$this->add_error("Email address is too big!");
$ret = false;
}
else
if(!$this->validate_email($_POST['email']))
{
$this->add_error("Please provide a valid email address");
$ret = false;
}
if(strlen($_POST['message'])>2048)
{
$this->add_error("Message is too big!");
$ret = false;
}
if(isset($this->captcha_handler))
{
if(!$this->captcha_handler->Validate())
{
$this->add_error($this->captcha_handler->GetError());
$ret = false;
}
}
if(!empty($this->fileupload_fields))
{
if(!$this->ValidateFileUploads())
{
$ret = false;
}
}
return $ret;
}
function ValidateFileType($field_name,$valid_filetypes)
{
$ret=true;
$info = pathinfo($_FILES[$field_name]['name']);
$extn = $info['extension'];
$extn = strtolower($extn);
$arr_valid_filetypes= explode(',',$valid_filetypes);
if(!in_array($extn,$arr_valid_filetypes))
{
$this->add_error("Valid file types are: $valid_filetypes");
$ret=false;
}
return $ret;
}
function ValidateFileSize($field_name,$max_size)
{
$size_of_uploaded_file =
$_FILES[$field_name]["size"]/2048;//size in KBs
if($size_of_uploaded_file > $max_size)
{
$this->add_error("The file is too big. File size should be less than $max_size KB");
return false;
}
return true;
}
function IsFileUploaded($field_name)
{
if(empty($_FILES[$field_name]['name']))
{
return false;
}
if(!is_uploaded_file($_FILES[$field_name]['tmp_name']))
{
return false;
}
return true;
}
function ValidateFileUploads()
{
$ret=true;
foreach($this->fileupload_fields as $upld_field)
{
$field_name = $upld_field["name"];
$valid_filetypes = $upld_field["file_types"];
if(!$this->IsFileUploaded($field_name))
{
continue;
}
if($_FILES[$field_name]["error"] != 0)
{
$this->add_error("Error in file upload; Error code:".$_FILES[$field_name]["error"]);
$ret=false;
}
if(!empty($valid_filetypes) &&
!$this->ValidateFileType($field_name,$valid_filetypes))
{
$ret=false;
}
if(!empty($upld_field["maxsize"]) &&
$upld_field["maxsize"]>0)
{
if(!$this->ValidateFileSize($field_name,$upld_field["maxsize"]))
{
$ret=false;
}
}
}
return $ret;
}
function StripSlashes($str)
{
if(get_magic_quotes_gpc())
{
$str = stripslashes($str);
}
return $str;
}
function Sanitize($str,$remove_nl=true)
{
$str = $this->StripSlashes($str);
if($remove_nl)
{
$injections = array('/(\n+)/i',
'/(\r+)/i',
'/(\t+)/i',
'/(%0A+)/i',
'/(%0D+)/i',
'/(%08+)/i',
'/(%09+)/i'
);
$str = preg_replace($injections,'',$str);
}
return $str;
}
function CollectData()
{
$this->name = $this->Sanitize($_POST['name']);
$this->email = $this->Sanitize($_POST['email']);
$this->message = $this->StripSlashes($_POST['message']);
}
function add_error($error)
{
array_push($this->errors,$error);
}
function validate_email($email)
{
return eregi("^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$", $email);
}
function GetKey()
{
return $this->form_random_key.$_SERVER['SERVER_NAME'].$_SERVER['REMOTE_ADDR'];
}
}
?>

What I do for multiple file/pictures upload is to use an IFRAME for a hidden form, with a file input that would get triggered once you press a button that you can include in your original form. The form is submitted in the iframe (therefore doesn't reload your page) and uploads the files, you can get files' details and add them with javascript to your form (ex. pic1.jpg uploaded, pic2.png uploaded...) I have a code sample, but I'll have to look for it a bit, so try and come up with the code yourself following this strategy.

Related

Illegal string offset 'formId' in repeater gravityform

PLease Help me,
I have this errors
Warning: Illegal string offset 'formId' in
C:\xampp\htdocs\wp-content\plugins\repeater-add-on-for-gravity-forms\class-gf-field-repeater.php
on line 287
Warning: Illegal string offset 'children' in
C:\xampp\htdocs\wp-content\plugins\repeater-add-on-for-gravity-forms\class-gf-field-repeater.php
on line 291
...
if (empty($value)) {
$value['formId'] = $form_id;
if (!empty($repeater_start)) { $value['start'] = $repeater_start; }
if (!empty($repeater_min)) { $value['min'] = $repeater_min; }
if (!empty($repeater_max)) { $value['max'] = $repeater_max; }
if (!empty($repeater_children)) { $value['children'] = $repeater_children; }
$value = json_encode($value);
}
...
Hi I solved adding $value = array() in line 287.
if (empty($value)) {
$value = array();
$value['formId'] = $form_id;
if (!empty($repeater_start)) { $value['start'] = $repeater_start; }
if (!empty($repeater_min)) { $value['min'] = $repeater_min; }
if (!empty($repeater_max)) { $value['max'] = $repeater_max; }
if (!empty($repeater_children)) { $value['children'] = $repeater_children; }
$value = json_encode($value);
}
That's work for me, I hope it could help you.
<?php
class GF_Field_Repeater extends GF_Field {
public $type = 'repeater';
public static function init_admin() {
$admin_page = rgget('page');
if ($admin_page == 'gf_edit_forms' && !empty($_GET['id'])) {
add_action('gform_field_standard_settings' , array('GF_Field_Repeater', 'gform_standard_settings'), 10, 2);
add_action('gform_field_appearance_settings' , array('GF_Field_Repeater', 'gform_appearance_settings'), 10, 2);
add_action('gform_editor_js_set_default_values', array('GF_Field_Repeater', 'gform_set_defaults'));
add_action('gform_editor_js', array('GF_Field_Repeater', 'gform_editor'));
add_filter('gform_tooltips', array('GF_Field_Repeater', 'gform_tooltips'));
}
if ($admin_page == 'gf_entries') {
add_filter('gform_form_post_get_meta', array('GF_Field_Repeater', 'gform_hide_children'));
}
}
public static function init_frontend() {
add_action('gform_form_args', array('GF_Field_Repeater', 'gform_disable_ajax'));
add_action('gform_enqueue_scripts', array('GF_Field_Repeater', 'gform_enqueue_scripts'), 10, 2);
add_filter('gform_pre_render', array('GF_Field_Repeater', 'gform_unhide_children_validation'));
add_filter('gform_pre_validation', array('GF_Field_Repeater', 'gform_bypass_children_validation'));
}
public static function gform_enqueue_scripts($form, $is_ajax) {
if (!empty($form)) {
if (GF_Field_Repeater::get_field_index($form) !== false) {
wp_enqueue_script('gforms_repeater_postcapture_js', plugins_url('js/jquery.postcapture.min.js', __FILE__), array('jquery'), '0.0.1');
wp_enqueue_script('gforms_repeater_js', plugins_url('js/gf-repeater.min.js', __FILE__), array('jquery'), GF_REPEATER_VERSION);
wp_enqueue_style('gforms_repeater_css', plugins_url('css/gf-repeater.css', __FILE__), array(), GF_REPEATER_VERSION);
}
}
}
public function get_form_editor_field_title() {
return 'Repeater';
}
public function get_form_editor_field_settings() {
return array(
'admin_label_setting',
'css_class_setting',
'description_setting',
'error_message_setting',
'label_setting',
'prepopulate_field_setting'
);
}
public static function gform_set_defaults() {
echo "
case \"repeater\" :
field.label = \"Repeater\";
break;
";
}
public static function gform_standard_settings($position, $form_id) {
if ($position == 1600) {
echo "<li class=\"repeater_settings field_setting\">
<label for=\"field_repeater_start\">Start ";
gform_tooltip('form_field_repeater_start');
echo " </label>
<input type=\"number\" id=\"field_repeater_start\" min=\"1\" value=\"1\" onchange=\"SetFieldProperty('start', this.value);\">
</li>";
echo "<li class=\"repeater_settings field_setting\">
<label for=\"field_repeater_min\">Min ";
gform_tooltip('form_field_repeater_min');
echo " </label>
<input type=\"number\" id=\"field_repeater_min\" min=\"1\" value=\"1\" onchange=\"SetFieldProperty('min', this.value);\">
</li>";
echo "<li class=\"repeater_settings field_setting\">
<label for=\"field_repeater_max\">Max ";
gform_tooltip('form_field_repeater_max');
echo " </label>
<input type=\"number\" id=\"field_repeater_max\" min=\"1\" onchange=\"SetFieldProperty('max', this.value);\">
</li>";
}
}
public static function gform_appearance_settings($position, $form_id) {
if ($position == 400) {
echo "<li class=\"repeater_settings field_setting\">
<input type=\"checkbox\" id=\"field_repeater_hideLabel\" onchange=\"SetFieldProperty('hideLabel', this.checked);\">
<label for=\"field_repeater_hideLabel\" class=\"inline\">Hide Label & Description ";
gform_tooltip('form_field_repeater_hideLabel');
echo " </label>
</li>";
}
}
public static function gform_editor() {
echo "<script type=\"text/javascript\">
fieldSettings['repeater'] += ', .repeater_settings';
jQuery(document).bind('gform_load_field_settings', function(event, field, form){
jQuery('#field_repeater_start').val(field['start']);
jQuery('#field_repeater_min').val(field['min']);
jQuery('#field_repeater_max').val(field['max']);
jQuery('#field_repeater_hideLabel').prop('checked', field['hideLabel']);
});
</script>";
}
public static function gform_tooltips($tooltips) {
$tooltips['form_field_repeater_start'] = "The number of times the repeater will be repeated when the form is rendered. Leaving this field blank or setting it to a number higher than the maximum number is the same as setting it to 1.";
$tooltips['form_field_repeater_min'] = "The minimum number of times the repeater is allowed to be repeated. Leaving this field blank or setting it to a number higher than the maximum field is the same as setting it to 1.";
$tooltips['form_field_repeater_max'] = "The maximum number of times the repeater is allowed to be repeated. Leaving this field blank or setting it to a number lower than the minimum field is the same as setting it to unlimited.";
$tooltips['form_field_repeater_hideLabel'] = "If this is checked, the repeater label and description will not be shown to users on the form.";
return $tooltips;
}
function validate($value, $form) {
$repeater_required = $this->repeaterRequiredChildren;
if (!empty($repeater_required)) {
$dataArray = json_decode($value, true);
foreach ($form['fields'] as $key=>$value) {
$fieldKeys[$value['id']] = $key;
if (is_array($value['inputs'])) {
foreach ($value['inputs'] as $inputKey=>$inputValue) {
$inputKeys[$value['id']][$inputValue['id']] = $inputKey;
}
}
}
if ($dataArray['repeatCount'] < $this->min) {
$this->failed_validation = true;
$this->validation_message = "A minimum number of ".$this->min." is required.";
return;
}
if ($this->max && $dataArray['repeatCount'] > $this->max) {
$this->failed_validation = true;
$this->validation_message = "A maximum number of ".$this->max." is allowed.";
return;
}
for ($i = 1; $i < $dataArray['repeatCount'] + 1; $i++) {
foreach ($dataArray['children'] as $field_id=>$field) {
$inputNames = $field['inputs'];
$repeatSkips = $field['conditionalLogic']['skip'];
if (!is_array($inputNames)) { continue; }
if (is_array($repeatSkips)) {
if (in_array($i, $repeatSkips) || in_array('all', $repeatSkips)) { continue; }
}
foreach ($inputNames as $inputName) {
if (is_array($inputName)) { $inputName = reset($inputName); }
if (substr($inputName, -2) == '[]') {
$getInputName = substr($inputName, 0, strlen($inputName) - 2).'-'.$dataArray['repeaterId'].'-'.$i;
} else {
$getInputName = $inputName.'-'.$dataArray['repeaterId'].'-'.$i;
}
$getInputName = str_replace('.', '_', strval($getInputName));
$getInputData = rgpost($getInputName);
$getInputIdNum = preg_split("/(_|-)/", $getInputName);
if (in_array($getInputIdNum[1], $repeater_required)) {
$fieldKey = $fieldKeys[$getInputIdNum[1]];
$fieldType = $form['fields'][$fieldKey]['type'];
$failedValidation = false;
switch($fieldType) {
case 'name':
$requiredIDs = array(3, 6);
if (in_array($getInputIdNum[2], $requiredIDs) && empty($getInputData)) { $failedValidation = true; }
break;
case 'address':
$skipIDs = array(2);
if (!in_array($getInputIdNum[2], $skipIDs) && empty($getInputData)) { $failedValidation = true; }
break;
default:
if (empty($getInputData)) { $failedValidation = true; }
}
if ($failedValidation) {
$this->failed_validation = true;
if ($this->errorMessage) { $this->validation_message = $this->errorMessage; } else { $this->validation_message = "A required field was left blank."; }
return;
}
}
}
}
}
}
}
public function get_field_content($value, $force_frontend_label, $form) {
if (is_admin()) {
$admin_buttons = $this->get_admin_buttons();
$field_content = "{$admin_buttons}
<div class=\"gf-pagebreak-first gf-pagebreak-container gf-repeater gf-repeater-start\">
<div class=\"gf-pagebreak-text-before\">begin repeater</div>
<div class=\"gf-pagebreak-text-main\"><span>REPEATER</span></div>
<div class=\"gf-pagebreak-text-after\">top of repeater</div>
</div>";
} else {
$field_label = $this->get_field_label($force_frontend_label, $value);
$description = $this->get_description($this->description, 'gsection_description gf_repeater_description');
$hide_label = $this->hideLabel;
$validation_message = ( $this->failed_validation && ! empty( $this->validation_message ) ) ? sprintf( "<div class='gfield_description validation_message'>%s</div>", $this->validation_message ) : '';
if (!empty($field_label)) { $field_label = "<h2 class='gf_repeater_title'>{$field_label}</h2>"; } else { $field_label = ''; }
if ($hide_label) { $field_label = ''; $description = ''; }
$field_content = "<div class=\"ginput_container ginput_container_repeater\">{$field_label}{FIELD}</div>{$description}{$validation_message}";
}
return $field_content;
}
public function get_field_input($form, $value = '', $entry = null) {
if (is_admin()) {
return '';
} else {
$form_id = $form['id'];
$is_entry_detail = $this->is_entry_detail();
$is_form_editor = $this->is_form_editor();
$id = (int) $this->id;
$field_id = $is_entry_detail || $is_form_editor || $form_id == 0 ? "input_$id" : 'input_' . $form_id . "_$id";
$tabindex = $this->get_tabindex();
$repeater_parem = $this->inputName;
$repeater_start = $this->start;
$repeater_min = $this->min;
$repeater_max = $this->max;
$repeater_required = $this->repeaterRequiredChildren;
$repeater_children = $this->repeaterChildren;
if (!empty($repeater_parem)) {
$repeater_parem_value = GFFormsModel::get_parameter_value($repeater_parem, $value, $this);
if (!empty($repeater_parem_value)) { $repeater_start = $repeater_parem_value; }
}
if (!empty($repeater_children)) {
$repeater_children_info = array();
$repeater_parems = GF_Field_Repeater::get_children_parem_values($form, $repeater_children);
foreach($repeater_children as $repeater_child) {
$repeater_children_info[$repeater_child] = array();
$repeater_child_field_index = GF_Field_Repeater::get_field_index($form, 'id', $repeater_child);
if (!empty($repeater_required)) {
if (in_array($repeater_child, $repeater_required)) {
$repeater_children_info[$repeater_child]['required'] = true;
}
}
if (!empty($repeater_parems)) {
if (array_key_exists($repeater_child, $repeater_parems)) {
$repeater_children_info[$repeater_child]['prePopulate'] = $repeater_parems[$repeater_child];
}
}
if ($repeater_child_field_index !== false) {
if ($form['fields'][$repeater_child_field_index]['inputMask']) {
$repeater_children_info[$repeater_child]['inputMask'] = $form['fields'][$repeater_child_field_index]['inputMaskValue'];
} elseif ($form['fields'][$repeater_child_field_index]['type'] == 'phone' && $form['fields'][$repeater_child_field_index]['phoneFormat'] = 'standard') {
$repeater_children_info[$repeater_child]['inputMask'] = "(999) 999-9999";
}
if ($form['fields'][$repeater_child_field_index]['conditionalLogic']) {
$repeater_children_info[$repeater_child]['conditionalLogic'] = $form['fields'][$repeater_child_field_index]['conditionalLogic'];
}
}
}
$repeater_children = $repeater_children_info;
}
if (empty($value)) {
$value['formId'] = $form_id;
if (!empty($repeater_start)) { $value['start'] = $repeater_start; }
if (!empty($repeater_min)) { $value['min'] = $repeater_min; }
if (!empty($repeater_max)) { $value['max'] = $repeater_max; }
if (!empty($repeater_children)) { $value['children'] = $repeater_children; }
$value = json_encode($value);
}
return sprintf("<input name='input_%d' id='%s' type='hidden' class='gform_repeater' value='%s' %s />", $id, $field_id, $value, $tabindex);
}
}
public function get_value_save_entry($value, $form, $input_name, $lead_id, $lead) {
$dataArray = json_decode($value, true);
$value = Array();
for ($i = 1; $i < $dataArray['repeatCount'] + 1; $i++) {
foreach ($dataArray['children'] as $field_id=>$field) {
$inputData = Array();
if (array_key_exists('inputs', $field)) {
$inputNames = $field['inputs'];
$repeatSkips = $field['conditionalLogic']['skip'];
if (is_array($repeatSkips)) {
if (in_array($i, $repeatSkips) || in_array('all', $repeatSkips)) { continue; }
}
if (is_array($inputNames)) {
foreach ($inputNames as $inputName) {
if (substr($inputName, -2) == '[]') {
$getInputName = substr($inputName, 0, strlen($inputName) - 2).'-'.$dataArray['repeaterId'].'-'.$i;
} else {
$getInputName = $inputName.'-'.$dataArray['repeaterId'].'-'.$i;
}
$getInputData = rgpost(str_replace('.', '_', strval($getInputName)));
if (!empty($getInputData)) {
if (is_array($getInputData)) {
foreach ($getInputData as $theInputData) {
$inputData[] = $theInputData;
}
} else {
$inputData[] = $getInputData;
}
}
}
}
} else {
if (GF_Field_Repeater::get_field_type($form, $field_id) == 'section') { $inputData = '[gfRepeater-section]'; }
}
$childValue[$field_id] = $inputData;
}
$value[$i] = $childValue;
}
return maybe_serialize($value);
}
public function get_value_entry_list($value, $entry, $field_id, $columns, $form) {
if (empty($value)) {
return '';
} else {
$dataArray = GFFormsModel::unserialize($value);
$arrayCount = count($dataArray);
if ($arrayCount > 1) { $returnText = $arrayCount.' entries'; } else { $returnText = $arrayCount.' entry'; }
return $returnText;
}
}
public function get_value_entry_detail($value, $currency = '', $use_text = false, $format = 'html', $media = 'screen') {
if (empty($value)) {
return '';
} else {
$dataArray = GFFormsModel::unserialize($value);
$arrayCount = count($dataArray);
$output = "\n";
$count = 0;
$repeatCount = 0;
$display_empty_fields = rgget('gf_display_empty_fields', $_COOKIE);
$form_id = $this->formId;
$get_form = GFFormsModel::get_form_meta_by_id($form_id);
$form = $get_form[0];
foreach ($dataArray as $key=>$value) {
$repeatCount++;
$tableContents = '';
if (!empty($value) && !is_array($value)) {
$save_value = $value;
unset($value);
$value[0] = $save_value;
}
foreach ($value as $childKey=>$childValue) {
$count++;
$childValueOutput = '';
if (empty($display_empty_fields) && count($childValue) == 0) { continue; }
if (is_numeric($childKey)) {
$field_index = GF_Field_Repeater::get_field_index($form, 'id', $childKey);
if ($field_index === false) { continue; }
$entry_title = $form['fields'][$field_index]['label'];
} else {
$entry_title = $childKey;
}
$entry_title = str_replace('[gfRepeater-count]', $repeatCount, $entry_title);
if ($format == 'html') {
if ($childValue == '[gfRepeater-section]') {
if ($media == 'email') {
$tableStyling = ' style="font-size:14px;font-weight:bold;background-color:#eee;border-bottom:1px solid #dfdfdf;padding:7px 7px"';
} else {
$tableStyling = ' class="entry-view-section-break"';
}
} else {
if ($media == 'email') {
$tableStyling = ' style="background-color:#EAF2FA;font-family:sans-serif;font-size:12px;font-weight:bold"';
} else {
$tableStyling = ' class="entry-view-field-name"';
}
}
$tableContents .= "<tr>\n<td colspan=\"2\"".$tableStyling.">".$entry_title."</td>\n</tr>\n";
} else {
$tableContents .= $entry_title.": ";
}
if (is_array($childValue)) {
if (count($childValue) == 1) {
$childValueOutput = $childValue[0];
} elseif (count($childValue) > 1) {
if ($format == 'html') {
if ($media == 'email') {
$childValueOutput = "<ul style=\"list-style:none;margin:0;padding:0;\">\n";
} else {
$childValueOutput = "<ul>\n";
}
}
foreach ($childValue as $childValueData) {
if ($format == 'html') {
$childValueOutput .= "<li>".$childValueData."</li>";
} else {
$childValueOutput .= $childValueData."\n";
}
}
if ($format == 'html') { $childValueOutput .= "</ul>\n"; }
}
if ($media == 'email') { $tableStyling = ''; } else { $tableStyling = ' class=\"entry-view-field-value\"'; }
if ($format == 'html') {
$tableContents .= "<tr>\n<td colspan=\"2\"".$tableStyling.">".$childValueOutput."</td>\n</tr>\n";
} else {
$tableContents .= $childValueOutput."\n";
}
}
}
if (!empty($tableContents)) {
if ($format == 'html') {
if ($media == 'email') { $tableStyling = ' width="100%" border="0" cellpadding="5" bgcolor="#FFFFFF"'; } else { $tableStyling = ' class="widefat fixed entry-detail-view"'; }
$output .= "<table cellspacing=\"0\"".$tableStyling.">\n";
$output .= $tableContents;
$output .= "</table>\n";
} else {
$output .= $tableContents."\n";
}
}
}
}
if ($count !== 0) {
if ($format == 'text') { $output = rtrim($output); }
return $output;
} else { return ''; }
}
public function get_value_merge_tag($value, $input_id, $entry, $form, $modifier, $raw_value, $url_encode, $esc_html, $format, $nl2br) {
$output = GF_Field_Repeater::get_value_entry_detail($raw_value, '', false, $format, 'email');
$output = preg_replace("/[\r\n]+/", "\n", $output);
return trim($output);
}
public function get_value_export($entry, $input_id = '', $use_text = false, $is_csv = false) {
if (empty($input_id)) { $input_id = $this->id; }
$output = rgar($entry, $input_id);
$output = GF_Field_Repeater::get_value_entry_detail($output, '', false, 'text', 'email');
$output = preg_replace("/[\r\n]+/", ", ", trim($output));
return $output;
}
public static function gform_hide_children($form) {
$form_id = $form['id'];
$repeaterChildren = Array();
$grid_modified = false;
$grid_meta = GFFormsModel::get_grid_column_meta($form_id);
foreach($form['fields'] as $key=>$field) {
if ($field->type == 'repeater') {
if (is_array($field->repeaterChildren)) { $repeaterChildren = array_merge($repeaterChildren, $field->repeaterChildren); }
} elseif ($field->type == 'repeater-end') { array_push($repeaterChildren, $field->id); }
if (!empty($repeaterChildren)) {
if (in_array($field->id, $repeaterChildren)) {
unset($form['fields'][$key]);
if (is_array($grid_meta)) {
$grid_pos = array_search($field->id, $grid_meta);
if ($grid_pos) {
$grid_modified = true;
unset($grid_meta[$grid_pos]);
}
}
}
}
}
if ($grid_modified) { GFFormsModel::update_grid_column_meta($form_id, $grid_meta); }
$form['fields'] = array_values($form['fields']);
return $form;
}
public static function gform_disable_ajax($args) {
$get_form = GFFormsModel::get_form_meta_by_id($args['form_id']);
$form = reset($get_form);
if (GF_Field_Repeater::get_field_index($form) !== false) {
$args['ajax'] = false;
}
return $args;
}
public static function gform_bypass_children_validation($form) {
if (GF_Field_Repeater::get_field_index($form) === false) { return $form; }
$repeaterChildren = Array();
foreach($form['fields'] as $key=>$field) {
if ($field->type == 'repeater') {
if (is_array($field->repeaterChildren)) { $repeaterChildren = array_merge($repeaterChildren, $field->repeaterChildren); }
}
if (!empty($repeaterChildren)) {
if (in_array($field->id, $repeaterChildren) && !$field->adminOnly) {
$form['fields'][$key]['adminOnly'] = true;
$form['fields'][$key]['repeaterChildValidationHidden'] = true;
}
}
}
return $form;
}
public static function gform_unhide_children_validation($form) {
if (GF_Field_Repeater::get_field_index($form) === false) { return $form; }
foreach($form['fields'] as $key=>$field) {
if ($field->repeaterChildValidationHidden) {
$form['fields'][$key]['adminOnly'] = false;
$form['fields'][$key]['repeaterChildValidationHidden'] = false;
}
}
return $form;
}
public static function get_field_index($form, $key = 'type', $value = 'repeater') {
if (is_array($form)) {
if (!array_key_exists('fields', $form)) { return false; }
} else { return false; }
foreach ($form['fields'] as $field_key=>$field_value) {
if (is_object($field_value)) {
if (property_exists($field_value, $key)) {
if ($field_value[$key] == $value) { return $field_key; }
}
}
}
return false;
}
public static function get_field_type($form, $id) {
$field_index = GF_Field_Repeater::get_field_index($form, 'id', $id);
if ($field_index !== false) { return $form['fields'][$field_index]['type']; }
return false;
}
public static function get_children_parems($form, $children_ids) {
foreach($form['fields'] as $key=>$value) {
if (in_array($value['id'], $children_ids)) {
if ($value['inputName']) {
$parems[$value['id']] = $value['inputName'];
} elseif ($value['inputs']) {
foreach($value['inputs'] as $key=>$value) {
if ($value['name']) { $parems[$value['id']] = $value['name']; }
}
}
}
}
if (!empty($parems)) { return $parems; } else { return false; }
}
public static function get_children_parem_values($form, $children_ids) {
global $wp_filter;
$children_parems = GF_Field_Repeater::get_children_parems($form, $children_ids);
if (empty($children_parems)) { return false; }
// Check the URL first
foreach($_GET as $url_key=>$url_value) {
$key = array_search($url_key, $children_parems);
if ($key !== false) {
$parems[$key][0] = $url_value;
} else {
$split_key = preg_split('/\D+\K/', $url_key);
$key = array_search($split_key[0], $children_parems);
if ($key !== false) { $parems[$key][$split_key[1]] = $url_value; }
}
}
// Then check the filters
foreach($wp_filter as $key=>$value) {
$split_key = preg_split('/^gform_field_value_+\K/', $key);
if (!empty($split_key[1])) {
$key1 = array_search($split_key[1], $children_parems);
if ($key1 !== false) {
$parems[$key1][0] = apply_filters($key, '');
} else {
$split_key2 = preg_split('/\D+\K/', $split_key[1]);
$key2 = array_search($split_key2[0], $children_parems);
if ($key2 !== false) { $parems[$key2][$split_key2[1]] = apply_filters($key, ''); }
}
}
}
if (!empty($parems)) { return $parems; } else { return false; }
}
}
GF_Fields::register(new GF_Field_Repeater());

Disable radio button based on PHP function

I want to call the javascript function based on the result coming from a PHP script.
if ($verify == 'Y' and $approve== 'Y' and $approve_2=='Y') {
$state = "disable";
} else {
$state = "undisable";
}
Below is my javascript function
function disable() {
document.getElementById("approvedd1").disabled = true;
document.getElementById("approvedd2").disabled = true;
}
function undisable() {
document.getElementById("approvedd1").disabled = false;
document.getElementById("approvedd2").disabled = false;
}
document.onreadystatechange = <?php echo $state; ?>()
This does not work.
I want to call function that can disable radio button, when the page has loaded.
The current output of your java script will be
function disable() {
document.getElementById("approvedd1").disabled = true;
document.getElementById("approvedd2").disabled = true;
}
function undisable() {
document.getElementById("approvedd1").disabled = false;
document.getElementById("approvedd2").disabled = false;
}
document.onreadystatechange = disabled/undisabled()
better you can try
php
if ($verify == 'Y' and $approve== 'Y' and $approve_2=='Y') {
$state = "true";
} else {
$state = "false";
}
Java Script
document.onreadystatechange = MyFun() {
document.getElementById("approvedd1").disabled = <?php echo $state; ?>;
document.getElementById("approvedd2").disabled = <?php echo $state; ?>;
}

php whois stopped working on another server

I am using this whois class, it works fine on one server but it does not work properly on another server with the same PHP version 5.4, on first server it returns domain name status correctly, but on the other one it returns just one status: "domain name is not available" while the domain name is actually available.
<?
class Whois_domain {
var $possible_tlds;
var $whois_server;
var $free_string;
var $whois_param;
var $domain;
var $tld;
var $compl_domain;
var $full_info;
var $msg;
var $info;
var $os_system = "linux"; // switch between "linux" and "win"
function Whois_domain() {
$this->info = "";
$this->msg = "";
}
function process() {
if ($this->create_domain()) {
if ($this->full_info == "yes") {
$this->get_domain_info();
} else {
if ($this->check_only() == 1) {
$this->msg = "The domain name: <b>".$this->compl_domain."</b> is free.";
return true;
} elseif ($this->check_only() == 0) {
$this->msg = "The domain name: <b>".$this->compl_domain."</b> is not available";
return false;
} else {
$this->msg = "There was something wrong, try it again.";
}
}
} else {
$this->msg = "Only letters, numbers and hyphens (-) are valid!";
}
}
function check_entry() {
if (preg_match("/^([a-z0-9]+(\-?[a-z0-9]*)){2,63}$/i", $this->domain)) {
return true;
} else {
return false;
}
}
function create_tld_select() {
$menu = "<select name=\"tld\" style=\"margin-left:0;\">\n";
foreach ($this->possible_tlds as $val) {
$menu .= " <option value=\"".$val."\"";
$menu .= (isset($_POST['tld']) && $_POST['tld'] == $val) ? " selected=\"selected\">" : ">";
$menu .= $val."</option>\n";
}
$menu .= "</select>\n";
return $menu;
}
function create_domain() {
if ($this->check_entry()) {
$this->domain = strtolower($this->domain);
$this->compl_domain = $this->domain.".".$this->tld;
return true;
} else {
return false;
}
}
function check_only() {
$data = $this->get_whois_data();
if (is_array($data)) {
$found = 0;
foreach ($data as $val) {
if (eregi($this->free_string, $val)) {
$found = 1;
}
}
return $found;
} else {
$this->msg = "Error, please try it again.";
}
}
function get_domain_info() {
if ($this->create_domain()) {
$data = ($this->tld == "nl") ? $this->get_whois_data(true) : $this->get_whois_data();
if (is_array($data)) {
foreach ($data as $val) {
if (eregi($this->free_string, $val)) {
$this->msg = "The domain name: <b>".$this->compl_domain."</b> is free.";
$this->info = "";
break;
}
$this->info .= $val;
}
} else {
$this->msg = "Error, please try it again.";
}
} else {
$this->msg = "Only letters, numbers and hyphens (-) are valid!";
}
}
function get_whois_data($empty_param = false) {
// the parameter is new since version 1.20 and is used for .nl (dutch) domains only
if ($empty_param) {
$this->whois_param = "";
}
if ($this->tld == "de") $this->os_system = "win"; // this tld must be queried with fsock otherwise it will not work
if ($this->os_system == "win") {
$connection = #fsockopen($this->whois_server, 43);
if (!$connection) {
unset($connection);
$this->msg = "Can't connect to the server!";
return;
} else {
sleep(2);
fputs($connection, $this->whois_param.$this->compl_domain."\r\n");
while (!feof($connection)) {
$buffer[] = fgets($connection, 4096);
}
fclose($connection);
}
} else {
$string = "whois -h ".$this->whois_server." \"".$this->whois_param.$this->compl_domain."\"";
$string = str_replace (";", "", $string).";";
exec($string, $buffer);
}
if (isset($buffer)) {
//print_r($buffer);
return $buffer;
} else {
$this->msg = "Can't retrieve data from the server!";
}
}
}
?>
I changed files permissions and php versions on the other server, but still the same.
This has been solved, it was fsockopen restrictions on the server, it is fine now.

PHP mail Form redirect URL doesn't work. Webpage is here. (Tried other "SOF" answers)

first of all, I have to say this.I used "Wix" for my website but since it doesn't have function to [img] tag with percentage width.So now I have started making my own website, and that's about 1month ago, when I only knew how to [img src], without any other html knowledge. I forced myself to make this myself so I can make my website exactly as what I want, and now it seems almost done as I uploaded on my hosting server.
The problem is, in my 'order page', after filling out the form, and press 'submit button', it doesn't show the page I attended to show. Just turns out to the first part of order page.
the code I tried is
if(isset($_POST['submitted']))
{
if($formproc->ProcessForm())
{
$formproc->RedirectToURL("http://ljhbunkercom.ipage.com/index/thank-you.php");
}
when fully filled form gets submitted with the submit button, it really sends every information to my mailbox, but thank-you.php doesn't show up.
I tried
if(isset($_POST['submitted']))
{
if($formproc->ProcessForm())
{
$formproc->header("Location: http://ljhbunkercom.ipage.com/index/thank-you.php");
}
( the change is , redirect url -> header location.)
and also, not showing the thank-you page.
I modified free open email form source into my own order page, by combining another open source.
-->http://www.sanwebe.com/2014/04/ajax-contact-form-attachment-jquery-php
this is the source I used, but this works so fine. when filled out all the input text box and pressed the submit button, it shows the thank-you.php.
I think I did something wrong, when I modified it.
I remember I changed this,
htmlentities-> htmlspecialchars
but I don't think this really does that effect.
please help .
My web orderpage is this .
http://ljhbunkercom.ipage.com/index/order.php
(! please do not hack my webpage. )
****What is the problem, and how can I make it show the thank-you.php page when required information have been submitted??****
============== The form class==========
class FG_CaptchaHandler
{
function Validate() { return false;}
function GetError(){ return '';}
}
/*
FGContactForm is a general purpose contact form class
It supports Captcha, HTML Emails, sending emails
conditionally, File atachments and more.
*/
class FGContactForm
{
var $receipients;
var $errors;
var $error_message;
var $name;
var $email;
var $message;
var $from_address;
var $form_random_key;
var $conditional_field;
var $arr_conditional_receipients;
var $fileupload_fields;
var $captcha_handler;
var $mailer;
function FGContactForm()
{
$this->receipients = array();
$this->errors = array();
$this->form_random_key = 'xxxxxxx';
$this->conditional_field='';
$this->arr_conditional_receipients=array();
$this->fileupload_fields=array();
$this->mailer = new PHPMailer();
$this->mailer->CharSet = 'utf-8';
}
function EnableCaptcha($captcha_handler)
{
$this->captcha_handler = $captcha_handler;
session_start();
}
function AddRecipient($email,$name="")
{
$this->mailer->AddAddress($email,$name);
}
function SetFromAddress($from)
{
$this->from_address = $from;
}
function SetFormRandomKey($key)
{
$this->form_random_key = $key;
}
function GetSpamTrapInputName()
{
return 'sp'.md5('xxxxxxxxx'.$this->GetKey());
}
function SafeDisplay($value_name)
{
if(empty($_POST[$value_name]))
{
return'';
}
return htmlspecialchars($_POST[$value_name]);
}
function GetFormIDInputName()
{
$rand = md5('xxxxxxx'.$this->GetKey());
$rand = substr($rand,0,20);
return 'id'.$rand;
}
function GetFormIDInputValue()
{
return md5('xxxxxxx'.$this->GetKey());
}
function SetConditionalField($field)
{
$this->conditional_field = $field;
}
function AddConditionalReceipent($value,$email)
{
$this->arr_conditional_receipients[$value] = $email;
}
function AddFileUploadField($file_field_name,$accepted_types,$max_size)
{
$this->fileupload_fields[] =
array("name"=>$file_field_name,
"file_types"=>$accepted_types,
"maxsize"=>$max_size);
}
function ProcessForm()
{
if(!isset($_POST['submitted']))
{
return false;
}
if(!$this->Validate())
{
$this->error_message = implode('<br/>',$this->errors);
return false;
}
$this->CollectData();
$ret = $this->SendFormSubmission();
return $ret;
}
function RedirectToURL($url)
{
header("Location: $url");
exit;
}
function GetErrorMessage()
{
return $this->error_message;
}
function GetSelfScript()
{
return htmlspecialchars($_SERVER['PHP_SELF']);
}
function GetName()
{
return $this->name;
}
function GetEmail()
{
return $this->email;
}
function GetMessage()
{
return htmlspecialchars($this->message,ENT_QUOTES,"UTF-8");
}
/*-------- Private (Internal) Functions -------- */
function SendFormSubmission()
{
$this->CollectConditionalReceipients();
$this->mailer->CharSet = 'utf-8';
$this->mailer->Subject = "Contact form submission from $this->name";
$this->mailer->From = $this->GetFromAddress();
$this->mailer->FromName = $this->name;
$this->mailer->AddReplyTo($this->email);
$message = $this->ComposeFormtoEmail();
$textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s','',$message)));
$this->mailer->AltBody = #html_entity_decode($textMsg,ENT_QUOTES,"UTF-8");
$this->mailer->MsgHTML($message);
$this->AttachFiles();
if(!$this->mailer->Send())
{
$this->add_error("알수없는 이유로 메일보내기가 실패하였습니다. LJHBUNKER#LJHBUNKER.COM 으로 연락주시길 바랍니다!");
return false;
}
return true;
}
function CollectConditionalReceipients()
{
if(count($this->arr_conditional_receipients)>0 &&
!empty($this->conditional_field) &&
!empty($_POST[$this->conditional_field]))
{
foreach($this->arr_conditional_receipients as $condn => $rec)
{
if(strcasecmp($condn,$_POST[$this->conditional_field])==0 &&
!empty($rec))
{
$this->AddRecipient($rec);
}
}
}
}
/*
Internal variables, that you donot want to appear in the email
Add those variables in this array.
*/
function IsInternalVariable($varname)
{
$arr_interanl_vars = array('scaptcha',
'submitted',
$this->GetSpamTrapInputName(),
$this->GetFormIDInputName()
);
if(in_array($varname,$arr_interanl_vars))
{
return true;
}
return false;
}
function FormSubmissionToMail()
{
$ret_str='';
foreach($_POST as $key=>$value)
{
if(!$this->IsInternalVariable($key))
{
$value = htmlspecialchars($value,ENT_QUOTES,"UTF-8");
$value = nl2br($value);
$key = ucfirst($key);
$ret_str .= "<div class='label'>$key :</div><div class='value'>$value </div>\n";
}
}
foreach($this->fileupload_fields as $upload_field)
{
$field_name = $upload_field["name"];
if(!$this->IsFileUploaded($field_name))
{
continue;
}
$filename = basename($_FILES[$field_name]['name']);
$ret_str .= "<div class='label'>File upload '$field_name' :</div><div class='value'>$filename </div>\n";
}
return $ret_str;
}
function ExtraInfoToMail()
{
$ret_str='';
$ip = $_SERVER['REMOTE_ADDR'];
$ret_str = "<div class='label'>IP address of the submitter:</div><div class='value'>$ip</div>\n";
return $ret_str;
}
function GetMailStyle()
{
$retstr = "\n<style>".
"body,.label,.value { font-family:Arial,Verdana; } ".
".label {font-weight:bold; margin-top:5px; font-size:1em; color:#333;} ".
".value {margin-bottom:15px;font-size:0.8em;padding-left:5px;} ".
"</style>\n";
return $retstr;
}
function GetHTMLHeaderPart()
{
$retstr = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">'."\n".
'<html><head><title></title>'.
'<meta http-equiv=Content-Type content="text/html; charset=utf-8">';
$retstr .= $this->GetMailStyle();
$retstr .= '</head><body>';
return $retstr;
}
function GetHTMLFooterPart()
{
$retstr ='</body></html>';
return $retstr ;
}
function ComposeFormtoEmail()
{
$header = $this->GetHTMLHeaderPart();
$formsubmission = $this->FormSubmissionToMail();
$extra_info = $this->ExtraInfoToMail();
$footer = $this->GetHTMLFooterPart();
$message = $header."Submission from 'contact us' form:<p>$formsubmission</p><hr/>$extra_info".$footer;
return $message;
}
function AttachFiles()
{
foreach($this->fileupload_fields as $upld_field)
{
$field_name = $upld_field["name"];
if(!$this->IsFileUploaded($field_name))
{
continue;
}
$filename =basename($_FILES[$field_name]['name']);
$this->mailer->AddAttachment($_FILES[$field_name]["tmp_name"],$filename);
}
}
function GetFromAddress()
{
if(!empty($this->from_address))
{
return $this->from_address;
}
$host = $_SERVER['SERVER_NAME'];
$from ="nobody#$host";
return $from;
}
function Validate()
{
$ret = true;
//security validations
if(empty($_POST[$this->GetFormIDInputName()]) ||
$_POST[$this->GetFormIDInputName()] != $this->GetFormIDInputValue() )
{
//The proper error is not given intentionally
$this->add_error("Automated submission prevention: case 1 failed");
$ret = false;
}
//This is a hidden input field. Humans won't fill this field.
if(!empty($_POST[$this->GetSpamTrapInputName()]) )
{
//The proper error is not given intentionally
$this->add_error("Automated submission prevention: case 2 failed");
$ret = false;
}
//name validations
if(empty($_POST['name']))
{
$this->add_error(" 이름을 기재하여주세요! ");
$ret = false;
}
else
if(strlen($_POST['name'])>50)
{
$this->add_error(" 이름을 정확히 기재하여 주세요! ");
$ret = false;
}
//email validations
if(empty($_POST['email']))
{
$this->add_error(" E-mail 주소가 입력되지 않았습니다! ");
$ret = false;
}
else
if(strlen($_POST['email'])>50)
{
$this->add_error(" 올바른 E-mail 주소를 “정확히” 입력하여주세요! ");
$ret = false;
}
else
if(!$this->validate_email($_POST['email']))
{
$this->add_error(" 올바른 E-mail 주소를 “정확히” 입력하여주세요! ");
$ret = false;
}
//check validations
if(empty($_POST['message0']))
{
$this->add_error(" 용도를 기입하여 주세요! ");
$ret = false;
}
//message validaions
if(strlen($_POST['message2'])>2048)
{
$this->add_error(" 추가 코멘트가 너무 깁니다! 500자 이내의 분량만 수용이 가능합니다. ");
$ret = false;
}
//file validations
if($_FILES['photo']['size'] == 0 )
{
$this->add_error(" 스케치가 첨부되지 않았습니다! ");
$ret = false;
}
//check validations
if(empty($_POST['check']))
{
$this->add_error(" 커스텀 일러스트 Type을 선택하여주세요! ");
$ret = false;
}
//captcha validaions
if(isset($this->captcha_handler))
{
if(!$this->captcha_handler->Validate())
{
$this->add_error($this->captcha_handler->GetError());
$ret = false;
}
}
//file upload validations
if(!empty($this->fileupload_fields))
{
if(!$this->ValidateFileUploads())
{
$ret = false;
}
}
return $ret;
}
function ValidateFileType($field_name,$valid_filetypes)
{
$ret=true;
$info = pathinfo($_FILES[$field_name]['name']);
$extn = $info['extension'];
$extn = strtolower($extn);
$arr_valid_filetypes= explode(',',$valid_filetypes);
if(!in_array($extn,$arr_valid_filetypes))
{
$this->add_error("Valid file types are: $valid_filetypes");
$ret=false;
}
return $ret;
}
function ValidateFileSize($field_name,$max_size)
{
$size_of_uploaded_file =
$_FILES[$field_name]["size"]/4096;//size in KBs
if($size_of_uploaded_file > $max_size)
{
$this->add_error("스케치파일의 용량이 너무 큽니다! (4메가 초과) ");
return false;
}
return true;
}
function IsFileUploaded($field_name)
{
if(empty($_FILES[$field_name]['name']))
{
return false;
}
if(!is_uploaded_file($_FILES[$field_name]['tmp_name']))
{
return false;
}
return true;
}
function ValidateFileUploads()
{
$ret=true;
foreach($this->fileupload_fields as $upld_field)
{
$field_name = $upld_field["name"];
$valid_filetypes = $upld_field["file_types"];
if(!$this->IsFileUploaded($field_name))
{
continue;
}
if($_FILES[$field_name]["error"] != 0)
{
$this->add_error("Error in file upload; Error code:".$_FILES[$field_name]["error"]);
$ret=false;
}
if(!empty($valid_filetypes) &&
!$this->ValidateFileType($field_name,$valid_filetypes))
{
$ret=false;
}
if(!empty($upld_field["maxsize"]) &&
$upld_field["maxsize"]>0)
{
if(!$this->ValidateFileSize($field_name,$upld_field["maxsize"]))
{
$ret=false;
}
}
}
return $ret;
}
function StripSlashes($str)
{
if(get_magic_quotes_gpc())
{
$str = stripslashes($str);
}
return $str;
}
/*
Sanitize() function removes any potential threat from the
data submitted. Prevents email injections or any other hacker attempts.
if $remove_nl is true, newline chracters are removed from the input.
*/
function Sanitize($str,$remove_nl=true)
{
$str = $this->StripSlashes($str);
if($remove_nl)
{
$injections = array('/(\n+)/i',
'/(\r+)/i',
'/(\t+)/i',
'/(%0A+)/i',
'/(%0D+)/i',
'/(%08+)/i',
'/(%09+)/i'
);
$str = preg_replace($injections,'',$str);
}
return $str;
}
/*Collects clean data from the $_POST array and keeps in internal variables.*/
function CollectData()
{
$this->name = $this->Sanitize($_POST['name']);
$this->email = $this->Sanitize($_POST['email']);
$this->check = $this->Sanitize($_POST['check']);
/*newline is OK in the message.*/
$this->message0 = $this->StripSlashes($_POST['message0']);
$this->message2 = $this->StripSlashes($_POST['message2']);
}
function add_error($error)
{
array_push($this->errors,$error);
}
function validate_email($email)
{
return eregi("^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$", $email);
}
function GetKey()
{
return $this->form_random_key.$_SERVER['SERVER_NAME'].$_SERVER['REMOTE_ADDR'];
}
}
(Please Please let me know if I just wrote something that should be kept unshown on public..)

php imap - get body and make plain text

I am using the PHP imap function to get emails from a POP3 mailbox and insert the data into a MySQL database.
Here is the PHP code:
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect: ' . imap_last_error());
$emails = imap_search($inbox,'ALL');
if($emails)
{
$output = '';
rsort($emails);
foreach($emails as $email_number)
{
$header=imap_headerinfo($inbox,$email_number);
$from = $header->from[0]->mailbox . "#" . $header->from[0]->host;
$toaddress=$header->toaddress;
$replyto=$header->reply_to[0]->mailbox."#".$header->reply_to[0]->host;
$datetime=date("Y-m-d H:i:s",$header->udate);
$subject=$header->subject;
//remove the " from the $toaddress
$toaddress = str_replace('"','',$toaddress);
echo '<strong>To:</strong> '.$toaddress.'<br>';
echo '<strong>From:</strong> '.$from.'<br>';
echo '<strong>Subject:</strong> '.$subject.'<br>';
//get message body
$message = (imap_fetchbody($inbox,$email_number,1.1));
if($message == '')
{
$message = (imap_fetchbody($inbox,$email_number,1));
}
}
It works fine, however on some emails in the body I get = in between words, or =20 in between words. And other times the emails will just be blank even though they are not blank when sent.
This only happens when coming from certain emails.
How can I get round this and just make the email completely plain text?
This happens because the emails are normally Quoted-printable encoded. The = is a soft line break and =20 is a white space. I think, you could use quoted_printable_decode() on the message so it shows correctly. About the blank emails, I don't know, I would need more details.
Basically:
//get message body
$message = quoted_printable_decode(imap_fetchbody($inbox,$email_number,1.1));
$data = imap_fetchbody($this->imapStream, $Part->uid, $Part->path, FT_UID | FT_PEEK);
if ($Part->format === 'quoted-printable' && $data) {
$data = quoted_printable_decode($data);
}
This is required for mails with
Content-Transfer-Encoding: quoted-printable
But for mails with
Content-Transfer-Encoding: 8bit
simply imap_fetchbody is enough.
Above code was taken from a cake-php component created for fetching mails from mail boxes throgh IMAP.
I made an entire class some years ago, and I'm still using it when I need to get contents from emails. It will help you fetch all email bodies (sometimes you have html and plain text) in a readable format, and get all attached files, just ready to be saved somewhere or sent to a website user.
It is not really optimized so on a big mailbox you may have troubles; but the purpose of this class was to access emails in a readable format to put them on a widget of a website. I let you play with the sample below to get how it works.
ImapReader.class.php Here is the source code.
<?php
class ImapReader
{
private $host;
private $port;
private $user;
private $pass;
private $box;
private $box_list;
private $errors;
private $connected;
private $list;
private $deleted;
const FROM = 0;
const TO = 1;
const REPLY_TO = 2;
const SUBJECT = 3;
const CONTENT = 4;
const ATTACHMENT = 5;
public function __construct($host = null, $port = '143', $user = null, $pass = null)
{
$this->host = $host;
$this->port = $port;
$this->user = $user;
$this->pass = $pass;
$this->box = null;
$this->box_list = null;
$this->errors = array ();
$this->connected = false;
$this->list = null;
$this->deleted = false;
}
public function __destruct()
{
if ($this->isConnected())
{
$this->disconnect();
}
}
public function changeServer($host = null, $port = '143', $user = null, $pass = null)
{
if ($this->isConnected())
{
$this->disconnect();
}
$this->host = $host;
$this->port = $port;
$this->user = $user;
$this->pass = $pass;
$this->box_list = null;
$this->errors = array ();
$this->list = null;
return $this;
}
public function canConnect()
{
return (($this->connected == false) && (is_string($this->host)) && (!empty($this->host))
&& (is_numeric($this->port)) && ($this->port >= 1) && ($this->port <= 65535)
&& (is_string($this->user)) && (!empty($this->user)) && (is_string($this->pass)) && (!empty($this->pass)));
}
public function connect()
{
if ($this->canConnect())
{
$this->box = #imap_open("{{$this->host}:{$this->port}/imap/ssl/novalidate-cert}INBOX", $this->user,
$this->pass);
if ($this->box !== false)
{
$this->_connected();
}
else
{
$this->errors = array_merge($this->errors, imap_errors());
}
}
return $this;
}
public function boxList()
{
if (is_null($this->box_list))
{
$list = imap_getsubscribed($this->box, "{{$this->host}:{$this->port}}", "*");
$this->box_list = array ();
foreach ($list as $box)
{
$this->box_list[] = $box->name;
}
}
return $this->box_list;
}
public function fetchAllHeaders($mbox)
{
if ($this->isConnected())
{
$test = imap_reopen($this->box, "{$mbox}");
if (!$test)
{
return false;
}
$num_msgs = imap_num_msg($this->box);
$this->list = array ();
for ($id = 1; ($id <= $num_msgs); $id++)
{
$this->list[] = $this->_fetchHeader($mbox, $id);
}
return true;
}
return false;
}
public function fetchSearchHeaders($mbox, $criteria)
{
if ($this->isConnected())
{
$test = imap_reopen($this->box, "{$mbox}");
if (!$test)
{
return false;
}
$msgs = imap_search($this->box, $criteria);
if ($msgs)
{
foreach ($msgs as $id)
{
$this->list[] = $this->_fetchHeader($mbox, $id);
}
}
return true;
}
return false;
}
public function isConnected()
{
return $this->connected;
}
public function disconnect()
{
if ($this->connected)
{
if ($this->deleted)
{
imap_expunge($this->box);
$this->deleted = false;
}
imap_close($this->box);
$this->connected = false;
$this->box = null;
}
return $this;
}
/**
* Took from khigashi dot oang at gmail dot com at php.net
* with replacement of ereg family functions by preg's ones.
*
* #param string $str
* #return string
*/
private function _fix($str)
{
if (preg_match("/=\?.{0,}\?[Bb]\?/", $str))
{
$str = preg_split("/=\?.{0,}\?[Bb]\?/", $str);
while (list($key, $value) = each($str))
{
if (preg_match("/\?=/", $value))
{
$arrTemp = preg_split("/\?=/", $value);
$arrTemp[0] = base64_decode($arrTemp[0]);
$str[$key] = join("", $arrTemp);
}
}
$str = join("", $str);
}
if (preg_match("/=\?.{0,}\?Q\?/", $str))
{
$str = quoted_printable_decode($str);
$str = preg_replace("/=\?.{0,}\?[Qq]\?/", "", $str);
$str = preg_replace("/\?=/", "", $str);
}
return trim($str);
}
private function _connected()
{
$this->connected = true;
return $this;
}
public function getErrors()
{
$errors = $this->errors;
$this->errors = array ();
return $errors;
}
public function count()
{
if (is_null($this->list))
{
return 0;
}
return count($this->list);
}
public function get($nbr = null)
{
if (is_null($nbr))
{
return $this->list;
}
if ((is_array($this->list)) && (isset($this->list[$nbr])))
{
return $this->list[$nbr];
}
return null;
}
public function fetch($nbr = null)
{
return $this->_callById('_fetch', $nbr);
}
private function _fetchHeader($mbox, $id)
{
$header = imap_header($this->box, $id);
if (!is_object($header))
{
return;
}
$mail = new stdClass();
$mail->id = $id;
$mail->mbox = $mbox;
$mail->timestamp = (isset($header->udate)) ? ($header->udate) : ('');
$mail->date = date("d/m/Y H:i:s", (isset($header->udate)) ? ($header->udate) : (''));
$mail->from = $this->_fix(isset($header->fromaddress) ? ($header->fromaddress) : (''));
$mail->to = $this->_fix(isset($header->toaddress) ? ($header->toaddress) : (''));
$mail->reply_to = $this->_fix(isset($header->reply_toaddress) ? ($header->reply_toaddress) : (''));
$mail->subject = $this->_fix(isset($header->subject) ? ($header->subject) : (''));
$mail->content = array ();
$mail->attachments = array ();
$mail->deleted = false;
return $mail;
}
private function _fetch($mail)
{
$test = imap_reopen($this->box, "{$mail->mbox}");
if (!$test)
{
return $mail;
}
$structure = imap_fetchstructure($this->box, $mail->id);
if ((!isset($structure->parts)) || (!is_array($structure->parts)))
{
$body = imap_body($this->box, $mail->id);
$content = new stdClass();
$content->type = 'content';
$content->mime = $this->_fetchType($structure);
$content->charset = $this->_fetchParameter($structure->parameters, 'charset');
$content->data = $this->_decode($body, $structure->type);
$content->size = strlen($content->data);
$mail->content[] = $content;
return $mail;
}
else
{
$parts = $this->_fetchPartsStructureRoot($mail, $structure);
foreach ($parts as $part)
{
$content = new stdClass();
$content->type = null;
$content->data = null;
$content->mime = $this->_fetchType($part->data);
if ((isset($part->data->disposition))
&& ((strcmp('attachment', $part->data->disposition) == 0)
|| (strcmp('inline', $part->data->disposition) == 0)))
{
$content->type = $part->data->disposition;
$content->name = null;
if (isset($part->data->dparameters))
{
$content->name = $this->_fetchParameter($part->data->dparameters, 'filename');
}
if (is_null($content->name))
{
if (isset($part->data->parameters))
{
$content->name = $this->_fetchParameter($part->data->parameters, 'name');
}
}
$mail->attachments[] = $content;
}
else if ($part->data->type == 0)
{
$content->type = 'content';
$content->charset = null;
if (isset($part->data->parameters))
{
$content->charset = $this->_fetchParameter($part->data->parameters, 'charset');
}
$mail->content[] = $content;
}
$body = imap_fetchbody($this->box, $mail->id, $part->no);
if (isset($part->data->encoding))
{
$content->data = $this->_decode($body, $part->data->encoding);
}
else
{
$content->data = $body;
}
$content->size = strlen($content->data);
}
}
return $mail;
}
private function _fetchPartsStructureRoot($mail, $structure)
{
$parts = array ();
if ((isset($structure->parts)) && (is_array($structure->parts)) && (count($structure->parts) > 0))
{
foreach ($structure->parts as $key => $data)
{
$this->_fetchPartsStructure($mail, $data, ($key + 1), $parts);
}
}
return $parts;
}
private function _fetchPartsStructure($mail, $structure, $prefix, &$parts)
{
if ((isset($structure->parts)) && (is_array($structure->parts)) && (count($structure->parts) > 0))
{
foreach ($structure->parts as $key => $data)
{
$this->_fetchPartsStructure($mail, $data, $prefix . "." . ($key + 1), $parts);
}
}
$part = new stdClass;
$part->no = $prefix;
$part->data = $structure;
$parts[] = $part;
}
private function _fetchParameter($parameters, $key)
{
foreach ($parameters as $parameter)
{
if (strcmp($key, $parameter->attribute) == 0)
{
return $parameter->value;
}
}
return null;
}
private function _fetchType($structure)
{
$primary_mime_type = array ("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER");
if ((isset($structure->subtype)) && ($structure->subtype) && (isset($structure->type)))
{
return $primary_mime_type[(int) $structure->type] . '/' . $structure->subtype;
}
return "TEXT/PLAIN";
}
private function _decode($message, $coding)
{
switch ($coding)
{
case 2:
$message = imap_binary($message);
break;
case 3:
$message = imap_base64($message);
break;
case 4:
$message = imap_qprint($message);
break;
case 5:
break;
default:
break;
}
return $message;
}
private function _callById($method, $data)
{
$callback = array ($this, $method);
// data is null
if (is_null($data))
{
$result = array ();
foreach ($this->list as $mail)
{
$result[] = $this->_callById($method, $mail);
}
return $result;
}
// data is an array
if (is_array($data))
{
$result = array ();
foreach ($data as $elem)
{
$result[] = $this->_callById($method, $elem);
}
return $result;
}
// data is an object
if ((is_object($data)) && ($data instanceof stdClass) && (isset($data->id)))
{
return call_user_func($callback, $data);
}
// data is numeric
if (($this->isConnected()) && (is_array($this->list)) && (is_numeric($data)))
{
foreach ($this->list as $mail)
{
if ($mail->id == $data)
{
return call_user_func($callback, $mail);
}
}
}
return null;
}
public function delete($nbr)
{
$this->_callById('_delete', $nbr);
return;
}
private function _delete($mail)
{
if ($mail->deleted == false)
{
$test = imap_reopen($this->box, "{$mail->mbox}");
if ($test)
{
$this->deleted = true;
imap_delete($this->box, $mail->id);
$mail->deleted = true;
}
}
}
public function searchBy($pattern, $type)
{
$result = array ();
if (is_array($this->list))
{
foreach ($this->list as $mail)
{
$match = false;
switch ($type)
{
case self::FROM:
$match = $this->_match($mail->from, $pattern);
break;
case self::TO:
$match = $this->_match($mail->to, $pattern);
break;
case self::REPLY_TO:
$match = $this->_match($mail->reply_to, $pattern);
break;
case self::SUBJECT:
$match = $this->_match($mail->subject, $pattern);
break;
case self::CONTENT:
foreach ($mail->content as $content)
{
$match = $this->_match($content->data, $pattern);
if ($match)
{
break;
}
}
break;
case self::ATTACHMENT:
foreach ($mail->attachments as $attachment)
{
$match = $this->_match($attachment->name, $pattern);
if ($match)
{
break;
}
}
break;
}
if ($match)
{
$result[] = $mail;
}
}
}
return $result;
}
private function _nmatch($string, $pattern, $a, $b)
{
if ((!isset($string[$a])) && (!isset($pattern[$b])))
{
return 1;
}
if ((isset($pattern[$b])) && ($pattern[$b] == '*'))
{
if (isset($string[$a]))
{
return ($this->_nmatch($string, $pattern, ($a + 1), $b) + $this->_nmatch($string, $pattern, $a, ($b + 1)));
}
else
{
return ($this->_nmatch($string, $pattern, $a, ($b + 1)));
}
}
if ((isset($string[$a])) && (isset($pattern[$b])) && ($pattern[$b] == '?'))
{
return ($this->_nmatch($string, $pattern, ($a + 1), ($b + 1)));
}
if ((isset($string[$a])) && (isset($pattern[$b])) && ($pattern[$b] == '\\'))
{
if ((isset($pattern[($b + 1)])) && ($string[$a] == $pattern[($b + 1)]))
{
return ($this->_nmatch($string, $pattern, ($a + 1), ($b + 2)));
}
}
if ((isset($string[$a])) && (isset($pattern[$b])) && ($string[$a] == $pattern[$b]))
{
return ($this->_nmatch($string, $pattern, ($a + 1), ($b + 1)));
}
return 0;
}
private function _match($string, $pattern)
{
return $this->_nmatch($string, $pattern, 0, 0);
}
}
ImapReader.demo.php Here is the usage sample
<?php
require_once("ImapReader.class.php");
$box = new ImapReader('example.com', '143', 'somebody#example.com', 'xxxxxxxxxxxx');
$box
->connect()
->fetchAllHeaders()
;
echo $box->count() . " emails in mailbox\n";
for ($i = 0; ($i < $box->count()); $i++)
{
$msg = $box->get($i);
echo "Reception date : {$msg->date}\n";
echo "From : {$msg->from}\n";
echo "To : {$msg->to}\n";
echo "Reply to : {$msg->from}\n";
echo "Subject : {$msg->subject}\n";
$msg = $box->fetch($msg);
echo "Number of readable contents : " . count($msg->content) . "\n";
foreach ($msg->content as $key => $content)
{
echo "\tContent " . ($key + 1) . " :\n";
echo "\t\tContent type : {$content->mime}\n";
echo "\t\tContent charset : {$content->charset}\n";
echo "\t\tContent size : {$content->size}\n";
}
echo "Number of attachments : " . count($msg->attachments) . "\n";
foreach ($msg->attachments as $key => $attachment)
{
echo "\tAttachment " . ($key + 1) . " :\n";
echo "\t\tAttachment type : {$attachment->type}\n";
echo "\t\tContent type : {$attachment->mime}\n";
echo "\t\tFile name : {$attachment->name}\n";
echo "\t\tFile size : {$attachment->size}\n";
}
echo "\n";
}
echo "Searching '*Bob*' ...\n";
$results = $box->searchBy('*Bob*', ImapReader::FROM);
foreach ($results as $result)
{
echo "\tMatched: {$result->from} - {$result->date} - {$result->subject}\n";
}
Enjoy
Regarding the blank emails, check the encoding of the mail.
If it is a binary encoded mail then you will get blank mails when you try to insert them into a mysql text field.
Try shifting every mail to UTF-8 and then insert it
iconv(mb_detect_encoding($mail_content, mb_detect_order(), true), "UTF-8", $mail_content);
function getmsg($mbox,$mid) {
// input $mbox = IMAP stream, $mid = message id
// output all the following:
global $charset,$htmlmsg,$plainmsg,$attachments;
$htmlmsg = $plainmsg = $charset = '';
$attachments = array();
// HEADER
$h = imap_header($mbox,$mid);
// add code here to get date, from, to, cc, subject...
// BODY
$s = imap_fetchstructure($mbox,$mid);
if (!$s->parts) // simple
getpart($mbox,$mid,$s,0); // pass 0 as part-number
else { // multipart: cycle through each part
foreach ($s->parts as $partno0=>$p)
getpart($mbox,$mid,$p,$partno0+1);
}
}
function getpart($mbox,$mid,$p,$partno) {
// $partno = '1', '2', '2.1', '2.1.3', etc for multipart, 0 if simple
global $htmlmsg,$plainmsg,$charset,$attachments;
// DECODE DATA
$data = ($partno)?
imap_fetchbody($mbox,$mid,$partno): // multipart
imap_body($mbox,$mid); // simple
// Any part may be encoded, even plain text messages, so check everything.
if ($p->encoding==4)
$data = quoted_printable_decode($data);
elseif ($p->encoding==3)
$data = base64_decode($data);
// PARAMETERS
// get all parameters, like charset, filenames of attachments, etc.
$params = array();
if ($p->parameters)
foreach ($p->parameters as $x)
$params[strtolower($x->attribute)] = $x->value;
if ($p->dparameters)
foreach ($p->dparameters as $x)
$params[strtolower($x->attribute)] = $x->value;
// ATTACHMENT
// Any part with a filename is an attachment,
// so an attached text file (type 0) is not mistaken as the message.
if ($params['filename'] || $params['name']) {
// filename may be given as 'Filename' or 'Name' or both
$filename = ($params['filename'])? $params['filename'] : $params['name'];
// filename may be encoded, so see imap_mime_header_decode()
$attachments[$filename] = $data; // this is a problem if two files have same name
}
// TEXT
if ($p->type==0 && $data) {
// Messages may be split in different parts because of inline attachments,
// so append parts together with blank row.
if (strtolower($p->subtype)=='plain')
$plainmsg. = trim($data) ."\n\n";
else
$htmlmsg. = $data ."<br><br>";
$charset = $params['charset']; // assume all parts are same charset
}
// EMBEDDED MESSAGE
// Many bounce notifications embed the original message as type 2,
// but AOL uses type 1 (multipart), which is not handled here.
// There are no PHP functions to parse embedded messages,
// so this just appends the raw source to the main message.
elseif ($p->type==2 && $data) {
$plainmsg. = $data."\n\n";
}
// SUBPART RECURSION
if ($p->parts) {
foreach ($p->parts as $partno0=>$p2)
getpart($mbox,$mid,$p2,$partno.'.'.($partno0+1)); // 1.2, 1.2.1, etc.
}
}
Reference (First user contributed note): http://php.net/manual/en/function.imap-fetchstructure.php
I tried all this answers, but neither one worked for me. Then I hit first user contributed note on this PHP page:
http://php.net/manual/en/function.imap-fetchstructure.php
and this works for all my cases. Quite old answer btw.

Categories