Request Response with PHP front-end and back-end - php

Currently, I have a client application sending requests (POST) to my local server. Basically a login form.
Now I would like for my local server, implemented in PHP, to send a response back to the client telling the client what errors were found...
Here is what I do to generate a response:
HttpResponse::setData('Incorrect Length for Password');
HttpResponse::send();
But nothing is in the response table in Chrome's debugger tools (Response) column.
I am able to successfully manipulate the header to redirect the user back to the login if there was no match within the database for said username and password combination:
header( 'Location: http://localhost:8080/iSchedj/index.php');
But this is all I can do... Just redirect... And I think this is not the way I am supposed to be redirecting. I feel that the client should be redirecting with respect to the response sent from the server to the client and have the client handle redirecting the user. I am quite new to web development.

HttpResponse is only available when using pecl_http. The default way to output content with php is to simply echo it. In rare occasions you might want to exit processing after some content, you could use die for that.
either:
echo 'Incorrect Length for Password');
or:
die('Incorrect Length for Password');
You also might want to add error reporting into your PHP file, preferably at the beginning:
ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);
This should only be considered for developing though.

Related

Google drive api file_get_contents and refferer

I am trying to list files from google drive folder.
If I use jquery I can successfully get my results:
var url = "https://www.googleapis.com/drive/v3/files?q='" + FOLDER_ID + "'+in+parents&key=" + API_KEY;
$.ajax({
url: url,
dataType: "jsonp"
}).done(function(response) {
//I get my results successfully
});
However I would like to get this results with php, but when I run this:
$url = 'https://www.googleapis.com/drive/v3/files?q='.$FOLDER_ID.'+in+parents&key='.$API_KEY;
$content = file_get_contents($url);
$response = json_decode($content, true);
echo json_encode($response);
exit;
I get an error:
file_get_contents(...): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden
If I run this in browser:
https://www.googleapis.com/drive/v3/files?q={FOLDER_ID}+in+parents&key={API_KEY}
I get:
The request did not specify any referer. Please ensure that the client is sending referer or use the API Console to remove the referer restrictions.
I have set up referrers for my website and localhost in google developers console.
Can someone explain me what is the difference between jquery and php call and why does php call fails?
It's either the headers or the cookies.
When you conduct the request using jQuery, the user agent, IP and extra headers of the user are sent to Google, as well as the user's cookies (which allow the user to stay logged in). When you do it using PHP this data is missing because you, the server, becomes the one who sends the data, not the user, nor the user's browser.
It might be that Google blocks requests with invalid user-agents as a first line of defense, or that you need to be logged in.
Try conducting the same jQuery AJAX request while you're logged out. If it didn't work, you know your problem.
Otherwise, you need to alter the headers. Take a look at this: PHP file_get_contents() and setting request headers. Of course, you'll need to do some trial-and-error to figure out which missing header allows the request to go through.
Regarding the referrer, jQuery works because the referrer header is set as the page you're currently on. When you go to the page directly there's no referrer header. PHP requests made using file_get_contents have no referrer because it doesn't make much sense for them to have any.

php webhook not responding to Stripe test event

I've setup a basic webhook php page as modeled on the stripe documentation and listed below. When I send a test event from the Stripe webhooks dashboard, stripe responds "Test webhook sent successfully" with a blankk reponse. However, the output log file is not written to, no email is sent and there is nothing logged to the http server error log or the php error log. My php version is 5.3.3. What am I doing wrong?
<?php
error_reporting(15);
// Set your secret key: remember to change this to your live secret key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
require_once('vendor/autoload.php');
\Stripe\Stripe::setApiKey("secret_test_key");
$handle = fopen("webhook.log","a");
// Retrieve the request's body and parse it as JSON
$input = file_get_contents("php://input");
$event_json = json_decode($input);
// Do something with $event_json
if (fwrite($handle, $event_json) === FALSE) {
mail("mike#example.com","Cannot write to webhook.log","");
echo "Cannot write to webhook.log";
exit;
}
mail('mike#example.com','Webhook Event',$event_json);
header(':', true, 200);
//http_response_code(200); // PHP 5.4 or greater
?>
You have a few potential problems. As a quick rule of thumb, the best way to debug this is to start by triggering the event yourself, which you can do simply by loading up your webhook url in a browser yourself. Then you can test it directly and make sure it is doing what you expect it to be doing. There are obviously two possibilities:
Stripe is not triggering your webhook handler for some reason
Your handler is not properly logging itself
The latter first: it could be that Stripe is triggering your handler but it isn't logging that fact successfully. This would mean that both your email logging and file logging are failing. That is actually quite possible. Email logging with the mail function is actually very unreliable, unless you know for a fact that it works. Mail sent with the mail function is dropped silently by most modern email systems (gmail, etc) unless you have your DNS records properly configured, which most people don't. So unless you know for sure that your mail attempt is working properly, it probably isn't. If you also happen to have a permission issue in your attempt to write to a log file (which is not uncommon for a newly setup server), your logs could simply be failing. The easiest way to check that is to load up the webhook URL in a browser yourself. That way you know it is being triggered, and can know for sure if the issue is improper logging or Stripe not calling your webhook.
If you determine for sure that stripe isn't calling your webhook, the most likely culprit would be an invalid HTTPS certificate. Is your webhook connected via HTTPS (it should be)? If so, is it a valid certificate? You can tell your browser to ignore an invalid certificate when you browse your own site, but stripe will simply refuse to send the request if it encounters an invalid certificate.
If none of the above fixes it then it will be time for more digging, but I would start with those: they are probably the most likely problems.
The solution is that $event_json is an object and the fwrite failed because it expects a string not an object. By converting to an array and then serializing I was able to both write to the log and send the email.
$event_json = (array)json_decode($input);
$event = serialize($event_json);

