Return value not string in php - php

I have a mail function in php that echoes a response.
The browser's developer tool is showing the response as string, but when I capture that response in the front end, with a callback function, it is showing as a JSON object.
So what is printed in the screen is :
{"0":"A","1":" ","2":"t","3":"e","4":"m","5":"p","6":"o","7":"r","8":"a","9":"r","10":"y","11":" ","12":"p","13":"a","14":"s","15":"s","16":"w","17":"o","18":"r","19":"d","20":" ","21":"h","22":"a","23":"s","24":" ","25":"b","26":"e","27":"e","28":"n","29":" ","30":"s","31":"e","32":"n","33":"t","34":" ","35":"t","36":"o","37":" ","38":"y","39":"o","40":"u","41":"r","42":" ","43":"e","44":"m","45":"a","46":"i","47":"l"}
I have no idea why? I am using Laravel 5.1 and AngularJS for the front end.
Here is the code for the function :
if (Mail::send('test-view', ['pass' => $pass], function($message) use ($data)
{
$message->to('esolorzano#renovatiocloud.com', 'Tarzan de la Selva')->subject('Password Reset');
})){
echo "A temporary password has been sent to your email";
}else {
echo "There was an error sending the temporary password";
}
I just fixed it, I did this
$response = new \stdClass();
$response->message = "A temporary password was sent to your email";
return json_encode($response);
And then in angular I just use response.message and that is it. Thanks

I fixed it
$response = new \stdClass();
$response->message = "A temporary password was sent to your email";
return json_encode($response);
then in Angular, I just use response.message.

Related

Php using post method says that the parameters are missing

