This question already has answers here:
Severity: 8192 Message: Methods with the same name as their class will not be constructors in a future version of PHP;
(6 answers)
Closed 9 days ago.
I have a script that sends a SMS alert but it is failing on "class UPLOAD". The PHP error log shows "Methods with the same name as their class will not be constructors in a future version of PHP; UPLOAD has a deprecated constructor". Can anyone see what is going wrong.
class UPLOAD
{
var $URI='';
var $Host='localhost';
var $Port='80';
var $Fields=array();
var $Files=array();
var $Headers=array();
var $Request='';
var $RequestHeaders='';
var $RequestBody='';
var $Response='';
var $ResponseHeaders='';
var $ResponseBody='';
var $log='';
var $errors=array();
var $UseProxy=false;
var $ProxyHost='localhost';
var $ProxyPort=3128;
// constructor
function UPLOAD($URI)
{
$this->log .= 'Creating object with URI: '.htmlspecialchars($URI)."\n";
if (preg_match("/^https:\/\/([^\/:]+)[:]?(\d*)?(.*)/i", $URI, $m))
{
$this->URI = $URI;
$this->Host = $m[1];
$this->Port = ((int)$m[2])==0 ? 80 : (int)$m[2];
$this->log .= 'Object with URI '.htmlspecialchars($URI)." created.\n";
$this->log .= ' host: '.htmlspecialchars($this->Host)."\n";
$this->log .= ' port: '.htmlspecialchars($this->Port)."\n";
}
else
{
$this->log .= 'Object with URI '.htmlspecialchars($URI)." create failed.\n";
$this->errors[] = 'Access URI '.htmlspecialchars('"'.$URI.'"').' is not valid';
}
}
// adding field(s) to form
function SetFields($field, $value='')
{
if (is_array($field))
{
foreach($field as $k=>$v)
{
$this->SetFields($k, $v);
}
}
else
{
$this->Fields[] = array($field, $value);
$this->log .= 'Added field '.htmlspecialchars('"'.$field.'"').' with value '.htmlspecialchars('"'.$value.'"')."\n";
}
}
// adding files to form
function SetFiles($field, $filename='', $content='')
{
if (is_array($field))
{
foreach($field as $k=>$v)
{
$this->SetFiles($k, $v);
}
}
else
{
if (is_array($filename))
{
foreach($filename as $k=>$v)
{
$this->SetFiles($field, $k, $v);
}
}
else
{
$this->Files[] = array($field, $filename, $content);
$this->log .= 'Added field '.htmlspecialchars('"'.$field.'"').' of type file with name '.htmlspecialchars('"'.$filename.'"')."\n";
}
}
}
// send form
function Send()
{
if (!$hosts=gethostbynamel($this->Host))
{
$this->errors[] = 'Send failed. Host '.htmlspecialchars('"'.$this->Host.'"').' not found.';
return false;
}
$fp = #fsockopen($this->Host, $this->Port, $errno, $errstr, 3);
if (!$fp)
{
$this->errors[] = "Connection failed with: ".$errno.' '.htmlspecialchars($errstr);
return false;
}
$this->calculate();
$out = $this->Request;
fwrite($fp, $out, strlen($out));
$result = '';
while (!feof($fp)) {
$result .= fgets($fp, 1024);
}
$this->Response = $result;
$i = strpos($result, "\r\n\r\n");
if ($i>0)
{
$this->ResponseHeader = substr($result, 0, $i);
$this->ResponseBody = substr($result, $i+4);
}
else
{
$this->ResponseHeader = $result;
$this->ResponseBody = '';
}
return true;
}
// calculate form
function calculate()
{
$boundary = '---------------------------PHPUPLOADCLASS';
$body = '';
foreach($this->Fields as $k=>$v)
{
$body .= "--$boundary\r\n";
$body .= 'Content-Disposition: form-data; name="'.$v[0]."\"\r\n";
$body .= "\r\n".$v[1]."\r\n";
}
foreach($this->Files as $k=>$v)
{
$body .= "--$boundary\r\n";
$body .= 'Content-Disposition: form-data; name="'.$v[0].'"; filename="'.$v[1]."\"\r\n";
$body .= "Content-Type: application/octet-stream\r\n";
$body .= "\r\n".$v[2]."\r\n";
}
$body .= "--$boundary--\r\n";
$headers = 'POST '.$this->URI." HTTPS/1.0\r\n";
$headers .= 'Host: '.$this->Host."\r\n";
$headers .= "User-Agent: Mozilla/4.0 (PHP Uploader Class)\r\n";
$headers .= "Accept: */*\r\n";
$headers .= "Pragma: no-cache\r\n";
foreach($this->Headers as $k=>$v)
{
$headers .= $k.': '.$v."\r\n";
}
$headers .= "Content-Type: multipart/form-data; boundary=$boundary\r\n";
$headers .= "Content-Length: ".strlen($body)."\r\n";
$headers .= "Connection: Close\r\n\r\n";
$this->Request = $headers.$body;
$this->RequestHeaders = $headers;
$this->RequestBody = $body;
}
}
[/CODE]
In PHP 7 the old style of constructor having the same name of the class name is deprecated.
So you need to use other name of method which is not same as class
name.
Or you can use A magic method in PHP that usually starts with 2 underscores instead of function UPLOAD.
Like:
public function __construct()
{
//put all your logic to instantiate an object with class properties
}
instead of :
public function UPLOAD()
{
//put all your logic to instantiate an object with class properties
}
Related
I have to send mail using Amazon AWS with PHP, I am able to send simple mail but got following Error, I used many codes get from Google but still I got the same error every time.
Fatal error: Cannot redeclare Aws\constantly() (previously declared
in /path/vendor/aws/aws-sdk-php/src/functions.php:20) in
phar:///opt/lampp/htdocs/path/amazon/aws.phar/Aws/functions.php on
line 22
Code I used:-
require_once '/mypath/vendor/autoload.php';
include_once("SESUtils.php");
$subject_str = "Some Subject";
$body_str = "<strong>Some email body</strong>";
$attachment_str = file_get_contents("mypdf_file.pdf");
//send the email
$params =
array("to" => "to#xyz.com",
"subject" => "Some subject",
"message" => "<strong>Some email body</strong>",
"from" => "from#xyz.com",
"replyTo" => "reply_to#gmail.com",
"files" =>
array(
"1" => array(
"name" => "filename1",
"filepath" => "/path/to/mypdf_file.pdf",
"mime" => "application/pdf"
),
)
);
$res = SESUtils::sendMail($params);
aws version:- 3.21.6
AND SESUtils.php
require_once('aws.phar');
use Aws\Ses\SesClient;
class SESUtils {
const version = "1.0";
const AWS_KEY = "AWS_KEY";
const AWS_SEC = "AWS_SEC";
const AWS_REGION = "us-east-1";
const MAX_ATTACHMENT_NAME_LEN = 60;
public static function sendMail($params) {
$to = self::getParam($params, 'to', true);
$subject = self::getParam($params, 'subject', true);
$body = self::getParam($params, 'message', true);
$from = self::getParam($params, 'from', true);
$replyTo = self::getParam($params, 'replyTo');
$files = self::getParam($params, 'files');
$res = new ResultHelper();
// get the client ready
$client = SesClient::factory(array(
'key' => self::AWS_KEY,
'secret' => self::AWS_SEC,
'region' => self::AWS_REGION
));
// build the message
if (is_array($to)) {
$to_str = rtrim(implode(',', $to), ',');
} else {
$to_str = $to;
}
$msg = "To: $to_str\n";
$msg .= "From: $from\n";
if ($replyTo) {
$msg .= "Reply-To: $replyTo\n";
}
// in case you have funny characters in the subject
$subject = mb_encode_mimeheader($subject, 'UTF-8');
$msg .= "Subject: $subject\n";
$msg .= "MIME-Version: 1.0\n";
$msg .= "Content-Type: multipart/mixed;\n";
$boundary = uniqid("_Part_".time(), true); //random unique string
$boundary2 = uniqid("_Part2_".time(), true); //random unique string
$msg .= " boundary=\"$boundary\"\n";
$msg .= "\n";
$msg .= "--$boundary\n";
$msg .= "Content-Type: multipart/alternative;\n";
$msg .= " boundary=\"$boundary2\"\n";
$msg .= "\n";
$msg .= "--$boundary2\n";
$msg .= "Content-Type: text/plain; charset=utf-8\n";
$msg .= "Content-Transfer-Encoding: 7bit\n";
$msg .= "\n";
$msg .= strip_tags($body); //remove any HTML tags
$msg .= "\n";
// now, the html text
$msg .= "--$boundary2\n";
$msg .= "Content-Type: text/html; charset=utf-8\n";
$msg .= "Content-Transfer-Encoding: 7bit\n";
$msg .= "\n";
$msg .= $body;
$msg .= "\n";
$msg .= "--$boundary2--\n";
// add attachments
if (is_array($files)) {
$count = count($files);
foreach ($files as $file) {
$msg .= "\n";
$msg .= "--$boundary\n";
$msg .= "Content-Transfer-Encoding: base64\n";
$clean_filename = self::clean_filename($file["name"], self::MAX_ATTACHMENT_NAME_LEN);
$msg .= "Content-Type: {$file['mime']}; name=$clean_filename;\n";
$msg .= "Content-Disposition: attachment; filename=$clean_filename;\n";
$msg .= "\n";
$msg .= base64_encode(file_get_contents($file['filepath']));
$msg .= "\n--$boundary";
}
// close email
$msg .= "--\n";
}
// now send the email out
try {
$ses_result = $client->sendRawEmail(
array(
'RawMessage' => array(
'Data' => base64_encode($msg)
)
), array(
'Source' => $from,
'Destinations' => $to_str
)
);
if ($ses_result) {
$res->message_id = $ses_result->get('MessageId');
} else {
$res->success = false;
$res->result_text = "Amazon SES did not return a MessageId";
}
} catch (Exception $e) {
$res->success = false;
$res->result_text = $e->getMessage().
" - To: $to_str, Sender: $from, Subject: $subject";
}
return $res;
}
private static function getParam($params, $param, $required = false) {
$value = isset($params[$param]) ? $params[$param] : null;
if ($required && empty($value)) {
throw new Exception('"'.$param.'" parameter is required.');
} else {
return $value;
}
}
/** Clean filename function - to be mail friendly **/
public static function clean_filename($str, $limit = 0, $replace=array(), $delimiter='-') {
if( !empty($replace) ) {
$str = str_replace((array)$replace, ' ', $str);
}
$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
$clean = preg_replace("/[^a-zA-Z0-9\.\/_| -]/", '', $clean);
$clean = preg_replace("/[\/| -]+/", '-', $clean);
if ($limit > 0) {
//don't truncate file extension
$arr = explode(".", $clean);
$size = count($arr);
$base = "";
$ext = "";
if ($size > 0) {
for ($i = 0; $i < $size; $i++) {
if ($i < $size - 1) { //if it's not the last item, add to $bn
$base .= $arr[$i];
//if next one isn't last, add a dot
if ($i < $size - 2)
$base .= ".";
} else {
if ($i > 0)
$ext = ".";
$ext .= $arr[$i];
}
}
}
$bn_size = mb_strlen($base);
$ex_size = mb_strlen($ext);
$bn_new = mb_substr($base, 0, $limit - $ex_size);
// doing again in case extension is long
$clean = mb_substr($bn_new.$ext, 0, $limit);
}
return $clean;
}
}
class ResultHelper {
public $success = true;
public $result_text = "";
public $message_id = "";
}
I had this error about redeclaring constantly() and the problem was resolved in our code by simply changing:
include('/PATH/TO/aws-sdk-3/aws-autoloader.php');
to
include_once('/PATH/TO/aws-sdk-3/aws-autoloader.php');
Maybe that will help you or the next person to Google this error message!
This is just namespacing. Look at the examples for reference - you need to either use the namespaced class or reference it absolutely, for example:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
//Load composer's autoloader
require 'vendor/autoload.php';
This question already has answers here:
Error with PHP mail(): Multiple or malformed newlines found in additional_header
(10 answers)
Closed 4 years ago.
I have below code for mail attachment, but it is not working, dont know why it is happening..
function mail_attachment($filename, $path, $mailto, $from_mail, $subject, $message){
$uid = md5(uniqid(time()));
$mime_boundary = "==Multipart_Boundary_x{$uid}x";
$header = "From: <".$from_mail.">\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$mime_boundary."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$mime_boundary."\r\n";
$header .= "Content-type:text/html; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= nl2br($message)."\r\n\r\n";
$header .= "--".$mime_boundary."\r\n";
foreach($filename as $k=>$v){
$file = $path.$v;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$header .= "Content-Type: application/octet-stream; name=\"".$v."\"\r\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$v."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
$header .= "--".$mime_boundary."--"."\r\n";
}
if (mail($mailto, $subject, "", $header)) {
//echo "mail send ... OK"; // or use booleans here
return true;
} else {
//echo "mail send ... ERROR!";
return false;
}
}
$path='upload/';
$send_email = mail_attachment($files, $path, $to, "roxmorphy26#gmail", $subject, $message);
//mail($to,$subject,$message,$headers);
if($send_email){ echo 'done';} else {echo 'not';}
but it gives error like -- Warning: mail(): Multiple or malformed newlines found in additional_header
please help.
<?php
define("LIBR", "\n"); // use a "\r\n" if you have problems
define("PRIORITY", 3); // 3 = normal, 2 = high, 4 = low
define("TRANS_ENC", "7bit");
define("ENCODING", "iso-8859-1");
class attach_mailer {
var $from_name;
var $from_mail;
var $mail_to;
var $mail_cc;
var $mail_bcc;
var $webmaster_email = "webmaster#yourdomain.com";
var $mail_headers;
var $mail_subject;
var $text_body = "";
var $html_body = "";
var $valid_mail_adresses; // boolean is true if all mail(to) adresses are valid
var $uid; // the unique value for the mail boundry
var $alternative_uid; // the unique value for the mail boundry
var $related_uid; // the unique value for the mail boundry
var $html_images = array();
var $att_files = array();
var $msg = array();
// functions inside this constructor
// - validation of e-mail adresses
// - setting mail variables
// - setting boolean $valid_mail_adresses
function attach_mailer($name = "", $from, $to, $cc = "", $bcc = "", $subject = "") {
$this->valid_mail_adresses = true;
if (!$this->check_mail_address($to)) {
$this->msg[] = "Error, the \"mailto\" address is empty or not valid.";
$this->valid_mail_adresses = false;
}
if (!$this->check_mail_address($from)) {
$this->msg[] = "Error, the \"from\" address is empty or not valid.";
$this->valid_mail_adresses = false;
}
if ($cc != "") {
if (!$this->check_mail_address($cc)) {
$this->msg[] = "Error, the \"Cc\" address is not valid.";
$this->valid_mail_adresses = false;
}
}
if ($bcc != "") {
if (!$this->check_mail_address($bcc)) {
$this->msg[] = "Error, the \"Bcc\" address is not valid.";
$this->valid_mail_adresses = false;
}
}
if ($this->valid_mail_adresses) {
$this->from_name = $this->strip_line_breaks($name);
$this->from_mail = $this->strip_line_breaks($from);
$this->mail_to = $this->strip_line_breaks($to);
$this->mail_cc = $this->strip_line_breaks($cc);
$this->mail_bcc = $this->strip_line_breaks($bcc);
$this->mail_subject = $this->strip_line_breaks($subject);
} else {
return;
}
}
function get_msg_str() {
$messages = "";
foreach($this->msg as $val) {
$messages .= $val."<br />\n";
}
return $messages;
}
// use this to prent formmail spamming
function strip_line_breaks($val) {
$val = preg_replace("/([\r\n])/", "", $val);
return $val;
}
function check_mail_address($mail_address) {
$pattern = "/^[\w-]+(\.[\w-]+)*#([0-9a-z][0-9a-z-]*[0-9a-z]\.)+([a-z]{2,4})$/i";
if (preg_match($pattern, $mail_address)) {
if (function_exists("checkdnsrr")) {
$parts = explode("#", $mail_address);
if (checkdnsrr($parts[1], "MX")){
return true;
} else {
return false;
}
} else {
// on windows hosts is only a limited e-mail address validation possible
return true;
}
} else {
return false;
}
}
function get_file_data($filepath) {
if (file_exists($filepath)) {
if (!$str = file_get_contents($filepath)) {
$this->msg[] = "Error while opening attachment \"".basename($filepath)."\"";
} else {
return $str;
}
} else {
$this->msg[] = "Error, the file \"".basename($filepath)."\" does not exist.";
return;
}
}
// use for $dispo "attachment" or "inline" (f.e. example images inside a html mail
function add_attach_file($file, $encoding = "base64", $dispo = "attachment", $type = "application/octet-stream") {
$file_str = $this->get_file_data($file);
if ($file_str == "") {
return;
} else {
if ($encoding == "base64") $file_str = base64_encode($file_str);
$this->att_files[] = array(
"data"=>chunk_split($file_str),
"name"=>basename($file),
"cont_type"=>$type,
"trans_enc"=>$encoding,
"disposition"=>$dispo);
}
}
function add_html_image($img_name) {
$file_str = $this->get_file_data($img_name);
$img_dim = getimagesize($img_name);
if ($file_str == "") {
return;
} else {
$this->html_images[] = array(
"data"=>chunk_split(base64_encode($file_str)),
"name"=>basename($img_name),
"cont_type"=>$img_dim['mime'],
"cid"=>md5(uniqid(time()))."#".$_SERVER['SERVER_NAME']);
}
}
function create_stand_headers() {
if ($this->from_name != "") {
$headers = "From: ".$this->from_name." <".$this->from_mail.">".LIBR;
$headers .= "Reply-To: ".$this->from_name." <".$this->from_mail.">".LIBR;
} else {
$headers = "From: ".$this->from_mail.LIBR;
$headers .= "Reply-To: ".$this->from_mail.LIBR;
}
if ($this->mail_cc != "") $headers .= "Cc: ".$this->mail_cc.LIBR;
if ($this->mail_bcc != "") $headers .= "Bcc: ".$this->mail_bcc.LIBR;
$headers .= sprintf("Message-ID: <%s#%s>%s", md5(uniqid(time())), $_SERVER['SERVER_NAME'], LIBR);
$headers .= "X-Priority: ".PRIORITY.LIBR;
$headers .= "X-Mailer: Attachment Mailer [version 1.2]".LIBR;
$headers .= "MIME-Version: 1.0".LIBR;
return $headers;
}
function create_html_image($img_array) {
$img = "Content-Type: ".$img_array['cont_type'].";".LIBR.chr(9)." name=\"".$img_array['name']."\"".LIBR;
$img .= "Content-Transfer-Encoding: base64".LIBR;
$img .= "Content-ID: <image".$img_array['cid'].">".LIBR;
$img .= "Content-Disposition: inline;".LIBR.chr(9)." filename=\"".$img_array['name']."\"".LIBR.LIBR;
$img .= $img_array['data'];
return $img;
}
function create_attachment($data_array) {
$att = "Content-Type: ".$data_array['cont_type'].";".LIBR.chr(9)." name=\"".$data_array['name']."\"".LIBR;
$att .= "Content-Transfer-Encoding: ".$data_array['trans_enc'].LIBR;
$att .= "Content-Disposition: ".$data_array['disposition'].";".LIBR.chr(9)." filename=\"".$data_array['name']."\"".LIBR.LIBR;
$att .= $data_array['data'];
return $att;
}
function create_html_body() {
$html = "Content-Type: text/html; charset=".ENCODING.LIBR;
$html .= "Content-Transfer-Encoding: ".TRANS_ENC.LIBR.LIBR;
foreach ($this->html_images as $img) {
$this->html_body = str_replace($img['name'], "cid:image".$img['cid'], $this->html_body);
}
$html .= $this->html_body;
return $html.LIBR.LIBR;
}
function build_message() {
$this->headers = $this->create_stand_headers();
$msg = "";
$is_html = ($this->html_body != "") ? true : false;
$is_attachment = (count($this->att_files) > 0) ? true : false;
$is_images = (count($this->html_images) > 0) ? true : false;
if ($is_attachment) {
$this->uid = md5(uniqid(time()));
$this->headers .= "Content-Type: multipart/mixed;".LIBR.chr(9)." boundary=\"".$this->uid."\"".LIBR.LIBR;
$this->headers .= "This is a multi-part message in MIME format.".LIBR;
if (!$is_html) {
$msg .= "--".$this->uid.LIBR;
} else {
$this->headers .= "--".$this->uid.LIBR;
}
}
if ($is_html) {
$this->alternative_uid = md5(uniqid(time()));
$this->headers .= "Content-Type: multipart/alternative;".LIBR.chr(9)." boundary=\"".$this->alternative_uid."\"".LIBR.LIBR;
if (!$is_attachment) {
$this->headers .= "This is a multi-part message in MIME format.".LIBR;
}
$msg .= LIBR."--".$this->alternative_uid.LIBR;
}
$body_head = "Content-Type: text/plain; charset=".ENCODING."; format=flowed".LIBR;
$body_head .= "Content-Transfer-Encoding: ".TRANS_ENC.LIBR.LIBR;
if (!$is_attachment && !$is_html) {
$this->headers .= $body_head;
} else {
$msg .= $body_head;
}
$msg .= trim($this->text_body).LIBR.LIBR;
if ($is_html) {
$msg .= "--".$this->alternative_uid.LIBR;
if ($is_images) {
$this->related_uid = md5(uniqid(time()));
$msg .= "Content-Type: multipart/related;".LIBR.chr(9)." boundary=\"".$this->related_uid."\"".LIBR.LIBR.LIBR;
$msg .= "--".$this->related_uid.LIBR;
$msg .= $this->create_html_body();
foreach ($this->html_images as $img) {
$msg .= "--".$this->related_uid.LIBR;
$msg .= $this->create_html_image($img);
}
$msg .= LIBR."--".$this->related_uid."--";
} else {
$msg .= $this->create_html_body();
}
$msg .= LIBR.LIBR."--".$this->alternative_uid."--".LIBR.LIBR;
}
if ($is_attachment) {
foreach ($this->att_files as $att) {
$msg .= "--".$this->uid.LIBR;
$msg .= $this->create_attachment($att);
}
$msg .= "--".$this->uid."--";
}
return $msg;
}
function process_mail() {
if (!$this->valid_mail_adresses) return;
if (mail($this->mail_to, $this->mail_subject, $this->build_message(), $this->headers, "-f".$this->webmaster_email)) {
$this->msg[] = "Your mail is succesfully submitted.";
return true;
} else {
$this->msg[] = "Error while sending you mail.";
return false;
}
}
}
$test = new attach_mailer($name = "Olaf", $from = "youremail#gmail.com", $to = "toemail#gmail.com", $cc = "", $bcc = "", $subject = "Test text email with attachments");
$test->text_body = "...Some body text\n\n the admin";
$test->add_attach_file("uploads/admin_doc.docx");
//$test->add_attach_file("ip2nation.zip");
$test->process_mail();
echo $test->get_msg_str();
can i have this function send email through smtp?
function send()
{
if(mail($this->to, $this->subject, $this->body, $this->headers)) return TRUE;
else return FALSE;
}
this is part of following code:
class sendMail
{
var $to;
var $cc;
var $bcc;
var $subject;
var $from;
var $headers;
var $html;
function sendMail()
{
$this->to = "test#mail.com";
#$this->to = "test#test.com";
$this->cc = NULL;
$this->bcc = NULL;
$this->subject = NULL;
$this->from = NULL;
$this->headers = NULL;
$this->html = FALSE;
}
function getParams($params)
{
$i = 0;
foreach ($params as $key => $value) {
switch($key) {
case 'Submit':
NULL;
break;
default:
if ($key == 'email')
{
$this->from = $value;
$this->subject ="Contactgegevens from " . $value . " at www.webandeve.nl ";
}
$this->body[$i]["key"] = str_replace("_", " ", ucWords(strToLower($key)));
$this->body[$i++]["value"] = $value;
}
}
}
function setHeaders()
{
$this->headers = "From: $this->from\r\n";
if($this->html === TRUE) {
$this->headers.= "MIME-Version: 1.0\r\n";
$this->headers.= "Content-type: text/html; charset=iso-8859-1\r\n";
}
}
function parseBody()
{
$count = count($this->body);
for($i = 0; $i < $count; $i++) {
if($this->html) $content.= "<b>";
$content .= $this->body[$i]["key"].': ';
if($this->html) $content.= "</b>";
if($this->html) $content .= nl2br($this->body[$i]["value"])."\n";
else $content .= $this->body[$i]["value"];
if($this->html) $content.= "<br>\n";
else $content.= "\n".str_repeat("-", 80)."\n";
}
if($this->html) {
$content = "
<style>
BODY {
font-family: verdana;
font-size: 10;
}
</style>
".$content;
}
$this->body = $content;
}
function send()
{
if(mail($this->to, $this->subject, $this->body, $this->headers)) return TRUE;
else return FALSE;
}
function set($key, $value)
{
if($value) $this->$key = $value;
else unset($this->$key);
}
function get_location()
{
return header('Location: thankyou.htm');break;
}
}
I've been looking for a simple solution but cannot find any (for my knowledge of php) but Git and some full replacements of my script.
If you want to use your SMTP mail config with the mail() function you need to set the SMTP config in your php.ini.
See E-Mail configuration for details.
However I would recommend the use of a third party lib like PHPMailer
I'm working with the paypal adaptive payments and my IPN listener worked fine in the sandbox, but now that we're testing live transactions, it always returns "INVALID", but the actual money has been transferred.
Any help on why I always receive "INVALD" is appreciated.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Paypal_ipn extends CI_Controller {
public function index() {
log_message('error', '');
log_message('error', '');
log_message('error', '##################');
log_message('error', '##################');
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate&'.file_get_contents("php://input");
$header = null;
// post back to PayPal system to validate
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Host: www.sandbox.paypal.com\r\n"; // this line is needed for sandbox, but may not be needed for prod.
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
$raw_post = file_get_contents("php://input");
$post_array = $this->decodePayPalIPN($raw_post);
log_message('error', "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
$log1 = var_export($post_array, true);
log_message('error', $log1);
log_message('error', "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
log_message('error', "sender_email = ".$post_array['sender_email']);
if(isset($post_array['sender_email'])) {
$sender_email = $post_array['sender_email'];
}
if(isset($post_array['status'])) {
$status = $post_array['status'];
}
if(isset($post_array['payment_request_date'])) {
$payment_request_date = $post_array['payment_request_date'];
}
if(isset($post_array['transaction'][0]['receiver'])) {
$receiver0 = $post_array['transaction'][0]['receiver'];
}
if(isset($post_array['transaction'][1]['receiver'])) {
$receiver1 = $post_array['transaction'][1]['receiver'];
}
if(isset($post_array['transaction'][0]['id'])) {
$id0 = $post_array['transaction'][0]['id'];
}
if(isset($post_array['transaction'][1]['id'])) {
$id1 = $post_array['transaction'][1]['id'];
}
if(isset($post_array['transaction'][0]['invoiceId'])) {
$invoiceId0 = $post_array['transaction'][0]['invoiceId'];
}
if(isset($post_array['transaction'][1]['invoiceId'])) {
$invoiceId1 = $post_array['transaction'][1]['invoiceId'];
}
if(isset($post_array['transaction'][0]['amount'])) {
$amount0 = $post_array['transaction'][0]['amount'];
}
if(isset($post_array['transaction'][1]['amount'])) {
$amount1 = $post_array['transaction'][1]['amount'];
}
if(isset($post_array['transaction'][0]['status'])) {
$status0 = $post_array['transaction'][0]['status'];
}
if(isset($post_array['transaction'][1]['status'])) {
$status1 = $post_array['transaction'][1]['status'];
}
if(isset($post_array['transaction'][0]['id_for_sender_txn'])) {
$id_for_sender_txn0 = $post_array['transaction'][0]['id_for_sender_txn'];
}
if(isset($post_array['transaction'][1]['id_for_sender_txn'])) {
$id_for_sender_txn1 = $post_array['transaction'][1]['id_for_sender_txn'];
}
if(isset($post_array['transaction'][0]['status_for_sender_txn'])) {
$status_for_sender_txn0 = $post_array['transaction'][0]['status_for_sender_txn'];
}
if(isset($post_array['transaction'][1]['status_for_sender_txn'])) {
$status_for_sender_txn1 = $post_array['transaction'][1]['status_for_sender_txn'];
}
if(isset($post_array['transaction'][1]['pending_reason'])) {
$pending_reason0 = $post_array['transaction'][1]['pending_reason'];
}
if(isset($post_array['transaction'][1]['pending_reason'])) {
$pending_reason1 = $post_array['transaction'][1]['pending_reason'];
}
if (!$fp) {
log_message('error', 'Problem with !$fp');
// HTTP ERROR
} else {
$counter = 0;
fputs ($fp, $header . $req);
$res = '';
while (!feof($fp)) {
$res .= fgets ($fp, 1024);
log_message('error', "res = $res");
if (strcmp ($res, "VERIFIED") == 0) {
log_message('error', 'we verified');
if($status0 == "Completed") {
log_message('error', 'we completed');
$this->load->model('customer_model');
$results = $this->customer_model->get_invoice_info($invoiceId0);
if($results != false) {
log_message('error', 'results is NOT false');
foreach($results as $row) {
if($row->amount_verified != 1) {
log_message('error', 'row->amount_verified is NOT equal to 1');
log_message('error', "row->amount = ".$row->amount);
if($row->amount == $amount0) {
//log_message('error', 'row->amount is equal to amount0');
if($this->customer_model->verify_amount($invoiceId0)) {
$subject = 'Successful transaction';
$message = 'There was a successful transaction. View the log for details /public_html/application/logs';
$this->_send_email($subject, $message);
}
} else {
//log_message('error', 'we in the else');
//log_message('error', 'invoiceId0 = '.$invoiceId0);
if($this->customer_model->update_amount_and_verify($invoiceId0, $row->amount)) {
//log_message('error', 'we inside update_amount_and_verify');
$subject = 'Successful transaction';
$message = 'There was a successful transaction. View the log for details /public_html/application/logs';
$this->_send_email($subject, $message);
}
}
}
}
} else {
$subject = 'Results Equal False';
$message = 'View the log for details /public_html/application/logs';
$this->_send_email($subject, $message);
}
} else {
$subject = 'Status NOT Complete!';
$message = 'View the log for details /public_html/application/logs';
$this->_send_email($subject, $message);
}
log_message('error', "sender_email = $sender_email");
log_message('error', "payment_request_date = $payment_request_date");
log_message('error', "status = $status");
log_message('error', "receiver0 = $receiver0");
log_message('error', "receiver1 = $receiver1");
log_message('error', "id0 = $id0");
log_message('error', "id1 = $id1");
log_message('error', "invoiceId0 = $invoiceId0");
log_message('error', "invoiceId1 = $invoiceId1");
log_message('error', "amount0 = $amount0");
log_message('error', "amount1 = $amount1");
log_message('error', "status0 = $status0");
log_message('error', "status1 = $status1");
log_message('error', "id_for_sender_txn0 = $id_for_sender_txn0");
log_message('error', "id_for_sender_txn1 = $id_for_sender_txn1");
log_message('error', "status_for_sender_txn0 = $status_for_sender_txn0");
log_message('error', "status_for_sender_txn1 = $status_for_sender_txn1");
log_message('error', "pending_reason0 = $pending_reason0");
log_message('error', "pending_reason1 = $pending_reason1");
// check the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your Primary PayPal email
// check that payment_amount/payment_currency are correct
// process payment
$counter++;
}
else if (strcmp ($res, "INVALID") == 0) {
log_message('error', 'WE INVALIDDDDDDDDDDDDDDDDDD');
$test = var_export($res, true);
$test = str_replace(array("\r","\n"), '', $test);
log_message('error', $test);
log_message('error', "Problem with IPN. res = $test");
}
}
fclose ($fp);
}
}
function decodePayPalIPN($raw_post)
{
//log_message('error', "testing");
if (empty($raw_post)) {
return array();
} # else:
$post = array();
$pairs = explode('&', $raw_post);
foreach ($pairs as $pair) {
list($key, $value) = explode('=', $pair, 2);
$key = urldecode($key);
$value = urldecode($value);
# This is look for a key as simple as 'return_url' or as complex as 'somekey[x].property'
preg_match('/(\w+)(?:\[(\d+)\])?(?:\.(\w+))?/', $key, $key_parts);
switch (count($key_parts)) {
case 4:
# Original key format: somekey[x].property
# Converting to $post[somekey][x][property]
if (!isset($post[$key_parts[1]])) {
$post[$key_parts[1]] = array($key_parts[2] => array($key_parts[3] => $value));
} else if (!isset($post[$key_parts[1]][$key_parts[2]])) {
$post[$key_parts[1]][$key_parts[2]] = array($key_parts[3] => $value);
} else {
$post[$key_parts[1]][$key_parts[2]][$key_parts[3]] = $value;
}
break;
case 3:
# Original key format: somekey[x]
# Converting to $post[somkey][x]
if (!isset($post[$key_parts[1]])) {
$post[$key_parts[1]] = array();
}
$post[$key_parts[1]][$key_parts[2]] = $value;
break;
default:
# No special format
$post[$key] = $value;
break;
}#switch
}#foreach
return $post;
}#decodePayPalIPN()
private function _send_email($subject, $message) {
//log_message('error', 'we in send_email');
$this->load->library('email');
$this->email->from('do-not-reply#mysite.com', 'Title');
$this->email->to('myemail#gmail.com');
$this->email->subject($subject);
$this->email->message($message);
$this->email->send();
//log_message('error', 'email error = '.$this->email->print_debugger());
}
}
If you are now testing live transactions your code is still showing for sandbox -
$header .= "Host: www.sandbox.paypal.com\r\n"; // this line is needed for sandbox, but may not be needed for prod.
...
$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
Make sure that you change to -
// $header .= "Host: www.sandbox.paypal.com\r\n"; line removed, not needed
...
$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
did not had a chance to try your code but can you try the code sample we have here on X.com https://www.x.com/developers/PayPal/documentation-tools/code-sample/216623 ? We actually recommend using curl than socket io.
I am using the Fedex PHP API.The problem is, when I run it on my server it only shows the response of the required fields of the xml without showing the price for the services at all.
<?php
require_once("xmlparser.php");
class Fedex {
// Variables
var $server = "https://gatewaybeta.fedex.com/GatewayDC";
var $accountNumber;
var $meterNumber;
var $carrierCode = "FDXG";
var $dropoffType = "REGULARPICKUP";
var $service;
var $serviceName;
var $packaging = "YOURPACKAGING";
var $weightUnits = "LBS";
var $weight;
// Origin Address
var $originStateOrProvinceCode;
var $originPostalCode;
var $originCountryCode;
// Destination Address
var $destStateOrProvinceCode;
var $destPostalCode;
var $destCountryCode;
var $payorType = "SENDER";
// Functions
function setServer($server) {
$this->server = $server;
}
function setAccountNumber($accountNumber) {
$this->accountNumber = $accountNumber;
}
function setMeterNumber($meterNumber) {
$this->meterNumber = $meterNumber;
}
function setCarrierCode($carrierCode) {
$this->carrierCode = $carrierCode;
}
function setDropoffType($dropoffType) {
$this->dropoffType = $dropoffType;
}
function setService($service, $name) {
$this->service = $service;
$this->serviceName = $name;
}
function setPackaging($packaging) {
$this->packaging = $packaging;
}
function setWeightUnits($units) {
$this->weightUnits = $units;
}
function setWeight($weight) {
$this->weight = $weight;
}
function setOriginStateOrProvinceCode($code) {
$this->originStateOrProvinceCode = $code;
}
function setOriginPostalCode($code) {
$this->originPostalCode = $code;
}
function setOriginCountryCode($code) {
$this->originCountryCode = $code;
}
function setDestStateOrProvinceCode($code) {
$this->destStateOrProvinceCode = $code;
}
function setDestPostalCode($code) {
$this->destPostalCode = $code;
}
function setDestCountryCode($code) {
$this->destCountryCode = $code;
}
function setPayorType($type) {
$this->payorType = $type;
}
function getPrice() {
$str = '<?xml version="1.0" encoding="UTF-8" ?>';
$str .= ' <FDXRateRequest xmlns:api="http://www.fedex.com/fsmapi" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FDXRateRequest.xsd">';
$str .= ' <RequestHeader>';
$str .= ' <CustomerTransactionIdentifier>Express Rate</CustomerTransactionIdentifier>';
$str .= ' <AccountNumber>'.$this->accountNumber.'</AccountNumber>';
$str .= ' <MeterNumber>'.$this->meterNumber.'</MeterNumber>';
$str .= ' <CarrierCode>'.$this->carrierCode.'</CarrierCode>';
$str .= ' </RequestHeader>';
$str .= ' <DropoffType>'.$this->dropoffType.'</DropoffType>';
$str .= ' <Service>'.$this->service.'</Service>';
$str .= ' <Packaging>'.$this->packaging.'</Packaging>';
$str .= ' <WeightUnits>'.$this->weightUnits.'</WeightUnits>';
$str .= ' <Weight>'.number_format($this->weight, 1, '.', '').'</Weight>';
$str .= ' <OriginAddress>';
$str .= ' <StateOrProvinceCode>'.$this->originStateOrProvinceCode.'</StateOrProvinceCode>';
$str .= ' <PostalCode>'.$this->originPostalCode.'</PostalCode>';
$str .= ' <CountryCode>'.$this->originCountryCode.'</CountryCode>';
$str .= ' </OriginAddress>';
$str .= ' <DestinationAddress>';
$str .= ' <StateOrProvinceCode>'.$this->destStateOrProvinceCode.'</StateOrProvinceCode>';
$str .= ' <PostalCode>'.$this->destPostalCode.'</PostalCode>';
$str .= ' <CountryCode>'.$this->destCountryCode.'</CountryCode>';
$str .= ' </DestinationAddress>';
$str .= ' <Payment>';
$str .= ' <PayorType>'.$this->payorType.'</PayorType>';
$str .= ' </Payment>';
$str .= ' <PackageCount>'.ceil(bcdiv(number_format($this->weight, 1, '.', ''), '150', 3)).'</PackageCount>';
$str .= ' </FDXRateRequest>';
//print($str);
$header[] = "Host: www.smart-shop.com";
$header[] = "MIME-Version: 1.0";
$header[] = "Content-type: multipart/mixed; boundary=----doc";
$header[] = "Accept: text/xml";
$header[] = "Content-length: ".strlen($str);
$header[] = "Cache-Control: no-cache";
$header[] = "Connection: close \r\n";
$header[] = $str;
$ch = curl_init();
//Disable certificate check.
// uncomment the next line if you get curl error 60: error setting certificate verify locations
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
// uncommenting the next line is most likely not necessary in case of error 60
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
//-------------------------
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
//curl_setopt($ch, CURLOPT_CAINFO, "c:/ca-bundle.crt");
//-------------------------
curl_setopt($ch, CURLOPT_URL,$this->server);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 4);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST,'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$data = curl_exec($ch);
if (curl_errno($ch)) {
$this->getPrice();
} else {
// close curl resource, and free up system resources
curl_close($ch);
$xmlParser = new xmlparser();
$array = $xmlParser->GetXMLTree($data);
//$xmlParser->printa($array);
if(count($array['FDXRATEREPLY'][0]['ERROR'])) { // If it is error
$error = new fedexError();
$error->number = $array['FDXRATEREPLY'][0]['ERROR'][0]['CODE'][0]['VALUE'];
$error->description = $array['FDXRATEREPLY'][0]['ERROR'][0]['MESSAGE'][0]['VALUE'];
$error->response = $array;
$this->error = $error;
} else if (count($array['FDXRATEREPLY'][0]['ESTIMATEDCHARGES'][0]['DISCOUNTEDCHARGES'][0]['NETCHARGE'])) {
$price = new fedexPrice();
$price->rate = $array['FDXRATEREPLY'][0]['ESTIMATEDCHARGES'][0]['DISCOUNTEDCHARGES'][0]['NETCHARGE'][0]['VALUE'];
$price->service = $this->serviceName;
$price->response = $array;
$this->price = $price;
}
//print_r($this);
return $this;
}
}
}
class fedexError
{
var $number;
var $description;
var $response;
}
class fedexPrice
{
var $service;
var $rate;
var $response;
}
?>
Below is the second file called xmlparser.php
<?php
class xmlparser
{
function GetChildren($vals, &$i)
{
$children = array();
if (isset($vals[$i]['value']))
$children['VALUE'] = $vals[$i]['value'];
while (++$i < count($vals))
{
switch ($vals[$i]['type'])
{
case 'cdata':
if (isset($children['VALUE']))
$children['VALUE'] .= $vals[$i]['value'];
else
$children['VALUE'] = $vals[$i]['value'];
break;
case 'complete':
if (isset($vals[$i]['attributes'])) {
$children[$vals[$i]['tag']][]['ATTRIBUTES'] = $vals[$i]['attributes'];
$index = count($children[$vals[$i]['tag']])-1;
if (isset($vals[$i]['value']))
$children[$vals[$i]['tag']][$index]['VALUE'] = $vals[$i]['value'];
else
$children[$vals[$i]['tag']][$index]['VALUE'] = '';
} else {
if (isset($vals[$i]['value']))
$children[$vals[$i]['tag']][]['VALUE'] = $vals[$i]['value'];
else
$children[$vals[$i]['tag']][]['VALUE'] = '';
}
break;
case 'open':
if (isset($vals[$i]['attributes'])) {
$children[$vals[$i]['tag']][]['ATTRIBUTES'] = $vals[$i]['attributes'];
$index = count($children[$vals[$i]['tag']])-1;
$children[$vals[$i]['tag']][$index] = array_merge($children[$vals[$i]['tag']][$index],$this->GetChildren($vals, $i));
} else {
$children[$vals[$i]['tag']][] = $this->GetChildren($vals, $i);
}
break;
case 'close':
return $children;
}
}
}
function GetXMLTree($xml)
{
$data = $xml;
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($parser, $data, $vals, $index);
xml_parser_free($parser);
//print_r($index);
$tree = array();
$i = 0;
if (isset($vals[$i]['attributes'])) {
$tree[$vals[$i]['tag']][]['ATTRIBUTES'] = $vals[$i]['attributes'];
$index = count($tree[$vals[$i]['tag']])-1;
$tree[$vals[$i]['tag']][$index] = array_merge($tree[$vals[$i]['tag']][$index], $this->GetChildren($vals, $i));
}
else
$tree[$vals[$i]['tag']][] = $this->GetChildren($vals, $i);
return $tree;
}
function printa($obj) {
global $__level_deep;
if (!isset($__level_deep)) $__level_deep = array();
if (is_object($obj))
print '[obj]';
elseif (is_array($obj)) {
foreach(array_keys($obj) as $keys) {
array_push($__level_deep, "[".$keys."]");
$this->printa($obj[$keys]);
array_pop($__level_deep);
}
}
else print implode(" ",$__level_deep)." = $obj\n";
}
}
?>
Last file below called index.php
<?php
require_once("xmlparser.php");
class Fedex {
// Variables
var $server = "https://gatewaybeta.fedex.com/GatewayDC";
var $accountNumber;
var $meterNumber;
var $carrierCode = "FDXG";
var $dropoffType = "REGULARPICKUP";
var $service;
var $serviceName;
var $packaging = "YOURPACKAGING";
var $weightUnits = "LBS";
var $weight;
// Origin Address
var $originStateOrProvinceCode;
var $originPostalCode;
var $originCountryCode;
// Destination Address
var $destStateOrProvinceCode;
var $destPostalCode;
var $destCountryCode;
var $payorType = "SENDER";
// Functions
function setServer($server) {
$this->server = $server;
}
function setAccountNumber($accountNumber) {
$this->accountNumber = $accountNumber;
}
function setMeterNumber($meterNumber) {
$this->meterNumber = $meterNumber;
}
function setCarrierCode($carrierCode) {
$this->carrierCode = $carrierCode;
}
function setDropoffType($dropoffType) {
$this->dropoffType = $dropoffType;
}
function setService($service, $name) {
$this->service = $service;
$this->serviceName = $name;
}
function setPackaging($packaging) {
$this->packaging = $packaging;
}
function setWeightUnits($units) {
$this->weightUnits = $units;
}
function setWeight($weight) {
$this->weight = $weight;
}
function setOriginStateOrProvinceCode($code) {
$this->originStateOrProvinceCode = $code;
}
function setOriginPostalCode($code) {
$this->originPostalCode = $code;
}
function setOriginCountryCode($code) {
$this->originCountryCode = $code;
}
function setDestStateOrProvinceCode($code) {
$this->destStateOrProvinceCode = $code;
}
function setDestPostalCode($code) {
$this->destPostalCode = $code;
}
function setDestCountryCode($code) {
$this->destCountryCode = $code;
}
function setPayorType($type) {
$this->payorType = $type;
}
function getPrice() {
$str = '<?xml version="1.0" encoding="UTF-8" ?>';
$str .= ' <FDXRateRequest xmlns:api="http://www.fedex.com/fsmapi" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FDXRateRequest.xsd">';
$str .= ' <RequestHeader>';
$str .= ' <CustomerTransactionIdentifier>Express Rate</CustomerTransactionIdentifier>';
$str .= ' <AccountNumber>'.$this->accountNumber.'</AccountNumber>';
$str .= ' <MeterNumber>'.$this->meterNumber.'</MeterNumber>';
$str .= ' <CarrierCode>'.$this->carrierCode.'</CarrierCode>';
$str .= ' </RequestHeader>';
$str .= ' <DropoffType>'.$this->dropoffType.'</DropoffType>';
$str .= ' <Service>'.$this->service.'</Service>';
$str .= ' <Packaging>'.$this->packaging.'</Packaging>';
$str .= ' <WeightUnits>'.$this->weightUnits.'</WeightUnits>';
$str .= ' <Weight>'.number_format($this->weight, 1, '.', '').'</Weight>';
$str .= ' <OriginAddress>';
$str .= ' <StateOrProvinceCode>'.$this->originStateOrProvinceCode.'</StateOrProvinceCode>';
$str .= ' <PostalCode>'.$this->originPostalCode.'</PostalCode>';
$str .= ' <CountryCode>'.$this->originCountryCode.'</CountryCode>';
$str .= ' </OriginAddress>';
$str .= ' <DestinationAddress>';
$str .= ' <StateOrProvinceCode>'.$this->destStateOrProvinceCode.'</StateOrProvinceCode>';
$str .= ' <PostalCode>'.$this->destPostalCode.'</PostalCode>';
$str .= ' <CountryCode>'.$this->destCountryCode.'</CountryCode>';
$str .= ' </DestinationAddress>';
$str .= ' <Payment>';
$str .= ' <PayorType>'.$this->payorType.'</PayorType>';
$str .= ' </Payment>';
$str .= ' <PackageCount>'.ceil(bcdiv(number_format($this->weight, 1, '.', ''), '150', 3)).'</PackageCount>';
$str .= ' </FDXRateRequest>';
//print($str);
$header[] = "Host: www.smart-shop.com";
$header[] = "MIME-Version: 1.0";
$header[] = "Content-type: multipart/mixed; boundary=----doc";
$header[] = "Accept: text/xml";
$header[] = "Content-length: ".strlen($str);
$header[] = "Cache-Control: no-cache";
$header[] = "Connection: close \r\n";
$header[] = $str;
$ch = curl_init();
//Disable certificate check.
// uncomment the next line if you get curl error 60: error setting certificate verify locations
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
// uncommenting the next line is most likely not necessary in case of error 60
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
//-------------------------
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
//curl_setopt($ch, CURLOPT_CAINFO, "c:/ca-bundle.crt");
//-------------------------
curl_setopt($ch, CURLOPT_URL,$this->server);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 4);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST,'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$data = curl_exec($ch);
if (curl_errno($ch)) {
$this->getPrice();
} else {
// close curl resource, and free up system resources
curl_close($ch);
$xmlParser = new xmlparser();
$array = $xmlParser->GetXMLTree($data);
//$xmlParser->printa($array);
if(count($array['FDXRATEREPLY'][0]['ERROR'])) { // If it is error
$error = new fedexError();
$error->number = $array['FDXRATEREPLY'][0]['ERROR'][0]['CODE'][0]['VALUE'];
$error->description = $array['FDXRATEREPLY'][0]['ERROR'][0]['MESSAGE'][0]['VALUE'];
$error->response = $array;
$this->error = $error;
} else if (count($array['FDXRATEREPLY'][0]['ESTIMATEDCHARGES'][0]['DISCOUNTEDCHARGES'][0]['NETCHARGE'])) {
$price = new fedexPrice();
$price->rate = $array['FDXRATEREPLY'][0]['ESTIMATEDCHARGES'][0]['DISCOUNTEDCHARGES'][0]['NETCHARGE'][0]['VALUE'];
$price->service = $this->serviceName;
$price->response = $array;
$this->price = $price;
}
//print_r($this);
return $this;
}
}
}
class fedexError
{
var $number;
var $description;
var $response;
}
class fedexPrice
{
var $service;
var $rate;
var $response;
}
?>