Sending email via PHP Script - php

I'm using a wamp server, and I've used this php script before when sending form values to an email..and it worked perfect before! I can't find what I've done with the code, or it might be something spooking with my wamp server, because it's not sending anymore and I get the error message: There was a problem sending your message.
Code:
// Create the form
$contactForm = new JFormer('contactForm', array(
'submitButtonText' => 'Send Message',
));
// Add components to the form
$contactForm->addJFormComponentArray(array(
new JFormComponentSingleLineText('artistname', 'Artist Name:', array(
'validationOptions' => array('required'),
'tip' => '<p>Enter your artist name.</p>'
)),
new JFormComponentSingleLineText('trackname', 'Track Name:', array(
'tip' => '<p>Enter your track name.</p>',
'validationOptions' => array('required'),
)),
new JFormComponentSingleLineText('email', 'E-mail Address:', array(
'tip' => '<p>Enter your email address.</p>',
'validationOptions' => array('required'),
)),
new JFormComponentSingleLineText('stream', 'Link to Stream:</br>(if applicable)', array(
'tip' => '<p>Enter your link to stream.</p>'
)),
new JFormComponentSingleLineText('download', 'Download Link:', array(
'tip' => '<p>Enter your download link.</p>',
'validationOptions' => array('required'),
)),
new JFormComponentMultipleChoice('multipleChoiceType', 'Full Track or Clip:',
array(
array('label' => 'Full Track', 'value' => 'fulltrack'),
array('label' => 'Clip', 'value' => 'clip'),
),
array(
'multipleChoiceType' => 'radio',
)),
new JFormComponentSingleLineText('downloadorpurchase', 'Free Download or
Purchase Link</br>(To be included in video description)', array(
'tip' => '<p>Enter your link.</p>',
)),
new JFormComponentSingleLineText('releasedate', 'Release Date:</br>(if applicable)', array(
'tip' => '<p>Enter the release date.</p>',
)),
new JFormComponentTextArea('artistandlabel', 'Artist / Label Links:</br>(To be included in description.)', array(
'validationOptions' => array('required'),
'tip' => '<p>Enter your description.</p>',
)),
new JFormComponentMultipleChoice('iagree', 'I confirm that I own full
copyright rights and grant the THU Records to post my music in their videos. I
understand that content may be monetized with adverts.',
array(
array('label' => 'I Accept', 'value' => 'accepted'),
array('label' => 'I Do Not Accept', 'value' => 'dontaccepted'),
),
array(
'iagree' => 'radio',
'validationOptions' => array('required'),
)),
));
// Set the function for a successful form submission
function onSubmit($formValues) {
// Concatenate the name
if(!empty($formValues->name->middleInitial)) {
$name = $formValues->name->firstName . ' ' . $formValues->name->middleInitial . ' ' . $formValues->name->lastName;
}
else {
$name = $formValues->name->firstName . ' ' . $formValues->name->lastName;
}
// Prepare the variables for sending the mail
$to = 'lill_z4ck3#hotmail.com';
$fromAddress = $formValues->email;
$trackName = $formValues->trackname;
$streamLink = $formValues->stream;
$download = $formValues->download;
$trackorclip = $formValues->multipleChoiceType;
$downloadOrPurchase = $formValues->downloadorpurchase;
$releaseDate = $formValues->releasedate;
$artistAndLabel = $formValues->artistandlabel;
$agreement = $formValues->iagree;
$artistName = $formValues->artistname;
$subject = "Submit from ".$formValues->artistname;
$message = "Artist Name : ".$artistName."\nTrack Name : ".$trackName."\n
Email : ".$fromAddress."\n Stream Link : ".$streamLink."\nDownload link
: ".$download."\nTrack or Clip : ".$trackorclip."\nDownload or Purchase
: ".$downloadOrPurchase."\n Release Date : ".$releaseDate."\n Artist
and Label Info : ".$artistAndLabel."\n Agreement : ".$agreement;
// Use the PHP mail function
$mail = mail($to, $subject, $message);
// Send the message
if($mail) {
$response['successPageHtml'] = '
<h1>Thanks for Contacting Us</h1>
<p>Your message has been successfully sent.</p>
';
}
else {
$response['failureNoticeHtml'] = '
There was a problem sending your message.
';
}
return $response;
}
// Process any request to the form
$contactForm->processRequest();
Do anyone of you have any idea what could be wrong? :(

The mail() function usually doesn't work by default for things like WAMP. You will need to add details of your SMTP server to the php.ini file and then configure some other settings.
This is a nice tutorial: http://roshanbh.com.np/2007/12/sending-e-mail-from-localhost-in-php-in-windows-environment.html
Hope this helps.

Related

Invalid parameter Facebook video ad creative in Facebook Marketing API

I am getting the same error while creating Ad Creative via Facebook Marketing API. I followed their guide but doesn't work. Facebook video ad creative reference
$config = Config::get('facebook');
$data['account_id'] = 'act_'.$config['ad_account_id'];
$data['page_id'] = $config['page_id'];
// Init facebook
$api = Api::init($config['app_id'], $config['app_secret'], $config['access_token']);
// Create product catalog
$product_catalog = new ProductCatalog(null, $config['business_id']);
$product_catalog->setData(array(
ProductCatalogFields::NAME => "Catalog",
));
$product_catalog->create();
$product_catalog_id = $product_catalog->id;
// Setup Feed
$product_feed = new ProductFeed(null, $product_catalog_id);
$product_feed->setData(array(
ProductFeedFields::NAME => 'Campaign Feed',
ProductFeedFields::SCHEDULE => array(
ProductFeedScheduleFields::INTERVAL => 'DAILY',
ProductFeedScheduleFields::URL => 'http://example.com/facebook/dpa_product_catalog_sample_feed.csv',
ProductFeedScheduleFields::HOUR => 22,
),
));
$product_feed = $product_feed->create();
// Create Product Set
$product_set = new ProductSet(null, $product_catalog_id);
$product_set->setData(array(
ProductFeedFields::NAME => 'All Product',
));
$product_set->create();
$data['product_set_id'] = $product_set->id;
$video = new Advideo(null, $data['account_id']);
$video->{AdVideoFields::SOURCE} = public_path().'/facebook/video-demo.mp4';
$video->create();
$video_data = new AdCreativeVideoData();
$video_data->setData(array(
AdCreativeVideoDataFields::IMAGE_URL => 'http://example.com/facebook/resize-image.jpg',
AdCreativeVideoDataFields::VIDEO_ID => $video->id,
AdCreativeVideoDataFields::CALL_TO_ACTION => array(
'type' => AdCreativeCallToActionTypeValues::LIKE_PAGE,
'value' => array(
'page' => $data['page_id'],
),
),
));
$object_story_spec = new AdCreativeObjectStorySpec();
$object_story_spec->setData(array(
AdCreativeObjectStorySpecFields::PAGE_ID => $data['page_id'],
AdCreativeObjectStorySpecFields::VIDEO_DATA => $video_data,
));
Above these code working and return response but when I call ad creative, the API return "Invalid parameter"
$creative = new AdCreative(null, $data['account_id']);
$creative->setData(array(
AdCreativeFields::NAME => 'Video Ad Template Creative Sample',
AdCreativeFields::OBJECT_STORY_SPEC => $object_story_spec,
AdCreativeFields::PRODUCT_SET_ID => $data['product_set_id'],
));
$creative->create();
Might be your issue is in creating AdCreativeVideoData.
search for line
AdCreativeVideoDataFields::IMAGE_URL => public_path().'/facebook/resize-image.jpg',
Here IMAGE_URL requires url path like http://example.com/myimage.jpg. You are giving directory path that might cause problem.
If your image is not directly accessible from URL then you should create IMAGE_HASH. For this see below.
try {
$image = new AdImage(null, $data['account_id']);
$image->{AdImageFields::FILENAME} = public_path().'/facebook/resize-image.jpg';
$image->create();
// Image_hash = $image->hash
} catch (Exception $e) {
echo 'Error message: ' . $e->getMessage() . "\n" . "<br/>";
echo 'Error Code: ' . $e->getCode() . "<br/>";
}
And replace IMAGE_URL to IMAGE_HASH in your AdCreativeVideoData like this
$video_data = new AdCreativeVideoData();
$video_data->setData(array(
AdCreativeVideoDataFields::IMAGE_HASH => $image->hash,
AdCreativeVideoDataFields::VIDEO_ID => $video->id,
AdCreativeVideoDataFields::CALL_TO_ACTION => array(
'type' => AdCreativeCallToActionTypeValues::LIKE_PAGE,
'value' => array(
'page' => $data['page_id'],
),
),
));

WordPress: Form posting but php script not executing

My goal is to have the user fill out a form with country and postal code, post the data to a php script that makes a call to fedex's server and returns shipment rates.
I have successfully accomplished this on my local web server, but upon implementation to my WordPress site, the php script does not execute when the form data is posted. My code is as follows:
rate.php (form and php script both in this file):
<!-- FORM -->
<h1 style="font-family: "Ek Mukta", sans-serif;">Quick Quote</h1>
<br>
<form id="quick-quote" class="" action="" method="post">
<label>Country</label>
<br>
<input id="country" type="text" name="country" value="">
<br>
<label>Postal Code</label>
<br>
<input id="postal" type="text" name="postal" value="">
<br>
<br>
<input id="submit" type="submit" name="" value="submit">
</form>
<br>
<!-- FEDEX CALL -->
<?php
print_r($_POST); //this works!
error_reporting(E_ALL);
session_start();
require_once('../../library/fedex-common.php'); //code seems to break here
$newline = "<br />";
//The WSDL is not included with the sample code.
//Please include and reference in $path_to_wsdl variable.
$path_to_wsdl = "RateService/RateService_v20.wsdl";
ini_set("soap.wsdl_cache_enabled", "0");
$client = new SoapClient($path_to_wsdl, array('trace' => 1)); // Refer to http://us3.php.net/manual/en/ref.soap.php for more information
$request['WebAuthenticationDetail'] = array(
'UserCredential' =>array(
'Key' => getProperty('key'),
'Password' => getProperty('password')
)
);
$request['ClientDetail'] = array(
'AccountNumber' => getProperty('shipaccount'),
'MeterNumber' => getProperty('meter')
);
$request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Request v20 using PHP ***');
$request['Version'] = array(
'ServiceId' => 'crs',
'Major' => '20',
'Intermediate' => '0',
'Minor' => '0'
);
$request['ReturnTransitAndCommit'] = true;
$request['RequestedShipment']['DropoffType'] = 'REGULAR_PICKUP'; // valid values REGULAR_PICKUP, REQUEST_COURIER, ...
$request['RequestedShipment']['ShipTimestamp'] = date('c');
$request['RequestedShipment']['ServiceType'] = 'INTERNATIONAL_ECONOMY'; // valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ...
$request['RequestedShipment']['PackagingType'] = 'YOUR_PACKAGING'; // valid values FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ...
$request['RequestedShipment']['TotalInsuredValue']=array('Ammount'=>0,'Currency'=>'USD');
$request['RequestedShipment']['Shipper'] = addShipper();
$request['RequestedShipment']['Recipient'] = addRecipient();
$request['RequestedShipment']['VariableHandlingChargeDetail'] = addHandlingCharge();
$request['RequestedShipment']['ShippingChargesPayment'] = addShippingChargesPayment();
//$request['RequestedShipment']['RateRequestTypes'] = addRateType();
$request['RequestedShipment']['RateRequestTypes'] = 'LIST';
// $request['RequestedShipment']['RateRequestTypes'] = 'PREFERRED ';
$request['RequestedShipment']['PackageCount'] = '1';
$request['RequestedShipment']['RequestedPackageLineItems'] = addPackageLineItem1();
try
{
if(setEndpoint('changeEndpoint'))
{
$newLocation = $client->__setLocation(setEndpoint('endpoint'));
}
$response = $client ->getRates($request);
if ($response -> HighestSeverity != 'FAILURE' && $response -> HighestSeverity != 'ERROR')
{
$rateReply = $response -> RateReplyDetails;
echo '<table>';
$country = $_POST['country'];
$postal = $_POST['postal'];
$productPrice = 100;
$serviceFee = 50;
echo $country;
// echo '<tr><td>Country Code </td><td>Postal Code</td><td>Service Type</td><td>Amount</td><td>Delivery Date</td></tr><tr>';
$serviceType = '<td>'.$rateReply -> ServiceType . '</td>';
$amount = number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalVariableHandlingCharges->TotalCustomerCharge->Amount,2,".",",");
if(array_key_exists('DeliveryTimestamp',$rateReply)){
$deliveryDate= '<td>' . $rateReply->DeliveryTimestamp . '</td>';
}else if(array_key_exists('TransitTime',$rateReply)){
$deliveryDate= '<td>' . $rateReply->TransitTime . '</td>';
}else {
$deliveryDate='<td> </td>';
}
$total = $productPrice + $serviceFee + $amount;
// echo "<td>$country</td>. <td>$postal</td>. $serviceType. <td>$amount</td>. $deliveryDate";
// echo '</tr>';
// echo '</table>';
echo
"
<h3>Country Code: $country</h3>
<h3>Postal Code: $postal</h3>
<br>
<table>
<tr>
<td>Product Cost</td>
<td>Shipping Cost</td>
<td>Service Fee</td>
<td>Total</td>
</tr>
<br>
<tr>
<td>$$productPrice<span>+</span></td>
<td>$$amount<span>+</span></td>
<td>$$serviceFee<span>=</span></td>
<td>$$total </td>
</tr>
</table>";
printSuccess($client, $response);
}
else
{
printError($client, $response);
}
writeToLog($client); // Write to log file
} catch (SoapFault $exception) {
printFault($exception, $client);
}
//FUNCTIONS
function addShipper(){
$shipper = array(
'Contact' => array(
'PersonName' => 'XXX',
'CompanyName' => 'XXX',
'PhoneNumber' => 'XXX'),
'Address' => array(
'StreetLines' => array('Address Line 1'),
'City' => 'New York',
'StateOrProvinceCode' => 'XXX',
'PostalCode' => 'XXXX',
'CountryCode' => 'US')
);
return $shipper;
}
function addRecipient(){
$country = $_POST['country'];
$postal = $_POST['postal'];
$recipient = array(
'Contact' => array(
'PersonName' => 'Recipient Name',
'CompanyName' => 'Company Name',
'PhoneNumber' => 'XXX'
),
'Address' => array(
'StreetLines' => array('Address Line 1'),
'City' => '',
'StateOrProvinceCode' => '',
'PostalCode' => ''.$postal.'',
'CountryCode' => ''.$country.'',
'Residential' => false)
);
return $recipient;
}
//HANDLING CHARGE
function addHandlingCharge(){
$VariableHandlingChargeDetail = array(
'RateTypeBasis' => 'LIST',
'RateElementBasis' => 'BASE_CHARGE', // valid values NET_CHARGE, NET_CHARGE_EXCLUDING_TAXES, NET_FREIGHT
'FixedValue' => array('Currency' => 'USD', 'Amount' => 0),
'PercentValue' => '0',
);
return $VariableHandlingChargeDetail;
};
function addShippingChargesPayment(){
$shippingChargesPayment = array(
'PaymentType' => 'SENDER', // valid values RECIPIENT, SENDER and THIRD_PARTY
'Payor' => array(
'ResponsibleParty' => array(
'AccountNumber' => getProperty('billaccount'),
// 'PostalCode' => '10036',
'CountryCode' => 'US')
)
);
return $shippingChargesPayment;
}
function addLabelSpecification(){
$labelSpecification = array(
'LabelFormatType' => 'COMMON2D', // valid values COMMON2D, LABEL_DATA_ONLY
'ImageType' => 'PDF', // valid values DPL, EPL2, PDF, ZPLII and PNG
'LabelStockType' => 'PAPER_7X4.75');
return $labelSpecification;
}
function addSpecialServices(){
$specialServices = array(
'SpecialServiceTypes' => array('COD'),
'CodDetail' => array(
'CodCollectionAmount' => array('Currency' => 'USD', 'Amount' => 150),
'CollectionType' => 'ANY')// ANY, GUARANTEED_FUNDS
);
return $specialServices;
}
function addPackageLineItem1(){
$packageLineItem = array(
'SequenceNumber'=>1,
'GroupPackageCount'=>1,
'Weight' => array(
'Value' => 2,
'Units' => 'LB'
),
'Dimensions' => array(
'Length' => 2,
'Width' => 2,
'Height' => 2,
'Units' => 'IN'
)
);
return $packageLineItem;
}
?>
quick-quote.php (template file to include feature on specific pages):
<?php /* Template Name: quick-quote */ ?>
<?php
get_header();
include('RateService_v20_php/RateAvailableServicesService_v20_php/php/RateWebServiceClient/RateAvailableServices/RateAvailableServicesWebServiceClient.php');
get_footer();
?>
functions.php (relevant code only):
add_action( 'admin_post_quick_quote', 'prefix_admin_quick_quote' );
function prefix_admin_quick_quote() {
// What do I do here!?
}
The issue that I have having is this:
-I fill out the form
-hit submit
-print_r($_POST) the data to see if form posted correctly (it does)
-any code after require_once('../../library/fedex-common.php'); does not execute
Things I have already checked/tried:
-PHP and SOAP are installed correctly on the server
-all files are excessible 664 not 666
-ran the file on the server, it works fine
-setting the form's action to "rate.php" or "quick-quote.php" (form posts data to same page so I think this can be left blank)
-made sure ('../../library/fedex-common.php') is the correct path
So my questions are:
-How do I make the php script execute after the form is submitted?
-Is this accomplished using functions.php to hook into admin-post.php?
Thanks so much!
It sounds like PHP does not have access to fedex-common.php.
Change the relative path for the 'require_once` to an absolute path.
Check that the application has permissions to the directory.
Check that the application has permissions to execute the file.
Additionally, you can check that the include is success by replacing the 'require_once' with the following to further determine if the issue actually a side effect of the file location or an issue with the referenced file.
if(!#include_once("/PATH/TO/library/fedex-common.php")) {
throw new Exception ('fedex-common.php does not exist');
}