I am using the curl to access a php to do a POST method. The problem it's that using the POST method, the if it's not working and I get the error that the parameters are missing.
The php code:
if(isTheseParametersAvailable(array('title','email', 'message'))){
if(isset($_POST['title']) and isset($_POST['message'])){
//creating a new push
//if the push don't have an image give null in place of image
$push = new Push(
$_POST['title'],
$_POST['message'],
null
);
//getting the push from push object
$mPushNotification = $push->getPush();
//getting the token from database object
echo $devicetoken = $db->getTokenByEmail('irina#yahoo.com');
//creating firebase class object
$firebase = new Firebase();
//sending push notification and displaying result
echo $firebase->send($devicetoken, $mPushNotification);
}else{
$response['error']=true;
$response['message']='Parameters missing';
}
POSTMAN screenshot:
The isThereParametersAvailable function:
function isTheseParametersAvailable($params){
foreach($params as $param){
if(!isset($_POST[$param])){
return false;
}
}
return true;
}
You must send the parameters is the body section to get the in the $_POST.
See image below.
<?php
if(isset($_POST['header'])) {
echo 1;
}

Unable to send an email in Mail::raw with get request email address variable

Herewith I'm using 'Mail::raw()' to send and email in Laravel - PHP. After getting request from the database, I assigned the receiver's email address to '$email'. In this case '$message->to('$email');' given an error 'Address in mailbox given [$email] does not comply with RFC 2822, 3.6.2.'. Instead of '$email', 'abcdef#test.com' its working perfectly. And also inside the 'Mail::row()' function, unable to get request values instead of hard code email address. Below is the code.
Controller.php
public function sendEmailToUser(Request $request)
{
$email = (String)$request->get('email');
$messageBody = $request->get('password');
$response = null;
$res_type = null;
\Mail::raw($messageBody, function ($message) {
$message->from('abcd#gmail.com', 'TESTING');
$message->to('$email');
$message->subject('TESTING TITLE');
});
// check for failures
if (\Mail::failures())
{
$response ="Email sent unsuccess";
$res_type = 'warning';
}
else
{
$response ="Email sent successful";
$res_type = 'success';
}
return redirect()->back()->with($response,$res_type);
}
Finally got a solution is use '$request' with \Mail::row() function.
\Mail::raw($request->password, function ($message) use($request)
{
$message->from($request->fromEmail, 'TESTING');
$message->to($request->toEmail);
$message->subject('TESTING TITLE');
});

JSON Login Authentification Zend Framework

I am creating a form login with ExtJS, and sending JSON data to do authentification within Zend Framework. The problem is, no matter what username and password I fill, login always succeed. Here's the related code :
Submit Function for Ext JS Form, where we send JSON data contained username and password.
var doLogin = function () {
if (formPanel.getForm().isValid()) {
formPanel.getForm().submit({
method: 'POST',
url: '/zend/public/auth/valid',
waitMsg: 'Processing Request',
success: function (form, action) {
document.location = '/zend/public/guestbook';
},
failure: function (form, action) {
if (action.failureType = 'server') {
obj = Ext.util.JSON.decode(action.response.responseText);
Ext.Msg.alert('Login Failed', obj.errors.reason);
} else {
Ext.Msg.alert('Warning!', 'Authentification server is uneachable : ' + action.response.responseText);
}
formPanel.getForm().reset
}
})
}
}
The Controller, we have ValidAction function to receive and send JSON data, and process to do the authentification.
public function validAction()
{
if(!isset($this->session->isLogin)){
$username = mysql_escape_string($_POST['username']);
$password = mysql_escape_string($_POST['password']);
$formdata = array('username'=>$username, 'password'=>$password);
if ($this->_process($formdata)) {
$this->session->setExpirationSeconds(3600);
$msg = '{success:true, result:{message:\'Welcome, '.$username.'!\'}}';
} else {
$msg = '{success:false, errors:{reason:\'Login failed, try again.\'}}';
}
}
protected function _process($values) {
// Get our authentication adapter and check credentials
$adapter = $this->_getAuthAdapter();
$adapter->setIdentity($values['username']);
$adapter->setCredential($values['password']);
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($adapter);
if ($result->isValid()) {
$user = $adapter->getResultRowObject();
$auth->getStorage()->write($user);
return true;
}
return false;
}
The problem lies in validAction, and weirdly I do var_dump to $this->process($formdata) and returns false, yet it always go to if function, message Success. Any ideas? Appreciated fellas.
UPDATE :
The var_dump :
Uncaught Error: You're trying to decode an invalid JSON String:
array(2) {
["username"]=>
string(2) "ad"
["password"]=>
string(4) "pass"
}
bool(false)
string(59) "{success:false, errors:{reason:'Login failed, try again.'}}"
Backend problem
You are outputting invalid JSON.
PHP provides json_encode to save you having to manually create json:
$response=array();
$response['success']=false;
$response['result']=array();
$response['message']='Welcome '.$username;
$msg = json_encode($response);
If you really don't want to use this you should add double quotes to your keys, and change to double quotes for your string properties too:
$msg = '{"success":true, "result":{"message":"Welcome, '.$username.'!"}}';
Front end problem
You are using success and failure methods, but I can't see anything in your back end code to send status headers.
The failure method will only get called when a response returns with a non 200 status code. So you may need to either add this to your back end code, and/or also decode the response inside your success method to make sure that you have sent success:true as part of your json before redirecting.
To send the header in PHP 5.4 or newer:
http_response_code(401);
in 5.3 or older you have to use header method instead - but if you are running this version you should upgrade immediately so I wont include an example.

json_encode adding too many double quotes

I am working on a PHP web service that returns data in JSON form. I am at a point where I am now testing the web service with a jQuery/javascript file. It seems to be making the calls and receiving data correctly but the return values from the server seem to have too many double quotes.
PHP:
public static function getToken($username, $password)
{
$token = AuthenticationController::authenticate($username, $password);
if ($token)
{
$user = AuthenticationController::getUserFromToken($token);
if (UserController::userIsVerified($user->id))
{
$t = array('token' => $token);
return json_encode($t);
}
return json_encode(array('error' => 'This account has not been verified. Check email and click the provided link to verify the account.'));
}
return json_encode(array('error' => 'Authentication failed.'));
}
JS:
req.done(function(msg)
{
if (msg.error)
{
error = true;
message = msg.error;
}
else if (msg.message)
{
message = msg.message;
}
else if (msg.token)
{
token = msg.token;
}
else
{
error = true;
message = "An unknown error has occured.";
}
});
For one, the msg object is not coming back as a JSON object but instead it comes in as a string, so I have to do a $.parseJSON(msg) on it. What you see below, the token variable ends up writing out to be "mylongtoken" (quotes included). And if you look at that variable in firebug, it is like this: ""mylongtoken"". Is this just default behavior and I need to strip the quotes out?
First, to enable jquery to parse your response as json, you must return an appropriate content type. application/json seems appropriate.
For added security, you can add X-Content-Type-Options: nosniff to prevent browsers that get tricked into reading your JSON as a normal page to try any content sniffing which might enable HTML parsing and XSS:
Second, If you get two sets of quotes, then something you coded does add them. json_encode() does not:
echo json_encode(array('token' => 'tokenstring'); will output {"token":"tokenstring"} - no surrounding quotes. Any quotes inside any strings will be escaped using a backslash.

Refactoring loop with conditionals

given a loop that sends an email to all subscriptions in an array
foreach($subscriptions as $s){
if(!$s->send_email()){
}
}
What would be the cleanest way to trigger a callback if all models have mailed successfully or show an error if one of the models fails to mail. Is it common to save all error messages till the end of the loop and print them as a whole, or break the loop with an error.
I'm using this in combination with a JSON REST API saving a project (/projects/1) which in turn emails all users.
The method I'm using now feels dirty with lot's of nested if else, sending 3 different response on different places
if($project->save()){
$subscriptions = Subscription::model()->findAllByAttributes(array('planning_id' => $planning->id));
foreach($subscriptions as $s){
if(!$s->send_email()){
$errors[] = "failed to send email. Subscription ". $s->id;
}
}
if(count($errors) > 0){
//send json api response with error response
} else {
//send json api success response
}
} else {
//send json api response with project error response
}
I was wondering what convention is concerning this
It is a little messy - and it combines multiple concerns within the "save" function - anyone reading the code needs to understand what "save" means, how we loop through the contacts etc.
I'd refactor it as follows:
if($project->save()){
$subscriptions = Subscription::model()->findAllByAttributes(array('planning_id' => $planning->id));
$errors = sendMailToSubscribers($subscriptions);
$response = determineResponse($errors);
// send JSON API response
} else {
//send json api response with project error response
}
function sendMailToSubscribers($subscriptions){
foreach($subscriptions as $s){
if(!$s->send_email()){
$errors[] = "failed to send email. Subscription ". $s->id;
}
}
return $errors;
}
function determineResponse($errors){
if(count($errors) > 0){
//return json api response with error response
} else {
//return json api success response
}
}
You can use while logic so that failure falls through to the end of the block.
while(1) {
if ($project->save()) {
foreach($subscripts as $s)
if (!$s->send_email())
$errors[] = "failed to send email. Subscription ". $s->id;
} else
$errors[] = 'failed to save the project';
if (empty($errors)) {
//send success here
break;
}
//send your errors here
break;
}

Categories