Php using post method says that the parameters are missing - php

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

Related

generating goo.gl not working on localhost

i am trying to dynamically generate the goo.gl links via function.php ,when a post is created ...but its not getting updating the field with the link created on localhost..and i just cant figure out the issue
function newlinks($post_id){
$permaurl=get_permalink($post_id);
$shorturl=make_my_url($permaurl);
update_post_meta('$post_id','shorturl',$shorturl)
}
add_action( 'save_post', 'newlinks' );
function make_my_url($myurl)
{
//got te key from https://console.developers.google.com/iam-admin/projects
$key = 'AIzBP0';
$googer = new GoogleURLAPI($key);
// Test: Shorten a URL
$shortDWName = $googer->shorten($myurl);
return $shortDWName; // returns the short url
}
// Declare the class
class GoogleUrlApi {
// Constructor
function GoogleURLAPI($key,$apiURL = 'https://www.googleapis.com/urlshortener/v1/url') {
// Keep the API Url
$this->apiURL = $apiURL.'?key='.$key;
}
// Shorten a URL
function shorten($url) {
// Send information along
$response = $this->send($url);
// Return the result
return isset($response['id']) ? $response['id'] : false;
}
// Send information to Google
function send($url,$shorten = true) {
// Create cURL
$ch = curl_init();
// If we're shortening a URL...
if($shorten) {
curl_setopt($ch,CURLOPT_URL,$this->apiURL);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode(array("longUrl"=>$url)));
curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-Type: application/json"));
}
else {
curl_setopt($ch,CURLOPT_URL,$this->apiURL.'&shortUrl='.$url);
}
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
// Execute the post
$result = curl_exec($ch);
// Close the connection
curl_close($ch);
// Return the result
return json_decode($result,true);
}
}
your code is good. I've created my own API key and tried this and works fine. The problem may be in google console.
Please login to https://developers.google.com/apis-explorer/?hl=pl#p/urlshortener/v1/ and try to generate short url there. Google should ask you to authorize the key you created before. After that code should work fine.

Return value not string in 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.

SLIM PHP api 400 error - $_REQUEST not working

I'm beginning to learn how to properly use REST API's following a popular tutorial here
When trying to create a simple POST api I keep running into a 400 error and I haven't found any answers online as of yet.
API is as follows:
$app->post('/test', function() use ($app) {
// check for required params
verifyRequiredParams(array('email'));
echo "Success";
});
Which attempts to verify the 'email' parameter with this block of code, unchanged from the tutorial:
function verifyRequiredParams($required_fields) {
$error = false;
$error_fields = "";
$request_params = array();
$request_params = $_REQUEST;
// Handling PUT request params
if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
$app = \Slim\Slim::getInstance();
parse_str($app->request()->getBody(), $request_params);
}
foreach ($required_fields as $field) {
if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
$error = true;
$error_fields .= $field . ', ';
}
}
if ($error) {
// Required field(s) are missing or empty
// echo error json and stop the app
$response = array();
$app = \Slim\Slim::getInstance();
$response["error"] = true;
$response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
echoRespnse(400, $response);
$app->stop();
}
}
The code always fails with a 400 error code because it seems that the $_REQUEST function is returning an empty array. Any idea's what could be going wrong? I'm developing on an ubuntu server running apache.
The Slim API framework is set up correctly as I can call a very simple call through Google's Advanced Rest Client which echos a response correctly. And I am definitely passing the correct parameters into the api.
UPDATE: I've also tried running the $_REQUEST and $_GET functions directly from the api and it just returns an empty string like this:
Array
(
)
I wonder if there's some sort of apache config file that's blocking data to these functions or something?
Possible Problem:
Have you double checked that your selected Content-Type in the request headers is right?
I suspect the client is perceiving a malformed markup language being sent from the server side.
Possible Solution:
Change Content-Type: application/x-www-form-urlencoded to application/JSON or vice versa.
For the tutorial to receive
$name = $app->request->post('name');
the POST parameters have to be in Payload data
name=yourname&password=pass&email=me#mail.com
application/x-www-form-urlencoded
If you provide the parameters after the URL but not in the payload data, that is for a GET request. In such a case the tutorial partly works (it sees the parameters to verify required parameters are present) but it is looking for the parameters "anywhere" when it should only be looking in the payload parameters for POST.

PHP - Zend keeping sessions alive

I am making requests from Product 1 to Product 2. 3 requests will be sent, the first is authentication via POST where a session will be set on the receiving server, two will be the GET requests to the REST action of choice and three will be the close call to unset the session by POST.
Below is a quick mock up of what is desired:
I can set the session from request one but when the second GET request is sent I think the Session no longer exists. How do I persist that session until the third request to unset it is sent?
Sender:
public function sendRestRequest($action, $params= array(), $method = 'GET')
{
try {
// Authenticate request
$this->sendAuthenticateRequest();
$this->client->setUri('https://product1/controller/'.$action);
// Set post parameter to the authentication token
$this->setRequestParams($params, false, 'GET');
// Make request
$restRequest = $this->client->request($method);
// Get response
$restResponse = $restRequest->getBody();
$this->debugging = 0;
if ($this->debugging == 1) {
echo '<b>Rest Request:</b>';
echo '<pre>';
echo $restRequest;
echo '<pre>';
echo '<b>Rest Response:</b>';
echo '<pre>';
echo $restResponse;
echo '<pre>';
}
// Check the request was successful
if ($restRequest->getStatus() != 200) {
throw new Zend_Exception('The request returned a '.$restRequest->getStatus().' status code');
}
// Clear parameters so another request can be sent
$this->client->resetParameters();
// Close request
$this->closeRequest();
return $restResponse;
} catch (Zend_Exception $e) {
$this->setError(500, $e->getMessage());
$this->generateXml();
}
}
Receiver:
public function authenticationIn($passPhrase)
{
try {
if (!isset($passPhrase)) {
throw new Zend_Rest_Exception('No authentication key is detected.');
}
// Construct pass key from pass phrase and the shared secret
$generatedKey = $this->generateApiKey($passPhrase);
// Get KEY setting value from global_settings
$storedKey = $this->getQuidApiKey();
if ($generatedKey != $storedKey) {
// Bad PASS_PHRASE key send a failed authenticate response
header('HTTP/1.1 500 Application Error');
$authObject = new \stdClass();
$authObject->success = false;
echo json_encode($authObject);
exit;
} else {
// This session needs to persist until the 3rd request to unset it
$_SESSION['auth'] = true;
return true;
}
} catch (Zend_Service_Exception $e) {
$this->setError(500, $e->getMessage());
$this->generateXml();
}
}
From the client's perspective it's just the cookie(s) that need to be preserved between requests. Take a look at the cookie jar functionality: http://framework.zend.com/manual/1.12/en/zend.http.client.advanced.html#zend.http.client.cookies (particularly example #3).

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