Laravel send mail with multiple product information - php

i have implemented multiple product upload and save the details to Database, i need to send the mail with inserted multiple product data to mail
My Controller:
public function store(Request $request)
{
$input = Input::all();
$destinationPath = public_path() . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'trade'; // upload path
$files = Input::file('file');
$length = 6;
$randomString = substr(str_shuffle("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
$trade = Trade::create(array(
'id' => $request->get('id'),
'first_name' => $request->get('first_name'),
'last_name' => $request->get('last_name'),
'address1' => $request->get('address1'),
'address2' => $request->get('address2'),
'zip_code' => $request->get('zip_code'),
'country' => $request->get('country'),
'email' => $request->get('email'),
'phone' => $request->get('phone'),
'bank_name' => $request->get('bank_name'),
'account_number' => $request->get('account_number'),
'iban_number' => $request->get('iban_number'),
'swift_number' => $request->get('swift_number'),
'voucher_code' => $randomString . $request->get('voucher_code'),
));
foreach ($input['purchase_item'] as $k => $v) {
$file = $input['file'][$k];
if (!file_exists($destinationPath)) {
mkdir($destinationPath, 0777, true);
}
$extension = $file->getClientOriginalExtension();
$file_name = time() . '_' . $file->getClientOriginalName();
$fileName = $file_name; // renameing image
$file->move($destinationPath, $fileName);
$timestamp = strtotime($input['purchase_date'][$k]);
$new_date = date('Y-m-d', $timestamp);
$tradeins_products = TradeProduct::create(array(
'tradins_id' => $trade->id,
'product_id' => $input['product_id'][$k],
'application_id' => $input['application_id'][$k],
'brand_id' => $input['brand_id'][$k],
'purchase_date' => $new_date,
'purchase_item' => $input['purchase_item'][$k] ,
'file' => $fileName
));
$data = array(
'first_name' => $request->get('first_name'),
'last_name' => $request->get('last_name'),
'email' => $request->get('email'),
'product_name' => $tradein_product_name[0]['name'],
'address' => $request->get('address1'),
'phone' => $request->get('phone'),
'bank_name' => $request->get('bank_name'),
'account_number' => $request->get('account_number'),
'purchase_date'=>$new_date,
'country_email'=>$country_name[0]['email'],
'country_address1' =>$country_name[0]['address_1'],
'country_address2'=>$country_name[0]['address_2'],
'country_city'=>$country_name[0]['city'],
'country_state'=>$country_name[0]['state'],
'country_zipcode'=>$country_name[0]['zipcode'],
'voucher_code'=>$trade->voucher_code
);
Mail::send('frontend.mail_trade', $data, function($message) use ($data){
$message->to($data['email'], $data['first_name'].' '.$data['last_name'])->subject('Product Trade-in');
return Response::json(array('voucher_code' => $trade- >voucher_code,'first_name'=>$trade->first_name,'email'=>$trade->email,'phone'=>$trade->phone,'address1'=>$trade->address1,'zip_code'=>$trade->zip_code,'country'=>$trade->country,'country_name' => $country_name[0]['name'],'voucher_code1' => $trade->voucher_code,'country_address1' =>$country_name[0]['address_1'],'country_address2'=>$country_name[0]['address_2'],'country_city' =>$country_name[0]['city'],'country_state' =>$country_name[0]['state'],'country_zipcode' =>$country_name[0]['zipcode'], 'country_email' =>$country_name[0]['email'], 'company_name' => $country_name[0]['company_name']));
}
So Above i done inserting two tables, tradin, and tradein products, so tradein products contain multiple product upload and insertion, so i need to show like below on mail
Product Data:
1)product name
-Sony
-Samsung
2)Application Name:
-Handsfree
-Wireless
So how is this possible with using foreach or any other alternate way to do it to show the Data's in mail template,
My Mail Template:
<h3>Cash Back</h3>
<p>Product Name:{{$product_name}} </p>
<p>Name: {{$first_name}} {{$last_name}}
</p>
<p>Address: {{$address}}</p>
<p>Phone:{{$phone}} </p>
<p>Bank: {{$bank_name}}</p>
<p>Account Number:{{$account_number}} </p>
<p>Voucher Code:{{$voucher_code}} </p>
<p>Company Email:{{$country_email}} </p>
<p>Company Address1:{{$country_address1}} </p>
<p>Company Address2:{{$country_address2}} </p>
<p>Company City:{{$country_city}} </p>
<p>Company State:{{$country_state}} </p>
<p>Company Zipcode:{{$country_zipcode}} </p>
<p>Purchase Date: {{$purchase_date}}</p>

Take note that first parameter is your email view, and the second parameter is the data you want to pass to your view. for example:
Mail::send('frontend.mail_trade', $productsData, function($message) use ($data){
// your code
});

Related

Skip image validation and creation in laravel update function

Please am trying to upload 3 different images using the code below. How do I get each of the methods that generates the unique image names to run only when their respective request fields have data or is not empty. thus the form submit should not try generating any image name for afile field when that particular file field is empty.
My update controller function
public function update(Request $request, Product $product)
{
$image = $request->file('primary_image');
$name_gen = md5(rand(1000, 10000)).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url = 'upload/products/'.$name_gen;
$image_1 = $request->file('image_1');
$name_gen = md5(rand(1000, 10000)).'.'.$image_1->getClientOriginalExtension();
Image::make($image_1)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url_1 = 'upload/products/'.$name_gen;
$image_2 = $request->file('image_2');
$name_gen = md5(rand(1000, 10000)).'.'.$image_2->getClientOriginalExtension();
Image::make($image_2)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url_2 = 'upload/products/'.$name_gen;
Product::insert([
'name' => $request->name,
'category' => $request->category,
'price' => $request->price,
'description' => $request->description,
'status' => $request -> status,
'estimated_delivery_time' => $request->estimated_delivery_time,
'available_quantity' => $request->available_quantity,
'colors' => $request->colors,
'supplier_name' => $request->supplier_name,
'supplier_phone' => $request->supplier_phone,
'video_description' => $request->video_description,
'primary_image' => $save_url,
'image_1' => $save_url_1,
'image_2' => $save_url_2,
]);
$notification = array(
'message' => 'Product updated successfully',
'alert-type' => 'success'
);
return redirect()->back()->with($notification);
}
Thanks so much for taking time to review my code
Since you are doing the same name generation process all through, you can use an array and do a foreach loop with an if condition like this:
$my_array = [$request->file('primary_image'), $request->file('image_1'), $request->file('image_2')];
foreach($my_array as $item) {
if($item) {
$image = $item;
$name_gen = md5(rand(1000, 10000)).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url = 'upload/products/'.$name_gen;
}
}
Now this will only generate names for images that are not empty.
UPDATE:
For the insert functionality, I would assume your table fields for the images can have null values, so this doesn't throw an error. Now instead of the code above, do this:
$my_array = [$request->file('primary_image'), $request->file('image_1'), $request->file('image_2')];
$insert_array = [];
foreach($my_array as $item) {
$save_url = '';
if($item) {
$image = $item;
$name_gen = md5(rand(1000, 10000)).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url = 'upload/products/'.$name_gen;
}
array_push($insert_array, $save_url);
}
Now for your insert query, do this:
Product::insert([
'name' => $request->name,
'category' => $request->category,
'price' => $request->price,
'description' => $request->description,
'status' => $request -> status,
'estimated_delivery_time' => $request->estimated_delivery_time,
'available_quantity' => $request->available_quantity,
'colors' => $request->colors,
'supplier_name' => $request->supplier_name,
'supplier_phone' => $request->supplier_phone,
'video_description' => $request->video_description,
'primary_image' => $insert_array[0],
'image_1' => $insert_array[1],
'image_2' => $insert_array[2],
]);
This would work.

How to attach different picture for each product type

I am building an eCommerce website and I want to add different combinations for the same product.
I use jQuery to add extra input fields as well.
I can successfully insert all data related to product_variation things like color, weight, type, qty but except images.
My database tables: products, product_images, product_variations.
In product_variations table I have field product_variation_image which I want to use for storing image for specific product type. I just don't know how to insert image there for specific product type, yes I know I need to use foreach loop but the problem is I'm already using foreach loop for product variation data, I tried so many different things nesting foreach into foreach but nothing seems to work.
P.S product_images table I'm only use for product basic images also for products which don't have any type.
I will leave my code below... with some comments on where the problem might be.
public function product_store(Request $request)
{
// PRODUCT TYPE VARIABLES //
$productTypes = $request->product_type;
$productColors = $request->product_color;
$productWeight = $request->product_weight;
$productQtys = $request->product_qty;
$productPrices = $request->product_variation_price;
$productTypeImages = $request->file('product_variation_image');
// PRODUCT TYPE VARIABLES ENDS //
// PRODUCT COVER IMAGE //
$productCoverImage = $request->file('product_cover_image');
$productCoverImageNewName = hexdec(uniqid()).'.'.$productCoverImage->getClientOriginalExtension();
Image::make($productCoverImage)->resize(917,1000)->save('upload/products/cover-images/'.$productCoverImageNewName);
$productCoverImageLink = 'upload/products/cover-images/'.$productCoverImageNewName;
// PRODUCT COVER IMAGE ENDS //
if(!empty(implode($productTypes))) {
$productId = Products::insertGetId([
'category_id' => $request->category_id,
'sub_category_id' => $request->sub_category_id,
'sub_sub_category_id' => $request->sub_sub_category_id,
'product_name' => $request->product_name,
'product_link' => strtolower(str_replace(' ','-', $request->product_name)),
'product_desc' => $request->product_desc,
'product_short_desc' => $request->product_short_desc,
'product_price' => $request->product_price,
'product_discount' => $request->product_discount,
'product_cover_image' => $productCoverImageLink,
'new_product' => $request->new_product,
'featured' => $request->featured,
'special_offer' => $request->special_offer,
'status' => $request->status,
]);
// PRODUCT TYPE IMAGES //
foreach ($productTypeImages as $img) {
$productTypeImagesNewName = hexdec(uniqid()) . '.' . $img->getClientOriginalExtension();
Image::make($img)->resize(917, 1000)->save('upload/products/product-images/' . $productTypeImagesNewName);
$productTypesImagesLink = 'upload/products/product-images/' . $productTypeImagesNewName;
}
// PRODUCT TYPE IMAGES ENDS //
foreach ($productTypes as $id => $key) {
ProductVariations::insert([
'product_id' => $productId,
'product_type' => $productTypes[$id],
'product_color' => $productColors[$id],
'product_weight' => $productWeight[$id],
//'product_variation_image' => $productTypesImagesLink[$id], <--- PROBLEM HERE
'product_variation_qty' => $productQtys[$id],
'product_variation_price' => $productPrices[$id],
'created_at' => Carbon::now()
]);
}
} else {
$productId = Products::insertGetId([
'category_id' => $request->category_id,
'sub_category_id' => $request->sub_category_id,
'sub_sub_category_id' => $request->sub_sub_category_id,
'product_name' => $request->product_name,
'product_link' => strtolower(str_replace(' ','-', $request->product_name)),
'product_desc' => $request->product_desc,
'product_short_desc' => $request->product_short_desc,
'product_price' => $request->product_price,
'product_discount' => $request->product_discount,
'product_cover_image' => $productCoverImageLink,
'new_product' => $request->new_product,
'featured' => $request->featured,
'special_offer' => $request->special_offer,
'status' => $request->status,
'created_at' => Carbon::now()
]);
}
// PRODUCT MULTIPLE IMAGES //
$productImages = $request->file('product_image');
foreach ($productImages as $productImage) {
$productImagesNewName = hexdec(uniqid()).'.'.$productImage->getClientOriginalExtension();
Image::make($productImage)->resize(917,1000)->save('upload/products/product-images/'.$productImagesNewName);
$productImagesLink = 'upload/products/product-images/'.$productImagesNewName;
ProductImages::insert([
'product_id' => $productId,
'product_image' => $productImagesLink,
'created_at' => Carbon::now()
]);
}
// PRODUCT MULTIPLE IMAGES ENDS //
$notification = array(
'message' => 'Product Inserted!',
'alert-type' => 'success'
);
return redirect()->back()->with($notification);
}
I have come up with different solution.
After inserting product with multiple images and if product has any variations, I redirect user to another page. Where he can select image for each type if he wants to. And I'm inserting only image id from product_images table, to product_variations table field - product_variation_image.
By the way, I use a jQuery plugin called image-picker for that. And now everything works and my client is happy with that.
Product function:
public function product_store(Request $request)
{
// PRODUCT TYPE VARIABLES //
$productTypes = $request->product_type;
$productColors = $request->product_color;
$productWeight = $request->product_weight;
$productQtys = $request->product_qty;
$productPrices = $request->product_variation_price;
$productTypeImages = $request->file('product_variation_image');
// PRODUCT TYPE VARIABLES ENDS //
// PRODUCT COVER IMAGE //
$productCoverImage = $request->file('product_cover_image');
if($productCoverImage) {
$productCoverImageNewName = hexdec(uniqid()) . '.' . $productCoverImage->getClientOriginalExtension();
Image::make($productCoverImage)->resize(917, 1000)->save('upload/products/cover-images/' . $productCoverImageNewName);
$productCoverImageLink = 'upload/products/cover-images/' . $productCoverImageNewName;
} else {
$productCoverImageLink = 'upload/no-image/image.png';
}
// PRODUCT COVER IMAGE ENDS //
if(!empty(implode($productTypes))) {
$productId = Products::insertGetId([
'category_id' => $request->category_id,
'sub_category_id' => $request->sub_category_id,
'sub_sub_category_id' => $request->sub_sub_category_id,
'product_name' => $request->product_name,
'product_link' => strtolower(str_replace(' ','-', $request->product_name)),
'product_desc' => $request->product_desc,
'product_short_desc' => $request->product_short_desc,
'product_price' => $request->product_price,
'product_discount' => $request->product_discount,
'product_cover_image' => $productCoverImageLink,
'new_product' => $request->new_product,
'featured' => $request->featured,
'special_offer' => $request->special_offer,
'status' => $request->status,
]);
foreach ($productTypes as $id => $key) {
ProductVariations::insert([
'product_id' => $productId,
'product_type' => $productTypes[$id],
'product_color' => $productColors[$id],
'product_weight' => $productWeight[$id],
'product_variation_qty' => $productQtys[$id],
'product_variation_price' => $productPrices[$id],
'created_at' => Carbon::now()
]);
}
} else {
$productId = Products::insertGetId([
'category_id' => $request->category_id,
'sub_category_id' => $request->sub_category_id,
'sub_sub_category_id' => $request->sub_sub_category_id,
'product_name' => $request->product_name,
'product_link' => strtolower(str_replace(' ','-', $request->product_name)),
'product_desc' => $request->product_desc,
'product_short_desc' => $request->product_short_desc,
'product_price' => $request->product_price,
'product_discount' => $request->product_discount,
'product_cover_image' => $productCoverImageLink,
'new_product' => $request->new_product,
'featured' => $request->featured,
'special_offer' => $request->special_offer,
'status' => $request->status,
'created_at' => Carbon::now()
]);
}
// PRODUCT MULTIPLE IMAGES //
$productImages = $request->file('product_image');
if($productImages) {
foreach ($productImages as $productImage) {
$productImagesNewName = hexdec(uniqid()) . '.' . $productImage->getClientOriginalExtension();
Image::make($productImage)->resize(917, 1000)->save('upload/products/product-images/' . $productImagesNewName);
$productImagesLink = 'upload/products/product-images/' . $productImagesNewName;
ProductImages::insert([
'product_id' => $productId,
'product_image' => $productImagesLink,
'created_at' => Carbon::now()
]);
}
}
// PRODUCT MULTIPLE IMAGES ENDS //
$notification = array(
'message' => 'Product Inserted!',
'alert-type' => 'success'
);
if(!empty(implode($productTypes))) {
return redirect()->route('admin.product-variations-images-settings', ['id' => $productId])->with($notification);
} else {
return redirect()->route('admin.products')->with($notification);
}
}
Functions for image varations:
public function product_variations_images_settings($id)
{
$productVariations = ProductVariations::where('product_id', $id)->get();
$productImages = ProductImages::where('product_id', $id)->get();
return view('administrator.pages.products.product-variations', compact('productVariations','productImages'));
}
public function product_variations_images_store(Request $request)
{
$productVariationId = $request->id;
$productImageId = $request->product_variation_image;
$array = array_combine($productVariationId, $productImageId);
foreach ($array as $id => $key){
//dd($key);
ProductVariations::findOrFail($id)->update([
'product_variation_image' => $key,
'updated_at' => Carbon::now()
]);
}
$notification = array(
'message' => 'Images Set!',
'alert-type' => 'success'
);
return redirect()->route('admin.products')->with($notification);
}

Laravel inserts two user records at register, how to prevent this?

I am creating an application where I have to insert a user at registration with custom fields. As found online, i customised the create method in the Laravel RegisterController. However, now the application inserts two user records whenever I register a new user. Can someone help me with this please?
Here is the code of my create method in the RegisterController
protected function create(array $data)
{
/********************************************************************************
* CALCULATE ALL THE NEEDED DATA FOR THE USER
********************************************************************************/
// Delete the uncompleted registration
UncompletedRegistration::deleteByEmail($data['email']);
// Set the right values based on the filled values
$compercentagecreative = 0.0;
$compercentagenotcreative = 0.0;
$creativepercent = 0.0;
switch ($data['headjob']) {
case 1:
$compercentagecreative = config('constants.percentageRates.comPercentageCreative.headjob');
$compercentagenotcreative = config('constants.percentageRates.comPercentageNotCreative.headjob');
$creativepercent = config('constants.percentageRates.creativePercent.headjob');
break;
case 2:
$compercentagecreative = config('constants.percentageRates.comPercentageCreative.notheadjob');
$compercentagenotcreative = config('constants.percentageRates.comPercentageNotCreative.notheadjob');
$creativepercent = config('constants.percentageRates.creativePercent.notheadjob');
break;
default:
$compercentagecreative = config('constants.percentageRates.comPercentageCreative.headjob');
$compercentagenotcreative = config('constants.percentageRates.comPercentageNotCreative.headjob');
$creativepercent = config('constants.percentageRates.creativePercent.headjob');
break;
}
// Format the VAT number
$data['vatnumber'] = Helper::formatVatNumber($data['vatnumber']);
$isVatValid = false;
try {
// Check if vat is valid
$response = Helper::checkVat($data['vatnumber']);
$responseArray = json_decode($response);
$isVatValid = $responseArray->valid;
} catch (\Exception $exception) {
$isVatValid = false;
}
// Generate an activation key
$activationKey = md5(uniqid('CS', true));
/********************************************************************************
* CREATE THE USER IN THE DATABASE
********************************************************************************/
// Create the user and insert in the database
return User::create([
'usertype' => config('constants.userTypes.USER'),
'registeredon' => strtotime(date("Y-m-d H:i:s")),
'activationkey' => $activationKey,
'language' => 'nl',
'email' => Helper::truncate($data['email']),
'fullname' => Helper::truncate($data['lastname'] . ' ' . $data['firstname']),
'firstname' => Helper::truncate($data['firstname']),
'lastname' => Helper::truncate($data['lastname']),
'password' => Hash::make($data['password']),
'lastloginon' => strtotime('now'),
'lastloginip' => $_SERVER['REMOTE_ADDR'],
'activatedon' => strtotime(date('Y-m-d H:i:s', strtotime('1970-01-01 00:00:00'))),
'deleted' => false,
'companyname' => Helper::truncate($data['companyname']),
'street' => Helper::truncate($data['street']),
'number' => Helper::truncate($data['number']),
'city' => Helper::truncate($data['city']),
'zipcode' => Helper::truncate($data['zipcode']),
'vatnumber' => Helper::truncate($data['vatnumber']),
'validvat' => $isVatValid,
'website' => Helper::truncate($data['website']),
'phonenumber' => Helper::truncate($data['phonenumber']),
'bankname' => Helper::truncate($data['bank']),
'iban' => Helper::truncate($data['iban']),
'bicswift' => Helper::truncate($data['bicswift']),
'paymentremindermode' => $data['paymentremindermode'],
'invoicecreationremindermode' => 2,
'nettosavedmailmode' => 1,
'zombiemailsent' => 0,
'zombiemail180sent' => 0,
'nettosavedperinvoicmailemode' => 1,
'logo' => NULL,
'emailaccepted' => false,
'contractaccepted' => false,
'compercentagecreative' => $compercentagecreative,
'compercentagenotcreative' => $compercentagenotcreative,
'contractdate' => date("Y-m-d H:i:s"),
'creativepercent' => $creativepercent,
'activity' => $data['activity'],
'headjob' => $data['headjob'],
'template' => config('constants.templates.ORIGINAL'),
'freebtw' => isset($data['freebtw']) ? ($data['freebtw'] == "on" ? true : false) : false,
'refid' => Input::get('invite_id'),
'api_key' => Helper::generateRandomString(40),
'allowed_quotation' => true,
'send_bcc' => false
]);
}

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');
}

zf2 how to upload files, more than 1 file

I refer to http://samsonasik.wordpress.com/2012/08/31/zend-framework-2-creating-upload-form-file-validation/ and follow this, I can upload 1 file successfully by using rename filter in ZF2.
However when I use this way to upload 2 files, it goes wrong. I paste my code as following:
$this->add(array(
'name' => 'bigpicture',
'attributes' => array(
'type' => 'file'
),
'options' => array(
'label' => 'Big Pic'
)
));
$this->add(array(
'name' => 'smallpicture',
'attributes' => array(
'type' => 'file'
),
'options' => array(
'label' => 'Small Pic'
)
));
<div class="row"><?php echo $this->formRow($form->get('smallpicture')) ?></div>
<div class="row"><?php echo $this->formRow($form->get('bigpicture')) ?></div>
$data = array_merge(
$request->getPost()->toArray(),
$request->getFiles()->toArray()
);
$form->setData($data);
if ($form->isValid()) {
$product->exchangeArray($form->getData());
$picid = $this->getProductTable()->saveProduct($product);
$pathstr = $this->md5path($picid);
$this->folder('public/images/product/'.$pathstr);
//move_uploaded_file($data['smallpicture']['tmp_name'], 'public/images/product/'.$pathstr.'/'.$picid.'_small.jpg');
//move_uploaded_file($data['bigpicture']['tmp_name'], 'public/images/product/'.$pathstr.'/'.$picid.'_big.jpg');
$fileadaptersmall = new \Zend\File\Transfer\Adapter\Http();
$fileadaptersmall->addFilter('File\Rename',array(
'source' => $data['smallpicture']['tmp_name'],
'target' => 'public/images/product/'.$pathstr.'/'.$picid.'_small.jpg',
'overwrite' => true
));
$fileadaptersmall->receive();
$fileadapterbig = new \Zend\File\Transfer\Adapter\Http();
$fileadapterbig->addFilter('File\Rename',array(
'source' => $data['bigpicture']['tmp_name'],
'target' => 'public/images/product/'.$pathstr.'/'.$picid.'_big.jpg',
'overwrite' => true
));
$fileadapterbig->receive();
}
the above are form,view,action.
using this way, only the small picture uploaed successfully. the big picture goes wrong.
a warning flashed like the following:
Warning:move_uploaded_file(C:\WINDOWS\TMP\small.jpg):failed to open stream:Invalid argument in
E:\myproject\vendor\zendframework\zendframework\library\zend\file\transfer\adapter\http.php
on line 173
Warning:move_uploaded_file():Unable to move 'C:\WINDOWS\TMP\php76.tmp'
to 'C:\WINDOWS\TEMP\big.jpg' in
E:\myproject\vendor\zendframework\zendframework\library\zend\file\transfer\adapter\http.php
on line 173
Who can tell me how to upload more than 1 file in this way. you know, the rename filter way similar to above. thanks.
I ran into the same problem with a site i did. The solution was to do the renaming in the controller itself by getting all the images and then stepping through them.
if ($file->isUploaded()) {
$pInfo = pathinfo($file->getFileName());
$time = uniqid();
$newName = $pName . '-' . $type . '-' . $time . '.' . $pInfo['extension'];
$file->addFilter('Rename', array('target' => $newName));
$file->receive();
}
Hope this helps point you in the right direction.
I encountered the same problem and i managed to make it work using the below code;
$folder = 'YOUR DIR';
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setDestination($folder);
foreach ($adapter->getFileInfo() as $info) {
$originalFileName = $info['name'];
if ($adapter->receive($originalFileName)) {
$newFilePath = $folder . '/' . $newFileName;
$adapter->addFilter('Rename', array('target' => $newFilePath,
'overwrite' => true));
}
}

Categories