Rest API: What do first, distinguish REQUEST_METHOD or PATH_INFO? - php

I am working on a small REST API, written in PHP.
Is there a best practice, to decide what the script should do?
Do I first check if the request is GET, POST, PUT, DELETE or do I check first the PATH_INFO.
Example first check PATH_INFO:
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'))[0];
switch ($request)
{
case 'books':
if ($method = 'GET')
{
getbooks();
} elseif ($method = 'POST')
{
postbooks();
}
break;
default:
include_once('error.php');
break;
}
Example first check REQUEST_METHOD:
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'))[0];
switch ($method)
{
case 'GET':
if ($request = 'books')
{
getbooks();
} elseif ($request = 'user')
{
getuser();
}
break;
default:
include_once('error.php');
break;
}
Thank you in advance!
Also, the APIwill be very limited. Mostly a path will have only one possibleREQUEST_METHOD`.

If you want to keep it simple and understandable. Then I would prefer the following
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'))[0];
if($method == "GET" && $request == "books"){
getBooks();
}elseif ($method == "POST" && $request == "books"){
addBooks();
}elseif ($method == "PUT" && $request == "books"){
updateBooks();
}elseif ($method == "DELETE" && $request == "books"){
deleteBooks();
}

Related

Apple Wallet not giving Push Token to Web Service

I have a Pass for Apple Wallet with a webServiceURL specified which I am currently trying to get working. So far, I can tell if the pass is added or deleted, after verifying with Auth Token and I get the correct Device ID as well as Serial Numbers. However, the value of $_POST is an empty array when the pass is added, so I cannot get the Push Token. Is there something I am missing? Here is my PHP.
<?php
function unauthorized() {
header('HTTP/1.1 401 Unauthorized');
exit;
}
$headers = apache_request_headers();
if (isset($headers['Authorization']) && strpos($headers['Authorization'], 'ApplePass') === 0 && strpos($_SERVER['PATH_INFO']) !== false) {
$pathInfo = $_SERVER['PATH_INFO'];
if ($pathInfo[0] === '/') { $pathInfo = substr($pathInfo, 1); }
$parameters = explode('/', $pathInfo);
if ($parameters[0] !== 'v1' || $parameters[1] !== 'devices' || $parameters[3] !== 'registrations' || $parameters[4] !== 'MYPASSIDENTIFIER') {
unauthorzed();
exit;
}
$deviceId = $parameters[2];
$passSerial = $parameters[5];
if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
// User deleted pass
} else if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// User added pass
$payload = json_decode($_POST);
// $_POST is empty array, and $payload is always nothing
} else {
// Something fishy
unauthorized();
}
} else {
unauthorized();
}
Try using the REQUEST_URI and read the body with php://inpupt
$headers = apache_request_headers();
$request = explode("/", substr(#$_SERVER['REQUEST_URI'], 1));
if (strtoupper($_SERVER['REQUEST_METHOD']) === "POST"
&& isset($headers['Authorization'])
&& (strpos($headers['Authorization'], 'ApplePass') === 0)
&& $request[1] === "devices"
&& ($request[3] === "registrations") {
$auth_key = str_replace(array('ApplePass '), '', $headers['Authorization']);
$device_id = $request[2];
$pass_id = $request[4];
$serial = $request[5];
$dt = #file_get_contents('php://input');
$det = json_decode($dt);
// Process Device Token

Prestashop remove one checkout step

I'm new to prestashop and I'm having major trouble removing the address(I want to have only Summary=Shrnutí, Login/Guest Checkout=Přihlásit se, Delivery=Doručení and Payment=Platba here https://www.enakupak.cz/objednavka?step=1) step,. I am using prestashop 1.6.1.5
I know I have to modify order-carrier.tpl file and have followed several posts here and there but couldn't get it done right.
Does any of you have any actual idea on how to do this ?
I think that it will be change in this part of OrderController.php but dont know how to concretly change it
switch ((int)$this->step) {
case OrderController::STEP_SUMMARY_EMPTY_CART:
$this->context->smarty->assign('empty', 1);
$this->setTemplate(_PS_THEME_DIR_.'shopping-cart.tpl');
break;
case OrderController::STEP_DELIVERY:
if (Tools::isSubmit('processAddress')) {
$this->processAddress();
}
$this->autoStep();
$this->_assignCarrier();
$this->setTemplate(_PS_THEME_DIR_.'order-carrier.tpl');
break;
case OrderController::STEP_PAYMENT:
// Check that the conditions (so active) were accepted by the customer
$cgv = Tools::getValue('cgv') || $this->context->cookie->check_cgv;
if ($is_advanced_payment_api === false && Configuration::get('PS_CONDITIONS')
&& (!Validate::isBool($cgv) || $cgv == false)) {
Tools::redirect('index.php?controller=order&step=2');
}
if ($is_advanced_payment_api === false) {
Context::getContext()->cookie->check_cgv = true;
}
// Check the delivery option is set
if ($this->context->cart->isVirtualCart() === false) {
if (!Tools::getValue('delivery_option') && !Tools::getValue('id_carrier') && !$this->context->cart->delivery_option && !$this->context->cart->id_carrier) {
Tools::redirect('index.php?controller=order&step=2');
} elseif (!Tools::getValue('id_carrier') && !$this->context->cart->id_carrier) {
$deliveries_options = Tools::getValue('delivery_option');
if (!$deliveries_options) {
$deliveries_options = $this->context->cart->delivery_option;
}
foreach ($deliveries_options as $delivery_option) {
if (empty($delivery_option)) {
Tools::redirect('index.php?controller=order&step=2');
}
}
}
}
$this->autoStep();
// Bypass payment step if total is 0
if (($id_order = $this->_checkFreeOrder()) && $id_order) {
if ($this->context->customer->is_guest) {
$order = new Order((int)$id_order);
$email = $this->context->customer->email;
$this->context->customer->mylogout(); // If guest we clear the cookie for security reason
Tools::redirect('index.php?controller=guest-tracking&id_order='.urlencode($order->reference).'&email='.urlencode($email));
} else {
Tools::redirect('index.php?controller=history');
}
}
$this->_assignPayment();
if ($is_advanced_payment_api === true) {
$this->_assignAddress();
}
// assign some informations to display cart
$this->_assignSummaryInformations();
$this->setTemplate(_PS_THEME_DIR_.'order-payment.tpl');
break;
default:
$this->_assignSummaryInformations();
$this->setTemplate(_PS_THEME_DIR_.'shopping-cart.tpl');
break;
}
What if you cann this code after first case - break:
case OrderController::STEP_SUMMARY_EMPTY_CART:
$this->context->smarty->assign('empty', 1);
$this->setTemplate(_PS_THEME_DIR_.'shopping-cart.tpl');
break;
After this case add this case:
case OrderController::STEP_ADDRESSES:
$this->_assignAddress();
$this->processAddressFormat();
if (Tools::getValue('multi-shipping') == 1) {
$this->_assignSummaryInformations();
$this->context->smarty->assign('product_list', $this->context->cart->getProducts());
$this->setTemplate(_PS_THEME_DIR_.'order-address-multishipping.tpl');
} else {
$this->autoStep();
$this->_assignCarrier();
$this->setTemplate(_PS_THEME_DIR_.'order-carrier.tpl');
}
break;
Check, is it work.

Facebook Realtime API

I believe to have Facebook realtime notifications set up correctly but don't receive any notifications. Any ideas?
And here my callback.php
define('VERIFY_TOKEN', 'SECRET');
$method = $_SERVER['REQUEST_METHOD'];
if ($method == 'GET' && $_GET['hub_mode'] == 'subscribe' && $_GET['hub_verify_token'] == VERIFY_TOKEN) {
echo $_GET['hub_challenge'];
} else if ($method == 'POST') {
if ( isset( $_SERVER['HTTP_X_HUB_SIGNATURE'] ) ) {
$post_body = file_get_contents("php://input");
if ($_SERVER['HTTP_X_HUB_SIGNATURE'] == "sha1=" . hash_hmac('sha1', $post_body, VERIFY_TOKEN)) {
$object = json_decode($post_body, true);
file_put_contents('/PATH_TO_FOLDER/updates.txt', $object, FILE_APPEND);
}
}
}
I'm not getting anything and the .txt file is not created.

Using $_Request inside function PHP

1)
I have this:
function ObtainRequest($Field, $Method) {
$Returned = "";
if ($Method == "POST")
$Returned = $_POST[$Field];
else if ($Method == "GET")
$Returned = $_GET[$Field];
else
$Returned = $_REQUEST[$Field];
return $Returned;
}
Now, using the function:
if (isset(ObtainRequest("OneField","POST"))) {
DoSomething();
} else if (!isset(ObtainRequest("OneField","POST"))) {
DoOtherthing();
}
But my script isn't running (SHOWING PLANK PAGE)...
What's my mistake?
2)
The $_REQUEST is lost inside of function?
This code works!!:
if (isset($_REQUEST["OneField"])) {
DoSomething();
}
This code doesn't work!!:
if (isset(ObtainRequest("OneField","REQUEST"))) {
DoSomething();
}
This code doesn't work!!:
if (empty(ObtainRequest("OneField","REQUEST"))) {
DoSomething();
}
3)
Is it applicable to Session too?
Your mistake is here:
$Method == "Post"
But you passing uppercased POST:
ObtainRequest("OneField","POST")
Fix with strtoupper():
function ObtainRequest($Field, $Method) {
$Returned = "";
$Method = strtoupper($Method);
if ($Method == "POST")
$Returned = isset($_POST[$Field]) ? $_POST[$Field] : false;
else if ($Method == "GET")
$Returned = isset($_GET[$Field]) ? $_GET[$Field] : false;
else
$Returned = isset($_REQUEST[$Field]) ? $_REQUEST[$Field] : false;
return $Returned;
}
Also, this function might be shortened with switch construction:
function ObtainRequest($Field, $Method) {
switch(strtoupper($Method)){
case "POST": return isset($_POST[$Field]) ? $_POST[$Field] : false;
case "GET": return isset($_GET[$Field]) ? $_GET[$Field] : false;
default: return isset($_REQUEST[$Field]) ? $_REQUEST[$Field] : false;
}
}
Second problem is that isset() might be used with variables, but not with function results. Use boolean check instead:
if (ObtainRequest("OneField","POST") !== false) {
DoSomething();
} else if (ObtainRequest("OneField","POST") === false) {
DoOtherthing();
}
Is it applicable to Session too?
Well, if you interested in my opinion: I would not mix $_SESSION in such function with $_POST, $_GET and $_REQUEST, because $_SESSIONs meaning is different. Also, it exists differently, not like them.
However something like this function might be realized for $_SESSION itself.
The first problem which I can see that you are using post instead of POST...
yes you can do this with sessions too, but codes need to be modified a bit..

Facebook JSON object in file_get_contents("php://input") doesn't return value

I'm trying to print out the or access the JSON objects returned by the POST request from Facebook. Here's the code:
<?php
define('VERIFY_TOKEN', 'mysecretverifytokenstring');
$method = $_SERVER['REQUEST_METHOD'];
if ($method == 'GET' && $_GET['hub_mode'] == 'subscribe' && $_GET['hub_verify_token'] == VERIFY_TOKEN) {
echo $_GET['hub_challenge'];
} else if ($method == 'POST') {
$post_body = file_get_contents("php://input");
$object = json_decode($post_body, true);
print_r($object);
}
?>
This would not output any, even though I can connect in Realtime Updates successfully.

Categories