I'm trying to set up WebSocket for my web application. I have found some doc and example with google but i don't understand very well what i am supposed to do to send additionnal data when the socket open.
I would like to have a User array which contain user socket and user id but i can't send userID in JavaScript at the opening of the socket and get that UserId in PHP on my server.
My application have to send a message to a specific client identified by UserID (UserID is stored in DB but i supposed that my client code in JS normally can send that).
For the moment I a socket list but i want to replace it by a User list which contain id and socket.
PHP SERVER CODE
$host = 'localhost'; //host
$port = '9000'; //port
$null = NULL; //null var
//Create TCP/IP sream socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
//reuseable port
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
//bind socket to specified host
socket_bind($socket, 0, $port);
//listen to port
socket_listen($socket);
//create & add listning socket to the list
$sockets = array($socket);
$users = array();
//$clients = array($socket);
//start endless loop, so that our script doesn't stop
while (true) {
//manage multipal connections
$changed = $sockets;
//returns the socket resources in $changed array
socket_select($changed, $null, $null, 0, 10);
//check for new socket
if (in_array($socket, $changed)) {
$socket_new = socket_accept($socket); //accept new socket
// HERE I NEED USER ID BUT I DON'T FIND HOW TO GET IT
$clients[] = $socket_new; //add socket to client array
$header = socket_read($socket_new, 1024); //read data sent by the socket
perform_handshaking($header, $socket_new, $host, $port); //perform websocket handshake
socket_getpeername($socket_new, $ip); //get ip address of connected socket
$response = mask(json_encode(array('type' => 'system', 'message' => $ip . ' connected'))); //prepare json data
send_message($response); //notify all users about new connection
//make room for new socket
$found_socket = array_search($socket, $changed);
unset($changed[$found_socket]);
}
//loop through all connected sockets
foreach ($changed as $changed_socket) {
//check for any incomming data
while (socket_recv($changed_socket, $buf, 1024, 0) >= 1) {
$received_text = unmask($buf); //unmask data
$tst_msg = json_decode($received_text); //json decode
$user_id = $tst_msg->iduser;
$user_name = $tst_msg->name; //sender name
$user_message = $tst_msg->message; //message text
$user_color = $tst_msg->color; //color
//prepare data to be sent to client
$response_text = mask(json_encode(array('type' => 'usermsg', 'name' => $user_name, 'message' => $user_message, 'color' => $user_color)));
send_message($response_text); //send data
break 2; //exist this loop
}
$buf = #socket_read($changed_socket, 1024, PHP_NORMAL_READ);
if ($buf === false) { // check disconnected client
// remove client for $clients array
$found_socket = array_search($changed_socket, $clients);
socket_getpeername($changed_socket, $ip);
unset($clients[$found_socket]);
//notify all users about disconnected connection
$response = mask(json_encode(array('type' => 'system', 'message' => $ip . ' disconnected')));
send_message($response);
}
}
}
// close the listening socket
socket_close($sock);
function send_message($msg) {
global $clients;
foreach ($clients as $changed_socket) {
#socket_write($changed_socket, $msg, strlen($msg));
}
return true;
}
//Unmask incoming framed message
function unmask($text) {
$length = ord($text[1]) & 127;
if ($length == 126) {
$masks = substr($text, 4, 4);
$data = substr($text, 8);
} elseif ($length == 127) {
$masks = substr($text, 10, 4);
$data = substr($text, 14);
} else {
$masks = substr($text, 2, 4);
$data = substr($text, 6);
}
$text = "";
for ($i = 0; $i < strlen($data); ++$i) {
$text .= $data[$i] ^ $masks[$i % 4];
}
return $text;
}
//Encode message for transfer to client.
function mask($text) {
$b1 = 0x80 | (0x1 & 0x0f);
$length = strlen($text);
if ($length <= 125)
$header = pack('CC', $b1, $length);
elseif ($length > 125 && $length < 65536)
$header = pack('CCn', $b1, 126, $length);
elseif ($length >= 65536)
$header = pack('CCNN', $b1, 127, $length);
return $header . $text;
}
//handshake new client.
function perform_handshaking($receved_header, $client_conn, $host, $port) {
$headers = array();
$lines = preg_split("/\r\n/", $receved_header);
foreach ($lines as $line) {
$line = chop($line);
if (preg_match('/\A(\S+): (.*)\z/', $line, $matches)) {
$headers[$matches[1]] = $matches[2];
}
}
$secKey = $headers['Sec-WebSocket-Key'];
$secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
//hand shaking header
$upgrade = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
"Upgrade: websocket\r\n" .
"Connection: Upgrade\r\n" .
"WebSocket-Origin: $host\r\n" .
"WebSocket-Location: ws://$host:$port/demo/shout.php\r\n" .
"Sec-WebSocket-Accept:$secAccept\r\n\r\n";
socket_write($client_conn, $upgrade, strlen($upgrade));
}
function getSocketbyIdUser($idU) {
global $clients;
foreach ($clients as $client) {
if ($client->getIdUser() == $idU) {
return $client->getSocket();
}
}
return false;
}
function userIsConnected($idU) {
global $clients;
return getSocketbyIdUser($idU) != false;
}
function getSocketsArray() {
global $clients;
$sockets[];
foreach ($clients as $client) {
$sockets[] = $client->getSocket();
}
return $sockets;
}
class Client {
private $idUser;
private $socket;
public function getIdUser() {
return self::$idUser;
}
public function getSocket() {
return self::$socket;
}
}
JS CODE
$(document).ready(function(){
//create a new WebSocket object.
var wsUri = "ws://localhost:9000/server/server.php";
websocket = new WebSocket(wsUri);
websocket.onopen = function(ev) { // connection is open
$('#message_box').append("<div class=\"system_msg\">Connected!</div>"); //notify user
}
$('#send-btn').click(function(){ //use clicks message send button
var mymessage = $('#message').val(); //get message text
var myname = $('#name').val(); //get user name
if(myname == ""){ //empty name?
alert("Enter your Name please!");
return;
}
if(mymessage == ""){ //emtpy message?
alert("Enter Some message Please!");
return;
}
//prepare json data
var msg = {
message: mymessage,
name: myname,
color : '<?php echo $colours[$user_colour]; ?>'
};
//convert and send data to server
websocket.send(JSON.stringify(msg));
});
//#### Message received from server?
websocket.onmessage = function(ev) {
var msg = JSON.parse(ev.data); //PHP sends Json data
var type = msg.type; //message type
var umsg = msg.message; //message text
var uname = msg.name; //user name
var ucolor = msg.color; //color
if(type == 'usermsg')
{
$('#message_box').append("<div><span class=\"user_name\" style=\"color:#"+ucolor+"\">"+uname+"</span> : <span class=\"user_message\">"+umsg+"</span></div>");
}
if(type == 'system')
{
$('#message_box').append("<div class=\"system_msg\">"+umsg+"</div>");
}
$('#message').val(''); //reset text
};
websocket.onerror = function(ev){$('#message_box').append("<div class=\"system_error\">Error Occurred - "+ev.data+"</div>");};
websocket.onclose = function(ev){$('#message_box').append("<div class=\"system_msg\">Connection Closed</div>");};
});
Send your additional data to websocket like this:
ws://yoursite:port/?param1=value;
In server:
if (preg_match("/GET (.*) HTTP/", $receved_header, $match)) {
$root = $match[1];
$userid = explode('param1=', $root);
if (!empty($userid) && array_key_exists(1, $param1))
$this->userid = $userid[1];
}
it works for me..try it
Related
I am using paypal integration in my web application everything is working fine . Checkout is working properly but when i apply the coupon then the paypal throws the exception of 400 error. Below is my code
I am using the daryldecode/cart for the checkout. The only problem is when I apply the coupon and move forward towards the paypal
public function paywithPaypal(Request $request)
{
// dd($request->all());
if(Auth::guest()){
if(Session::has('user_id')){
$sessionUserId = Session::get('user_id');
echo $sessionUserId;
}
$checkEmail= User::where('email',$request->billing_email )->first();
if(empty($checkEmail)) {
$user = User::create( [
'first_name' => $request->billing_first_name,
'last_name' => $request->billing_last_name,
'email' => $request->billing_email,
'username' => $request->billing_first_name,
'password' => bcrypt( 123456 ),
'province' => $request->billing_state,
'city' => $request->billing_town,
'address' => $request->billing_address_1,
'role' => 'Member',
] );
$userId = $user->id;
}else{
$userId = $checkEmail->id;
}
}else{
//user login
$sessionUserId = $userId = Auth::user()->id;
}
$items = [];
\Cart::session($sessionUserId)->getContent()->each(function($item) use (&$items)
{
$items[] = $item;
});
$subtotal = \Cart::session($sessionUserId)->getSubTotal();
// dd($subtotal);
$line1 = $request->billing_address_1;
$line2 = $request->billing_address_2;
$fullname = $request->billing_first_name ." ". $request->billing_last_name;
$state = $request->billing_state;
$zip = $request->billing_zip;
$phone = $request->billing_phone;
$email = $request->billing_email;
$city = $request->billing_town;
//invoke new order
$order = new Orders ;
$order->id = $order->generateID('INV');
$saved_order_id = $order->id;
$shippingAddress= Paypalpayment::shippingAddress();
$shippingAddress->setLine1($line1)
->setLine2($line2)
->setCity($city)
->setState($state)
->setPostalCode($zip)
->setCountryCode("US")
->setPhone($phone)
->setRecipientName($fullname);
// ### Payer
// A resource representing a Payer that funds a payment
// Use the List of `FundingInstrument` and the Payment Method
// as 'credit_card'
$payer = Paypalpayment::payer();
$payer->setPaymentMethod("paypal");
$listitem = array();
$fees=HandlingFee::find(1);
$fee = $fees->fee;
$shipping = $request->shipping_fee;
foreach($items as $key=>$item){
$listitem[$key] = Paypalpayment::item();
$listitem[$key]->setName($item->name)
->setCurrency('USD')
->setQuantity($item->quantity)
->setPrice($item->price);
$item_detail = new Order_Item_Details;
$item_detail->order_id = $saved_order_id;
$item_detail->item_id = $item->id;
$item_detail->qty = $item->quantity;
$item_detail->save();
}
$itemList = Paypalpayment::itemList();
$itemList->setItems($listitem)
->setShippingAddress($shippingAddress);
$details = Paypalpayment::details();
$details->setShipping($shipping)
->setHandlingFee($fee)
//total of items prices
->setSubtotal($subtotal);
$grandTotal = $subtotal + $fee + $shipping;
//dd($grandTotal);
//Payment Amount
$amount = Paypalpayment::amount();
$amount->setCurrency("USD")
// the total is $17.8 = (16 + 0.6) * 1 ( of quantity) + 1.2 ( of Shipping).
->setTotal($grandTotal)
->setDetails($details);
//dd($amount);
// ### Transaction
// A transaction defines the contract of a
// payment - what is the payment for and who
// is fulfilling it. Transaction is created with
// a `Payee` and `Amount` types
$transaction = Paypalpayment::transaction();
$transaction->setAmount($amount)
->setItemList($itemList)
->setDescription("Payment description")
->setInvoiceNumber($saved_order_id)
->setCustom($request->shipping_service);
// dd($transaction);
// ### Payment
// A Payment Resource; create one using
// the above types and intent as 'sale'
$redirectUrls = Paypalpayment::redirectUrls();
$redirectUrls->setReturnUrl(url("/payments/success"))
->setCancelUrl(url("/payments/fails"));
$payment = Paypalpayment::payment();
$payment->setIntent("sale")
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions([$transaction]);
$order->status = 1;
$order->user_id = $userId;
$order->total = $grandTotal;
$order->subtotal = $subtotal;
$order->shipping = $shipping;
if($request->coupon_code == ""){
$order->isCoupon = 0;
}
else{
$order->isCoupon = 1;
}
$order->isBillingDetail = 1;
if($request->shipping_first_name <> ""){
$order->isShippingDetail = 1;
}
if($request->has('order_notes')){
$order->notes = $request->order_notes;
}
$order->save();
$order_billing = new Order_Billing_Details;
$order_billing->order_id = $order->id;
$order_billing->first_name = $request->billing_first_name ;
$order_billing->last_name = $request->billing_last_name ;
$order_billing->company = $request->billing_company_name ;
$order_billing->address_line_1 = $line1;
$order_billing->address_line_2 = $line2;
$order_billing->state = $state;
$order_billing->city = $city;
$order_billing->postal_code = $zip;
$order_billing->email = $email;
$order_billing->phone = $phone;
$order_billing->save();
if($request->shipping_first_name <> ""){
$order_shipping = new Order_Shipping_Details;
$order_shipping->order_id = $order->id;
$order_shipping->first_name = $request->shipping_first_name ;
$order_shipping->last_name = $request->shipping_last_name ;
$order_shipping->company = $request->shipping_company_name ;
$order_shipping->address_line_1 = $request->shipping_address_1 ;
$order_shipping->address_line_2 = $request->shipping_address_2 ;
$order_shipping->state = $request->shipping_state ;
$order_shipping->city = $request->shipping_town ;
$order_shipping->postal_code = $request->shipping_zip ;
$order_shipping->email = $email ;
$order_shipping->phone = $request->shipping_phone ;
$order_shipping->save();
}
else{
$order_shipping = new Order_Shipping_Details;
$order_shipping->order_id = $order->id;
$order_shipping->first_name = $request->billing_first_name ;
$order_shipping->last_name = $request->billing_last_name ;
$order_shipping->company = $request->billing_company_name ;
$order_shipping->address_line_1 = $line1;
$order_shipping->address_line_2 = $line2;
$order_shipping->state = $state;
$order_shipping->city = $city;
$order_shipping->postal_code = $zip;
$order_shipping->email = $email;
$order_shipping->phone = $phone;
$order_shipping->save();
}
try {
// ### Create Payment
// Create a payment by posting to the APIService
// using a valid ApiContext
// The return object contains the status;
//dd(Paypalpayment::apiContext());
$payment->create(Paypalpayment::apiContext());
// dd($payment);
$arrpayment = $payment->toArray();
$order = Orders::find($saved_order_id);
$order->paypal_invoice = $arrpayment['id'];
$order->save();
} catch (\PPConnectionException $ex) {
echo $ex->getCode(); // Prints the Error Code
echo $ex->getData();
dd($ex);
return response()->json(["error" => $ex->getMessage()], 400);
}
catch (PayPal\Exception\PayPalConnectionException $ex) {
echo $ex->getCode(); // Prints the Error Code
echo $ex->getData(); // Prints the detailed error message
}
$email=$request->billing_email;
$fees=HandlingFee::find(1);
$fee = $fees->fee;
$data=array(
'order' => $order,
'name' => $request->billing_first_name.' '.$request->billing_last_name,
'email'=>$email,
'fee'=>$fee,
'payPalLink' => $payment->getApprovalLink(),
);
Mail::send('email.placed', $data, function($message) use ($email) {
$message->subject('New Order Received');
$message->from('no-reply#blurack.com', 'BluRack');
$message->to($email);
});
$admins=DB::table('users')
->select('updates_email')
->where('receiving_updates',1)
->where(function($q) {
$q->where('role','Administrator')
->orWhere('role','Retailer');
})->get()->toArray();
// ->where('role','Administrator')
// ->orWhere('role','Retailer')
// dd($admins);
foreach($admins as $admin){
$admin_mail=$admin->updates_email;
//dd($admin_mail);
Mail::send('email.orderplaced',$data, function($message) use ($admin_mail) {
$message->subject('New Order Received');
$message->from('no-reply#blurack.com', 'BluRack');
$message->to($admin_mail);
});
}
return redirect($payment->getApprovalLink());
// return response()->json([$payment->toArray(), 'approval_url' => $payment->getApprovalLink()],
200);
}
I think the issue is with try catch problem?
Hi Every One,
I am trying to connect through web socket to replace ajax log polling in my project as it has too much over head , tried a simple websocket chat code , issue is I cant make the handshake work on executing get following error in browser console
WebSocket connection to 'ws://192.168.5.78:8080/Chat-WebSocket/server.php' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
I have setup my client code on local machine Client :
http://192.168.5.66/test/zaheer/Chat-WebSocket/
and server code is on another local machine
192.168.5.78
here is my code
Client :
<script language="javascript" type="text/javascript">
//create a new WebSocket object.
var msgBox = $('#message-box');
//var wsUri = "ws://192.168.5.78:8080/Chat-WebSocket/server.php";
var websocket = new WebSocket("ws://192.168.5.78:8080/Chat-WebSocket/server.php");
//websocket = new WebSocket(wsUri);
websocket.onopen = function(ev) { // connection is open
msgBox.append('<div class="system_msg" style="color:#bbbbbb">Welcome to my "Demo WebSocket Chat box"!</div>'); //notify user
}
// Message received from server
websocket.onmessage = function(ev) {
var response = JSON.parse(ev.data); //PHP sends Json data
var res_type = response.type; //message type
var user_message = response.message; //message text
var user_name = response.name; //user name
var user_color = response.color; //color
switch(res_type){
case 'usermsg':
msgBox.append('<div><span class="user_name" style="color:' + user_color + '">' + user_name + '</span> : <span class="user_message">' + user_message + '</span></div>');
break;
case 'system':
msgBox.append('<div style="color:#bbbbbb">' + user_message + '</div>');
break;
}
msgBox[0].scrollTop = msgBox[0].scrollHeight; //scroll message
};
websocket.onerror = function(ev){ msgBox.append('<div class="system_error">Error Occurred - ' + ev.data + '</div>'); };
websocket.onclose = function(ev){ msgBox.append('<div class="system_msg">Connection Closed</div>'); };
//Message send button
$('#send-message').click(function(){
send_message();
});
//User hits enter key
$( "#message" ).on( "keydown", function( event ) {
if(event.which==13){
send_message();
}
});
//Send message
function send_message(){
var message_input = $('#message'); //user message text
var name_input = $('#name'); //user name
if(message_input.val() == ""){ //empty name?
alert("Enter your Name please!");
return;
}
if(message_input.val() == ""){ //emtpy message?
alert("Enter Some message Please!");
return;
}
//prepare json data
var msg = {
message: message_input.val(),
name: name_input.val(),
color : '<?php echo $colors[$color_pick]; ?>'
};
//convert and send data to server
websocket.send(JSON.stringify(msg));
message_input.val(''); //reset message input
}
</script>
Server :
<?php
$host = '192.168.5.78'; //host
$port = '8080'; //port
$null = NULL; //null var
//Create TCP/IP sream socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
//reuseable port
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
//bind socket to specified host
socket_bind($socket, 0, $port);
//listen to port
socket_listen($socket);
//create & add listning socket to the list
$clients = array($socket);
//start endless loop, so that our script doesn't stop
while (true) {
//manage multipal connections
$changed = $clients;
//returns the socket resources in $changed array
socket_select($changed, $null, $null, 0, 10);
//check for new socket
if (in_array($socket, $changed)) {
$socket_new = socket_accept($socket); //accpet new socket
$clients[] = $socket_new; //add socket to client array
$header = socket_read($socket_new, 1024); //read data sent by the socket
perform_handshaking($header, $socket_new, $host, $port); //perform websocket handshake
socket_getpeername($socket_new, $ip); //get ip address of connected socket
$response = mask(json_encode(array('type'=>'system', 'message'=>$ip.' connected'))); //prepare json data
send_message($response); //notify all users about new connection
//make room for new socket
$found_socket = array_search($socket, $changed);
unset($changed[$found_socket]);
}
//loop through all connected sockets
foreach ($changed as $changed_socket) {
//check for any incomming data
while(socket_recv($changed_socket, $buf, 1024, 0) >= 1)
{
$received_text = unmask($buf); //unmask data
$tst_msg = json_decode($received_text, true); //json decode
$user_name = $tst_msg['name']; //sender name
$user_message = $tst_msg['message']; //message text
$user_color = $tst_msg['color']; //color
//prepare data to be sent to client
$response_text = mask(json_encode(array('type'=>'usermsg', 'name'=>$user_name, 'message'=>$user_message, 'color'=>$user_color)));
send_message($response_text); //send data
break 2; //exist this loop
}
$buf = #socket_read($changed_socket, 1024, PHP_NORMAL_READ);
if ($buf === false) { // check disconnected client
// remove client for $clients array
$found_socket = array_search($changed_socket, $clients);
socket_getpeername($changed_socket, $ip);
unset($clients[$found_socket]);
//notify all users about disconnected connection
$response = mask(json_encode(array('type'=>'system', 'message'=>$ip.' disconnected')));
send_message($response);
}
}
}
// close the listening socket
socket_close($socket);
function send_message($msg)
{
global $clients;
foreach($clients as $changed_socket)
{
#socket_write($changed_socket,$msg,strlen($msg));
}
return true;
}
//Unmask incoming framed message
function unmask($text) {
$length = ord($text[1]) & 127;
if($length == 126) {
$masks = substr($text, 4, 4);
$data = substr($text, 8);
}
elseif($length == 127) {
$masks = substr($text, 10, 4);
$data = substr($text, 14);
}
else {
$masks = substr($text, 2, 4);
$data = substr($text, 6);
}
$text = "";
for ($i = 0; $i < strlen($data); ++$i) {
$text .= $data[$i] ^ $masks[$i%4];
}
return $text;
}
//Encode message for transfer to client.
function mask($text)
{
$b1 = 0x80 | (0x1 & 0x0f);
$length = strlen($text);
if($length <= 125)
$header = pack('CC', $b1, $length);
elseif($length > 125 && $length < 65536)
$header = pack('CCn', $b1, 126, $length);
elseif($length >= 65536)
$header = pack('CCNN', $b1, 127, $length);
return $header.$text;
}
//handshake new client.
function perform_handshaking($receved_header,$client_conn, $host, $port)
{
$headers = array();
$lines = preg_split("/\r\n/", $receved_header);
foreach($lines as $line)
{
$line = chop($line);
if(preg_match('/\A(\S+): (.*)\z/', $line, $matches))
{
$headers[$matches[1]] = $matches[2];
}
}
$secKey = $headers['Sec-WebSocket-Key'];
$secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
//hand shaking header
$upgrade = "HTTP/1.1 101 Web Socket Protocol Handshake\n" .
"Upgrade: websocket\n" .
"Connection: Upgrade\n" .
"WebSocket-Origin: $host\n" .
"WebSocket-Location: ws://$host:$port/demo/shout.php\n".
"Sec-WebSocket-Accept:$secAccept\r\n\r\n";
socket_write($client_conn,$upgrade,strlen($upgrade));
}
i am trying to call API from ionic but it shows 404 error
here is my code for provider
remoteservice.ts
export class RemoteserviceProvider {
public headers = new Headers( { 'X-API-KEY' :
'xxxxxxxxx' });
public options = new RequestOptions({ headers: this.headers });
constructor(public http: Http) {
console.log('Hello RemoteserviceProvider Provider');
}
rec:any[]=[];
use:any[]=[];
login(credentials) {
return new Promise((resolve, reject) => {
this.http.post('http://localhost/my/v1/adminlogin', credentials,
{headers: this.headers})
.subscribe(res => {
resolve(res.json());
}, (err) => {
reject(err);
});
});
}
Login.ts
doLogin() {
this.showLoader();
this.remoteService.login(this.loginData).then((result) => {
this.loading.dismiss();
this.responseData = result;
console.log(this.responseData);
if(this.responseData.message=='Login Success'){
localStorage.setItem('loginData', JSON.stringify(this.responseData));
if(this.responseData.user_type==1){
if(this.responseData.project_type==null){
this.presentToast('You are not assigned to any project');
}
else{
if(this.responseData.project_type=='Concrete'){
console.log(this.responseData.p_id)
this.navCtrl.setRoot(ConcretePage,
{p_id:this.responseData.p_id, s_name:this.responseData.name,
project:this.responseData.project,
project_type:this.responseData.project_type,
location:this.responseData.location});
}
else if(this.responseData.project_type=='Bricks'){
this.navCtrl.setRoot(ProductionPage,
{p_id:this.responseData.p_id,s_name:this.responseData.name,
project:this.responseData.project,
project_type:this.responseData.project_type,
location:this.responseData.location});
}
else{
this.navCtrl.setRoot(DailyReportPage,
{p_id:this.responseData.p_id,s_name:this.responseData.name,
project:this.responseData.project,
project_type:this.responseData.project_type,
location:this.responseData.location});
}
}
My API code is laravel
index.php
<?php
//including the required files
require_once '../include/DbOperation.php';
require '.././libs/Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->hook('slim.before.dispatch', function () use ($app){
$headers = request_headers();
$response = array();
$app = \Slim\Slim::getInstance();
$api_key = $headers['X-API-KEY'];
// this could be a MYSQL query that parses an API Key table, for example
if($api_key == 'xxxxxxxxxxxxxxx') {
$authorized = true;
} else if ($api_key == NULL) {
$response["error"] = true;
$response["message"] = '{"error":{"text": "api key not sent"
}}';
$app->response->headers['X-Authenticated'] = 'False';
$authorized = false;
$app->halt(401, $response['message']);
} else {
$response["error"] = true;
$response["message"] = '{"error":{"text": "api key invalid" }}';
$app->response->headers['X-Authenticated'] = 'False';
$authorized = false;
}
if(!$authorized){ //key is false
// dont return 403 if you request the home page
$req = $_SERVER['REQUEST_URI'];
if ($req != "/") {
$app->halt('403', $response['message']); // or redirect, or
other something
}
}
});
$app->post('/adminlogin', function () use ($app) {
$json = $app->request->getBody();
$input = json_decode($json, true);
$mobile= (int)$input['mobile'];
$password = (string)$input['password'];
$db = new DbOperation();
$response = array();
$response['report'] = array();
if ($db->adminLogin($mobile,$password)) {
$admin = $db->getAdmin($mobile);
$admin1 = $db->getassignedproject($mobile);
$admin2 = $db->getprojecttype($admin1['p_id']);
$admin4 = $db->updateadminlogin($mobile,$password);
$response['error'] = false;
$response['p_id']=$admin1['p_id'];
$response['id'] = $admin['u_id'];
$response['name'] = $admin['username'];
$response['date'] = date('Y-m-d');
$response['user_type'] = $admin['user_type'];
$response['project'] = $admin1['p_name'];
$response['project_type'] = $admin2['p_type'];
$response['location'] = $admin2['location'];
$response['message'] = "Login Success";
} else {
$response['error'] = true;
$response['message'] = "Invalid username or password";
}
echoResponse(200, $response);
});
while am calling API using /adminlogin this shows 404 error
i don't know where i did wrong.
Anyone can please give me some idea to overcome this.
Thanks in Advance
I have pdf file created with mpdf library and I want to send the output file as attachment in email with PHPMailer. I have tried this code but still not working. The attachment is missing but the email is successfully sent.
This is my code in controller :
public function pdf_file()
{
$this->load->library('m_pdf');
$this->data['title']="MY PDF TITLE 1.";
$this->data['description']="Test PDF File";
$html=$this->load->view('frontend/pdf_output',$this->data, true);
$pdfFilePath = "the_pdf_output.pdf";
$pdf = $this->m_pdf->load();
$pdf->SetProtection(array('copy'), '123456', '123456', 128);
$pdf->SetVisibility('screenonly');
$pdf->WriteHTML($html,2);
//$pdf->Output($pdfFilePath, "D");
$content = $pdf->Output('', 'S');
$content = chunk_split(base64_encode($content));
$subject = "PDF File";
$message = $this->load->view('frontend/pdf_output',$this->data,TRUE);
$from = "aaa#yahoo.com";
$to = 'xxx#gmail.com';
$cc = null;
$attachment = $content;
$sender = "Administrator";
$site_url = site_url();
if ($site_url == 'http://localhost/mysite/')
{
$this->load->view('frontend/email',$data);
}
else
{
$this->booking_model->send_email($subject,$message,$from,$to,$cc,$attachment,$sender);
}
}
This is my PHPMailer configuration :
function send_email($subject,$message,$from,$to,$cc,$attachment,$sender)
{
$this->load->library('PHPMailerAutoload');
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 0;
$mail->Debugoutput = 'html';
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->Host = "mail.host.com";
$mail->IsHTML(true);
$mail->Port = 26;
$mail->SMTPAuth = true;
//$mail->SMTPSecure = 'ssl';
$mail->Username = "aaa#domain.com";
$mail->Password = "123456";
$mail->setFrom($from, $sender);
if (count($cc) > 1)
{
for ($i=1; $i <= count($cc); $i++)
{
$mail->addCC($cc[$i], $sender);
}
}
if (!empty($attachment))
{
$mail->addAttachment($attachment);
}
$mail->addAddress($to);
$mail->Subject = $subject;
$mail->msgHTML($message);
//send the message, check for errors
if (!$mail->send()) {
// failed
} else {
// success
}
}
Anyone know to send the pdf attachment on email ? Please help.
I have the following script which retrieves code from gmail. the code runs well in localhost, but gives error when i upload it on server and make it eun. The script is made in codeigniter.
<?php
class invite_friends extends CI_Controller{
var $FEED_URL = "http://www.google.com/m8/feeds/contacts/default/full";
var $LOGIN_URL = "https://www.google.com/accounts/ClientLogin";
var $username = "my_qmail#gmail.com";
var $passwd = "my_passowrd";
var $postData = array();
function __construct() {
parent::__construct();
session_start();
}
function index()
{
if(isset($_SESSION['logged_user']))
redirect(base_url().'home');
$this->load->view('header');
$this->load->view('invite_friends');
$this->load->view('footer');
}
/*function GmailContacts_lib($gUsername, $gPassword) {
//constructor function
$this->username = $gUsername;
$this->passwd = $gPassword;
}*/
function get_gmail_contacts() {
$emailLists = array();
//create an array for post data
$this->postData = array(
"accountType" => "HOSTED_OR_GOOGLE",
"Email" => $this->username,
"Passwd" => $this->passwd,
"service" => "cp",
"source" => "anything"
);
//initialize the curl object
$curl = curl_init($this->LOGIN_URL);
//set the curl options
$this->set_curl_options($curl, CURLOPT_POST, true);
$this->set_curl_options($curl, CURLOPT_POSTFIELDS, $this->postData);
$this->set_curl_options($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
$this->set_curl_options($curl, CURLOPT_SSL_VERIFYPEER, false);
$this->set_curl_options($curl, CURLOPT_RETURNTRANSFER, 1);
//following variable contains the responses
$response = curl_exec($curl);
//check if the user has logged in sucessfully
//and save auth key if logged in
preg_match("/Auth=([a-z0-9_\-]+)/i", $response, $matches);
$auth = $matches[1];
if( !empty($auth)) {
$headers = array("Authorization: GoogleLogin auth=".$auth);
//make the request to google contacts feed with the auth key maximum contacts is 10000
$curl1 = curl_init($this->FEED_URL);
//passing the headers of auth key
$this->set_curl_options($curl1, CURLOPT_HTTPHEADER, $headers);
//return the result in a variable
$this->set_curl_options($curl1, CURLOPT_RETURNTRANSFER, 1);
//results response
$feed = curl_exec($curl1);
//parse the feed and return email list array
$emailLists = $this->parse_response($feed);
}
else {
$emailLists = array("Invalid Username/Password");
}
print_r($emailLists);
}
//function to set curl options
function set_curl_options($ch, $option, $value) {
//make the post TRUE
return curl_setopt($ch, $option, $value);
}
//function to parse response
public function parse_response($feed) {
$contacts = array();
$doc = new DOMDocument();
//load the XML response
$doc->loadXML($feed);
//check the entry tag
$nodeList = $doc->getElementsByTagName( 'entry' );
foreach($nodeList as $node) {
//children of each entry tag
$entry_nodes = $node->childNodes;
$tempArray = array();
foreach($entry_nodes as $child) {
//get the tagname of the child
$domNodesName = $child->nodeName;
switch($domNodesName) {
case "title":
{ $tempArray['fullName'] = $child->nodeValue; }
break;
case "gd:email":
{
if (strpos($child->getAttribute('rel'),'home')!==false)
$tempArray['email_1']=$child->getAttribute('address');
elseif(strpos($child->getAttribute('rel'),'work')!=false)
$tempArray['email_2']=$child->getAttribute('address');
elseif(strpos($child->getAttribute('rel'),'other')!==false)
$tempArray['email_3']=$child->getAttribute('address');
}
break;
} //end of switch for nodeNames
} //end of foreach for entry_nodes child nodes
if( !empty($tempArray['email_1'])) $contacts[$tempArray['email_1']] = $tempArray;
if( !empty($tempArray['email_2'])) $contacts[$tempArray['email_2']] = $tempArray;
if( !empty($tempArray['email_3'])) $contacts[$tempArray['email_3']] = $tempArray;
}
return $contacts;
}
}
?>
it gives error and here is the error
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 1
Filename: controllers/invite_friends.php
Line Number: 54
I would suggest changing your code to the following
if(preg_match("/Auth=([a-z0-9_\-]+)/i", $response, $matches))
{
$auth = $matches[1];
}
else
{
$auth = null;
}
You could set $auth to null or 0. But if you set it to null I would then instead check:
if(!is_null($auth)) {