I am using this method to make apache header request work in nginx.
if (!function_exists('apache_request_headers')) {
function apache_request_headers() {
foreach($_SERVER as $key=>$value) {
if (substr($key,0,5)=="HTTP_") {
$key=str_replace(" ","-",ucwords(strtolower(str_replace("_"," ",substr($key,5)))));
$out[$key]=$value;
}else{
$out[$key]=$value;
}
}
return $out;
}
}
I retrieve the header like so $headers = apache_request_headers(); and use an array to hold json.
$response=array()
$response["error"] = true;
$response["message"] = $headers;
The code below is what is inside of the $response array variable:
{
error: true
message: {
CONTENT_LENGTH: "13"
CONTENT_TYPE: "application/x-www-form-urlencoded"
DOCUMENT_ROOT: "/home4/admin/public_html"
GATEWAY_INTERFACE: "CGI/1.1"
Accept: "*/*"
Accept-Encoding: "gzip, deflate"
Accept-Language: "en-US,en;q=0.8"
Connection: "close"
Cookie: "_ga=GA1.2.1266385826.1428275832"
Host: "mysite.com"
Origin: "chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo"
User-Agent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36"
X-Apikey: "bca0de3e7c10cb6623ef00021caf9450"
X-Http-Proto: "HTTP/1.1"
X-Log-7528: "107.147.160.193"
X-Real-Ip: "107.147.160.193"
PATH: "/bin:/usr/bin"
PHPRC: "/home4/admin"
QUERY_STRING: ""
REDIRECT_STATUS: "200"
REDIRECT_UNIQUE_ID: "VVlk5sD##rgAACwVT0AAAACM"
REDIRECT_URL: "/rmapp/v1/tasks"
REMOTE_ADDR: "107.147.160.193"
REMOTE_PORT: "31527"
REQUEST_METHOD: "POST"
REQUEST_URI: "/rmapp/v1/tasks"
SCRIPT_FILENAME: "/home4/admin/public_html/rmapp/v1/index.php"
SCRIPT_NAME: "/rmapp/v1/index.php"
SERVER_ADDR: "192.185.226.161"
SERVER_ADMIN: "webmaster#mysite.com"
SERVER_NAME: "mysite.com"
SERVER_PORT: "80"
SERVER_PROTOCOL: "HTTP/1.1"
SERVER_SIGNATURE: "<address>Apache Server at mysite.com Port 80</address> "
SERVER_SOFTWARE: "Apache"
UNIQUE_ID: "VVlk5sD##rgAACwVT0AAAACM"
PHP_SELF: "/rmapp/v1/index.php"
REQUEST_TIME: 1431921894
argv: [0]
argc: 0
}-
}
My problem is, I need to grab X-ApiKey from $header, but using $api_key = $headers['X-ApiKey']; returns nothing, but as you can see, X-ApiKey exists in $header. Can someone please tell me what I'm missing here?
Looks like you are using the wrong variable name. Variable names are case-sensitive.
The response returns the following (small k in Apikey):
X-Apikey: "bca0de3e7c10cb6623ef00021caf9450"
while you are using capital k $api_key = $headers['X-ApiKey'];
Try the following:
$api_key = $headers['X-Apikey'];
$response["message"] is a string. First try to explode it and then access it -
$temp = explode('X-Apikey:', $response['message']);
$temp1 = explode('X-Http-Proto:', $temp[1]);
var_dump(trim(str_replace('"', '', $temp1[0])));
Output
string(32) "bca0de3e7c10cb6623ef00021caf9450"
Related
I have php function that is supposed to verify if there is a token, and if so, search my table for a company name that matches. The function works fine when I use xampp in localhost. When I do it in prod on the server, it gives me a 'token undefined' error, What could possibly be causing the error?
my php function
public function findCompany(){
echo "global var= ";
// var_dump($GLOBALS['headers']['Authorization']);
// var_dump($GLOBALS);
var_dump($_SERVER['REMOTE_ADDR']);
if (isset($GLOBALS['headers']['Authorization'])) {
if ($id = $this->VerifyUserToken($GLOBALS['headers']['Authorization'], $_SERVER['REMOTE_ADDR'])) {
$data = [
'company_name' => $_POST['company_name']
];
$companies = $this->currentModel->findCompany($data);
if($companies){
echo json_encode($companies);
} else {
echo json_encode(['success' => false]);
}
}
else {
echo json_encode(['success' => false, 'error' => "invalid token"]);
}
} else {
echo json_encode(['success' => false, 'error' => "token undefined"]);
}
}
}
the verifyUserToken function
public function verifyUserToken($token, $ip) {
$db = new Database();
$db->query('SELECT * FROM auth WHERE token = :token AND expiry >now()');
$db->bind(':token', $token);
//check database if token exists and is not expired
if($res = $db->single()) {
// checks if token matches to ip address
// returns user or contact id if verified else returns false
if($res->token === $token && $res->ip === $ip) {
$this->cleanTokens();
if($res->user_id >0) {
return $res->user_id;
}
//
} else {
return false;
}
} else {
return false;
}
}
I checked the database, and the token is clearly there. anyway, it's not giving me an invalid token message. it looks like the token isn't being sent.
It works fine when I do it in localhost on my machine.
IN order to debug, I used var_dump to see what gets sent. I don't have much experience with PHP, but it looks like my headers authorizations never gets set. what could be the solution
see the images and code below for what I get in the console when I try. I truncated some of the paths for security purposes
echo "global var= ";
and
var_dump($GLOBALS);
you get
["GLOBALS"]=>
*RECURSION*
["headers"]=>
array(13) {
["Host"]=>
string(20) "globalplantbased.com"
["Connection"]=>
string(10) "keep-alive"
["Content-Length"]=>
string(2) "15"
["Pragma"]=>
string(8) "no-cache"
["Cache-Control"]=>
string(8) "no-cache"
["Accept"]=>
string(33) "application/json, text/plain, */*"
["User-Agent"]=>
string(115) "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36"
["Content-Type"]=>
string(33) "application/x-www-form-urlencoded"
["Origin"]=>
string(27) "http://globalplantbased.com"
["Referer"]=>
string(59) "http://globalplantbased.com"
["Accept-Encoding"]=>
string(13) "gzip, deflate"
["Accept-Language"]=>
string(14) "en-US,en;q=0.9"
["Cookie"]=>
string(31) "_ga=GA1.2.1321601484.1609694939"
or
echo "global var= ";
and
var_dump($GLOBALS['headers']['Authorization']);
or
echo "global var= ";
and
var_dump($_SERVER['REMOTE_ADDR']);
[![($GLOBALS['headers']['Authorization'])2]2
$this->VerifyUserToken($GLOBALS['headers']['Authorization...
Has to be
$this->verifyUserToken($GLOBALS['headers']['Authorization
Windows does not make a Difference between capital and small Letters
Regards,
Henrik
I want to post data from Frontend to MYSQL database in the backend using Laravel API. I tried the following code, but it outputs a 500: Internal Server Error while trying to post.
public function postOrder(Request $request)
{
/*
$request is a JSON Object which looks like
{"order":{"table_id":2,"food_id":4,"status":1}}
*/
$order = new Order();
$order->table_id = $request->order->table_id;
$order->food_id = $request->food_id;
$order->user_id = $request->user_id;
$order->status = $request->status;
$order->save();
return response()->json(['message' => 'Order Added'], 201);
}
Should I json_decode($request)? How?
When I error_log($request), here's what I get:
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8
Connection: keep-alive
Content-Length: 60
Content-Type: application/json
Host: localhost:8000
Origin: http://localhost:8100
Referer: http://localhost:8100/
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML
, like Gecko) Chrome/55.0.2883.87 Safari/537.36
X-Xsrf-Token: eyJpdiI6IlJpNVV1ejhZTDVaSnVcL09lVkFIZER3PT0iLCJ2YWx1ZSI6IjNFK0
NnSXFsczd1eGJBRjZiZFc3U3lBUE9jR1lNZ0hSN0ZWNVpyWHlyWGE1TVZvZW9vK1F0eExXVjdkQzdPS
nBISEM3UXBINGQxZ09jTCttQ0huYmlnPT0iLCJtYWMiOiJmZWNiMTY1NTJjNjYyNDZjM2Q3YTE2N2Jl
NWNmYjgwYmNiMTlkNThjYWQ2NjEyYjk3YzQ4ZTVkYjQwMzFjY2VlIn0=
{"order":{"table_id":2,"food_id":4,"time":"333","status":1}}
You need to use json_decode() to get an associative array:
$json = '{"order":{"table_id":2,"food_id":4,"time":"333","status":1}}';
$array = json_decode($json, true);
var_dump($array['order']); //Here you can see that it is an associative array with the needed values now
Then you can create a model based on it.
$order = Order::create($array['order']);
that could be the solution:
json_decode($request, true)['order']['table_id']
When I try to implement auto-complete using the code below :
$('#keyword').autocomplete({
source : '/Dev/pages/search.php',
minLength : 3,
type : 'POST',
select: function( event, ui )
{
$(this).data("autocomplete").menu.element.addClass("yellow");
}
})
.data( "ui-autocomplete" )._renderItem = function( ul, item )
{
console.log(item);
return $( "<li>" )
.append( "<a>" + add3Dots(item.name,20) + "</a>" )
.appendTo( ul );
};
if (isset($_POST["term"])){
$term = trim($_GET['term']);
$parts = explode(' ', $term);
$p = count($parts);
$a_json = array();
$a_json_row = array();
$search = connexion::bdd_test();
$requete = "SELECT name from BDD_TEST.companies";
for($i = 0; $i < $p; $i++) {
$requete .= ' WHERE name LIKE ' . "'%" . $conn->real_escape_string($parts[$i]) . "%'";
}
$result = $search->query($requete);
while($donnees = $result->fetch(PDO::FETCH_ASSOC)) {
$a_json_row["name"] = $data['name'];
array_push($a_json, $a_json_row);
}
}
else
{
$a_json['call']=false;
$a_json['message']="Problem to collect word.";
}
$json = json_encode($a_json);
print_r($json);
When I test, if condition is not satisfied and I get the message directly from else " Problem to collect word . "
It means that $_POST["term"] is not defined.
How can I retrieve the input value ?
To be sure that values have been send, you can see what headers the browser sent to the web server with PHP for testing purposes.
This is possible using the apache_request_headers() function but it only works if PHP is run on Apache as a module.
How using apache_request_headers() :
If PHP is run on Apache as a module then the headers the browser send can be retrieved using the apache_request_headers() function. The following example code uses print_r to output the value from this function call:
print_r(apache_request_headers());
The output from the above using an example request from Google Chrome would output something similar to the following:
Array
(
[Host] => www.testing.local
[Connection] => keep-alive
[User-Agent] => Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/532.0 (KHTML, like Gecko) Chrome/4.0.206.1 Safari/532.0
[Cache-Control] => max-age=0
[Accept] => application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
[Accept-Encoding] => gzip,deflate,sdch
[Accept-Language] => en-US,en;q=0.8
[Accept-Charset] => ISO-8859-1,utf-8;q=0.7,*;q=0.3
)
Alternative when PHP is run as a CGI :
If PHP is not being run as a module on Apache, the browser headers should be stored in the $SERVER array with the key being the request header name converted to upper case, hypens replaced with underscores, and prefixed with HTTP
The same request above showing the relevent lines from $_SERVER are as follows:
[HTTP_HOST] => www.testing.local
[HTTP_CONNECTION] => keep-alive
[HTTP_USER_AGENT] => Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/532.0 (KHTML, like Gecko) Chrome/4.0.206.1 Safari/532.0
[HTTP_CACHE_CONTROL] => max-age=0
[HTTP_ACCEPT] => application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
[HTTP_ACCEPT_ENCODING] => gzip,deflate,sdch
[HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.8
[HTTP_ACCEPT_CHARSET] => ISO-8859-1,utf-8;q=0.7,*;q=0.3
The alternative method is create our own function if the apache_request_headers() function does not exist, which extracts just the values from $_SERVER and converts the key names to the same style as apache_request_headers(). This works like so:
if(!function_exists('apache_request_headers')) {
function apache_request_headers() {
$headers = array();
foreach($_SERVER as $key => $value) {
if(substr($key, 0, 5) == 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))))] = $value;
}
}
return $headers;
}
}
The new function is only declare if the function with that name does not already exist. The end result is that whether or not the internal PHP function exists, you will be able to call a function with this name in your code.
A loop is done though the $SERVER array and any whose key starts with HTTP is added to the array, and the key is translated via a series of function calls to be in the same format as returned by apache_request_headers().
View HTTP headers in Google Chrome
Chrome has a tab "Network" with several items and when I click on them I can see the headers on the right in a tab.
Press F12 on windows or ⌥⌘I on a mac to bring up the Chrome developer tools.
Try to retrieve value(s) without knowing HTTP methods
You can detect which request type was used (GET, POST, PUT or DELETE) in PHP by using
$_SERVER['REQUEST_METHOD']
For more details please see the documentation for the $_SERVER variable.
Or you can retrieve value(s) using $_REQUEST['you_variable'].
Note $_REQUEST is a different variable than $_GET and $_POST, it is treated as such in PHP -- modifying $_GET or $_POST elements at runtime will not affect the elements in $_REQUEST, nor vice versa.
I am trying to get twitter posts following this tutorial:
https://www.youtube.com/watch?v=tPrsVKudecs
there aren't a lot of tutorials regarding this online, and twitters console doesn't support running queries anymore as far as I understood.
any idea why this is happening?
This is the output I get in the Chrome "Network":
Remote Address:54.666.666.666:80
Request URL:http://666.com/yh/test/tweets_json.php
Request Method:GET
Status Code:500 Internal Server Error
Response Headers
view source
Connection:close
Content-Length:0
Content-Type:text/html
Date:Mon, 15 Jun 2015 13:51:40 GMT
Server:Apache/2.4.7 (Ubuntu)
X-Powered-By:PHP/5.5.9-1ubuntu4.5
Request Headers
view source
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Host:666.com
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36
Any ideas why this is happening?
Is there a better simple way to do it?
EDIT:
tweets_json.php
<?php
require 'tmhOAuth.php'; // Get it from: https://github.com/themattharris/tmhOAuth
// Use the data from http://dev.twitter.com/apps to fill out this info
// notice the slight name difference in the last two items)
$connection = new tmhOAuth(array(
'consumer_key' => '',
'consumer_secret' => '',
'user_token' => '', //access token
'user_secret' => '' //access token secret
));
// set up parameters to pass
$parameters = array();
if ($_GET['count']) {
$parameters['count'] = strip_tags($_GET['count']);
}
if ($_GET['screen_name']) {
$parameters['screen_name'] = strip_tags($_GET['screen_name']);
}
if ($_GET['twitter_path']) { $twitter_path = $_GET['twitter_path']; } else {
$twitter_path = '1.1/statuses/user_timeline.json';
}
$http_code = $connection->request('GET', $connection->url($twitter_path), $parameters );
if ($http_code === 200) { // if everything's good
$response = strip_tags($connection->response['response']);
if ($_GET['callback']) { // if we ask for a jsonp callback function
echo $_GET['callback'],'(', $response,');';
} else {
echo $response;
}
} else {
echo "Error ID: ",$http_code, "<br>\n";
echo "Error: ",$connection->response['error'], "<br>\n";
}
// You may have to download and copy http://curl.haxx.se/ca/cacert.pem
tmhOAuth.php: https://github.com/themattharris/tmhOAuth/blob/master/tmhOAuth.php
and this pem key: http://curl.haxx.se/ca/cacert.pem
All three in the same folder
In the tutorial it should run the query and get the json output.
I get a blank page.
I´m sending an ajax request with a custom header called Authorization,
and I'm trying to get that header with PHP
if (!function_exists('getallheaders'))
{
function getallheaders()
{
$headers = array();
foreach ($_SERVER as $k => $v)
{
if (substr($k, 0, 5) == "HTTP_")
{
$k = str_replace('_', ' ', substr($k, 5));
$k = str_replace(' ', '-', ucwords(strtolower($k)));
$headers[$k] = $v;
}
}
return $headers;
}
}
$val = getallheaders();
echo $val;
and I get all the headers but not the custom one
val: Object{
Accept: "application/json, text/plain, */*"
Accept-Encoding: "gzip, deflate, sdch"
Accept-Language: "es-ES,es;q=0.8,en;q=0.6"
Connection: "keep-alive"
Host: "www.localhost.com"
Origin: "http://localhost"
Referer: "http://localhost/gestion/"
User-Agent: "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36"
}
Any clues why I'm not getting header Authorization?
For custom headers the $_SERVER global in php documentation state that
There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here. That said, a large number of these variables are accounted for in the » CGI/1.1 specification, so you should be able to expect those
so try to use apache_request_headers which may help you if your working with apache as a server
Server Quote
apache_request_headers