SessionID changes with each HTTP request

I've just started using the fetch API to send my data as ReactJS recommends. Prior to this, to send API requests to my server I used AngularJS. I am currently encountering the most annoying bug, sending HTTP requests fails to load the correct session.
Firstly, my web application uses a PHP API to expose itself and is (basically for now) a bunch of .php files to get parts of the app. One of them is authenticateUser.php which authenticates and stores the session. However, I noticed that my HTTP requests with fetch weren't working as expected as other stuff like getCurrentUser.php returned NotLoggedIn, despite just authenticating. I thought it might have something to do with the sessions, so on authenticateUser.php, I set my .php file to output the current session_id after authenticating via.: (echo array('session_id' => session_id());
I have noticed that basically, when I myself load the url myself in the browser: myapp.com/php/http/user/authenticateUser.php, the session_id I get is completely different from the one I get when using fetch:
return fetch("/php/http/user/authenticateUser.php", {
method: "post",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(successResponse) {
return successResponse.json();
}, function(errorResponse) {
console.log(errorResponse);
}).then(function(data) {
console.log(data);
});
I checked further and thought maybe it was because fetch was querying http version of my site instead of the non-HTTP version of my site. So I changed the logic on authenticateUser.php such that if it detects a session existing, it prints out that session_id, else it creates and prints out the new one. Everytime I sent my HTTP request with fetch I got a different session_id meaning that my session_id was changing with each request. Here is the code I used:
header("Content-Type: application/json");
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
http_response_code(200);
echo json_encode(array('session_id' => session_id()),JSON_PRETTY_PRINT);
Am I missing something completely different with fetch API, or headers? Or does anyone have any experience with this that could possibly enlighten me?
The answer is that fetch by default does not send cookies, you need to specify it via:
credentials: same-origin

sending a response from a php script to iOS

I am creating an iPhone app which sends a username and password to a php script, the php script then looks in a mySQL database for the values and sets a boolean to either 0 or 1, depending on whether or not the user should be authenticated. I really have no idea where to start or even what I should Google to look into how to do this.
Is this feasible?
Is this the proper way to authenticate a user in an iOS app?
Thanks!
There are various types to achieve this.
a) Generate an XML or JSON file in PHP, and read the content back in iOS. (this method gives you the benefit of fetching any extra data if you want).
b) Send back HTTP header() from PHP, and read the HTTP response code. you can do something like this.
function checkLogin()
{
//Check login
if($login == true) {
header('HTTP/1.1 200 OK');
} else {
header('HTTP/1.1 401 Unauthorized');
}
}
c) You can output anything in PHP(plain text, JSON, HTML etc.), as the output generated by PHP will be received as HTTP response.
Anything the PHP script outputs will be returned as the HTTP response. Simply output something meaningful, and read it in the client.
The simplest solution would be to use HTTP status codes. Then you don't even have to care about the response body.
If authenticated: "HTTP 200 OK"
If unauthorized: "HTTP 401 Unauthorized"
Resource: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
You can write a php script like this:
<?php
// the authentication procedures memorized in the $authentication variable the result of authentication process. Supposed to be 1 if successful
echo $authentication;
?>
Call this script from your iOS by using an NSURLRequest object for example.
P.S.: However, for data exchange between the client and the server you should use the JSON format.

Getting empty result within PHP when in browser I get the JSON exception

I have this code:
$url="https://graph.facebook.com/me/friends?access_token=".$access_token."&fields=id,first_name,last_name&limit=10";
$content=file_get_contents($url);
Whenever I use this on a non authenticated user I should get feedback of OAuthException, which doesn't show up in the PHP the $content is empty. While if I copy the URL to the browser I get the result and I see the exception.
I want to detect if the user is logged in and the session data is valid.
What might be wrong?
Maybe Facebook decides whether to respond with exception feedback or with just no response depending on the contents of Accept HTTP header(s) you are sending (file_get_contents sends different HTTP headers than your browser).

Categories