Laravel push notifications

I'm using this library: https://github.com/davibennun/laravel-push-notification for sending push notifications. I used the example code and the push messages to my iPhone are working.
Only now I want to send 1 message to multiple devices. The docs say that I need to use:
$devices = PushNotification::DeviceCollection(array(
PushNotification::Device('token', array('badge' => 5)),
PushNotification::Device('token1', array('badge' => 1)),
PushNotification::Device('token2')
));
$message = PushNotification::Message('Message Text',array(
'badge' => 1,
'sound' => 'example.aiff',
'actionLocKey' => 'Action button title!',
'locKey' => 'localized key',
'locArgs' => array(
'localized args',
'localized args',
),
'launchImage' => 'image.jpg',
'custom' => array('custom data' => array(
'we' => 'want', 'send to app'
))
));
$collection = PushNotification::app('appNameIOS')
->to($devices)
->send($message);
// get response for each device push
foreach ($collection->pushManager as $push) {
$response = $push->getAdapter()->getResponse();
}
But I want a foreach loop from my database on the devicecollection. How do I do that with laravel? Many thanks!
foreach($usersApple as $userApple){
echo $userApple->reg_id . '<br>';
$deviceslist[] = PushNotification::Device($userApple->reg_id);
}
$devices = PushNotification::DeviceCollection($deviceslist);
Already fixed, was not sharp today haha

Campaign Monitor php sdk - add Subscribe bug - no longer showing on list

I am working on a campaign monitor api which creates a custom list with custom fields.
When I try and add subscribers it used to work, now when I look at the list its not added them. Although its still returning a success code 201.
function addSubscriber($list_id, $emailAddress, $name, $title, $showName, $showDate, $showTime){
//create subscriber
$subscriber = array(
'EmailAddress' => $emailAddress,
'Name' => $name,
'CustomFields' => array(
array(
'Key' => "Title",
'Value' => $title
),
array(
'Key' => "ShowName",
'Value' => $showName
),
array(
'Key' => "ShowDate",
'Value' => $showDate
),
array(
'Key' => "ShowTime",
'Value' => $showTime
)
),
'Resubscribe' => true,
'RestartSubscriptionBasedAutoResponders' => true
);
//print_r($subscriber);
$subwrap = new CS_REST_Subscribers($list_id, $this->auth);
$result = $subwrap->add($subscriber);
//var_dump($result->response);
echo "Result of POST /api/v3.1/subscribers/{list id}.{format}\n<br />";
if($result->was_successful()) {
echo "Subscribed with code ".$result->http_status_code;
} else {
echo 'Failed with code '.$result->http_status_code."\n<br /><pre>";
var_dump($result->response);
echo '</pre>';
}
return $result->response;
}
This code is working for me.You need to add campaign monitor class files in you project folder and use valid list id and api key.You can find you api key from manage account link and list id from click on (change name/type) below list title. Please wait some time to see in you list.
require_once 'csrest_subscribers.php';
$name=$_POST['name'];
$email=$_POST['email'];
$wrap = new CS_REST_Subscribers('Your list ID', 'Your API Key');
$result = $wrap->add(array(
'EmailAddress' => $email,
'Name' => $name,
'CustomFields' => array(), // no custom fields, can remove this line completely
'Resubscribe' => true
));
echo "Result of POST /api/v3/subscribers/{list id}.{format}\n<br />";
if($result->was_successful()) {
echo "Subscribed with code ".$result->http_status_code;
} else {
echo 'Failed with code '.$result->http_status_code."\n<br /><pre>";
var_dump($result->response);
echo '</pre>';
}

AWS SES on PHP error: Unable to determine service/operation name to be authorized

I am trying to send email using AWS SES using the following PHP script:
<?php
require_once("phar://aws.phar");
use Aws\Ses\SesClient;
//Open client
$client = SesClient::factory(array(
"key" => "key",
"secret" => "secret",
"region" => "region"
));
$subject = "subject";
$messageText = "text message";
$messageHtml = "<h1>formatted message</h1>";
//Send email
try{
$response = $client->sendEmail(
array(
'Source' => 'verified_email#domain.com',
'Destination' => array(
'ToAddresses' => array('an_address#domain.com')
),
'Message' => array(
'Subject' => array('Data' => $subject),
'Body' => array('Text' => array('Data' => $messageText)),
'Html' => array('Data' => $messageHtml)
)
)
);
}catch(Exception $e){
//An error happened and the email did not get sent
echo($e->getMessage());
}
?>
Whenever I run this, it goes to the catch clause and prints to the screen the message:
Unable to determine service/operation name to be authorized
This doesn't really give me any information on what's wrong and there's no documentation on the API page about this. Any ideas?

Categories