PHP apache_request_headers does not work well - php

Hello may ask this why is it that on my code i cannot obtain the headers['Authorization'] when executing my code?
coz meanwhile iv'e developed a REST API that can handle database to clients using php-json-mysql so when i use GET method together i also include my apikey into headers as 'Authorization' but i cannot fetch it in my code.
Here's my approach:
$headers = apache_request_headers();
if (isset($headers['Authorization'])) {
//Good
}else {
//API KEY is missing
}
but in my request header it says that
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36
Authorization: API_KEY
Accept: */*
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
im using Advance REST Client extension on chrome.
anyone encounter this?

The Authorization header has a specific format it should conform to.
Since using it as
Authorization: API_KEY
is not valid, the web server is probably ignoring it altogether. You might want to use a custom header like this:
X-Authorization: API_KEY or
X-Api-Key: API_KEY
It's been a while since I've used PHP but I think if you send the header like this, you can't get them by using apache_request_headers so you will have to obtain it this way:
$_SERVER['HTTP_X_AUTHORIZATION'] or
$_SERVER['HTTP_X_API_KEY']

Related

Check whether a url exists or not in Shopify

How can I validate a Shopify store's URL? Given a URL how can I know whether it is a valid URL or 404 page not found? I'm using PHP. I've tried using PHP get_headers().
<?php
$getheadersvalidurlresponse= get_headers('https://test072519.myshopify.com/products/test-product1'); // VALID URL
print_r($getheadersvalidurlresponse);
$getheadersinvalidurlresponse= get_headers('https://test072519.myshopify.com/products/test-product1451'); // INVALID URL
print_r($getheadersinvalidurlresponse);
?>
But for both valid and invalid URLs, I got the same response.
Array
(
[0] => HTTP/1.1 403 Forbidden
[1] => Date: Wed, 08 Jul 2020 13:27:52 GMT
[2] => Content-Type: text/html
[3] => Connection: close
..............
)
I'm expecting 200 OK status code for valid URL and 404 for invalid URL.
Can anyone please help to check whether given shopify URL is valid or not using PHP?
Thanks in advance.
This happens because Shopify differentiates between bot requests and actual genuine requests to avoid denial of service attack up to a certain point. To overcome this problem, you will have to specify the user-agent header to mimic a browser request for an appropriate HTTP response.
As an improvement, you can make a HEAD request instead of a GET request(as get_headers() uses GET request by default, as mentioned in the examples) because here we are only concerned about response metadata and not response body.
Snippet:
<?php
$opts = array(
'http'=>array(
'method'=> "HEAD",
'header'=> "User-agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36"
)
);
$headers1 = get_headers('https://test072519.myshopify.com/products/test-product1',0,stream_context_create($opts));
$headers2 = get_headers('https://test072519.myshopify.com/products/test-product1451',0,stream_context_create($opts));
echo "<pre>";
print_r($headers1);
print_r($headers2);

JWT Authorization [duplicate]

This question already has answers here:
How to enable CORS in AngularJs
(10 answers)
XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header
(11 answers)
Origin evil.example in Request Header
(2 answers)
Closed 4 years ago.
I'm implementing a JWT for secure my API. my front-end is coded with Angular and the back-end with PHP.
I have a problem with the authorization set in the header. I'm sending a request to the server with the JWT that I stored but I don't know really how the back-end read that header
users.get = function(project){
var req = {
method: 'GET',
url: Global.url_api+'action=GET&table='+project+'_users',
headers: {
'Authorization': 'Bearer '+localStorage.getItem('tokenAPI')
}
}
console.log(req);
return $http(req);
My server isn't able to read that header, the Authorization variable is set to "NULL"
I'm trying to read with :
var_dump($_SERVER['HTTP_AUTHORIZATION']);
Here is my request in the browser :
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7
Access-Control-Request-Headers: authorization
Access-Control-Request-Method: GET
Host:
Origin: http://evil.com/
Proxy-Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36
It's looking like there is no authorization set in the header, but my token is generated and stored by the client with the following:
if(response.status == 200){ //Status 200 : Everything OK
var jwt_token = response.data.jwt;
localStorage.setItem('tokenAPI',jwt_token); //Set the token sent by server in localStorage
$scope.credentials = true; //Set visible the tab

PayPal sandbox IPN validation always return INVALID

I googled this question and tried all suggestions but nothing works.
I tried this code: https://developer.paypal.com/docs/classic/ipn/ht_ipn/ but it don't work. Just copy-pasted it and deleted old magick_quotes routunes.
I tried this code: http://samples.geekality.net/view-source.php?file=ipn/ipn_handler.class.php and it also do not work.
In all cases I tried to do following:
$req = 'cmd=_notify-validate&' . file_get_contents('php://input');
To ensure I sent to IPN exactly what it sent to me. In addition I used the debug proxy (Fiddler) and saved what IPN sent to me and what I sent to IPN. The requests bodies are byte-to-byte identical except my request is prefixed by the cmd=_notify-validate& string.
Yes, I checked I use proper sandbox URL. Here are entire requests bodies:
What IPN sent to me: (I just replaced personal data to XXX)
POST http://localhost.loc/en/payment/success/1 HTTP/1.1
Host: localhost.loc
Connection: keep-alive
Content-Length: 921
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: null
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4
mc_gross=1.00&protection_eligibility=Ineligible&payer_id=5XNKM66NSDKC4&tax=0.00&payment_date=05%3A34%3A11+Jun+01%2C+2015+PDT&payment_status=Completed&charset=utf-8&first_name=XXX&mc_fee=0.33&notify_version=3.8&custom=topup%3A262262%3A1%3A1433162020&payer_status=verified&business=XXX&quantity=1&payer_email=XXX&verify_sign=AG58dBsn5g2z8O8NEjotbuJGP14PAIpZ4k26VL8IyhaDPkcDRj002Keq&memo=hmgvjgjhgfjhfggjhfjtfgjh&txn_id=4CN141026K278934Y&payment_type=instant&last_name=XXX&receiver_email=XXX&payment_fee=0.33&receiver_id=DCMXPXGX4QX6J&txn_type=web_accept&item_name=Account+top+up&mc_currency=USD&item_number=Account+262262+top+up&residence_country=US&test_ipn=1&handling_amount=0.00&transaction_subject=topup%3A262262%3A1%3A1433162020&payment_gross=1.00&shipping=0.00&auth=ANSTBwT3znll-gJQZO2cLoV5QJFW9v8W.FqyWxffdtI0L-9mfsoe2xRL44M86Sn2XtYGtcqG4Fjjel1kdYZyxpQ
What I sent to IPN:
POST https://www.sandbox.paypal.com/cgi-bin/webscr HTTP/1.1
Host: www.sandbox.paypal.com
Accept: */*
Content-Length: 942
Content-Type: application/x-www-form-urlencoded
cmd=_notify-validate&mc_gross=1.00&protection_eligibility=Ineligible&payer_id=5XNKM66NSDKC4&tax=0.00&payment_date=05%3A34%3A11+Jun+01%2C+2015+PDT&payment_status=Completed&charset=utf-8&first_name=XXX&mc_fee=0.33&notify_version=3.8&custom=topup%3A262262%3A1%3A1433162020&payer_status=verified&business=XXX&quantity=1&payer_email=XXX&verify_sign=AG58dBsn5g2z8O8NEjotbuJGP14PAIpZ4k26VL8IyhaDPkcDRj002Keq&memo=hmgvjgjhgfjhfggjhfjtfgjh&txn_id=4CN141026K278934Y&payment_type=instant&last_name=XXX&receiver_email=XXX&payment_fee=0.33&receiver_id=DCMXPXGX4QX6J&txn_type=web_accept&item_name=Account+top+up&mc_currency=USD&item_number=Account+262262+top+up&residence_country=US&test_ipn=1&handling_amount=0.00&transaction_subject=topup%3A262262%3A1%3A1433162020&payment_gross=1.00&shipping=0.00&auth=ANSTBwT3znll-gJQZO2cLoV5QJFW9v8W.FqyWxffdtI0L-9mfsoe2xRL44M86Sn2XtYGtcqG4Fjjel1kdYZyxpQ
Can anyone help me what I do wrong?
Thanks.
AARRRRGH!!!!!!!! I have only dirty words to PayPal!!!!!!! The problem was in... (drumroll... tadam!) in the charset field! No, its value must be the same as IPN sent it to you, but... in UPPERCASE! IPN sends it in lowercase! So you MUST modify IPN data to verify it successfully regardless manual tells us to return data back "as-is". PayPal bug?
So my final working code is: (using HTTP_Request2)
protected function verifyPostData() {
$this->request->setBody('cmd=_notify-validate&' . str_replace('=utf-8', '=UTF-8', file_get_contents('php://input')));
$response = $this->request->send();
if ($response->getStatus() != 200) {
throw new \RuntimeException("Transaction data verification request failed with code {$response->getStatus()}");
}
$content = trim($response->getBody());
return ($content == 'VERIFIED');
}
How I did it: I sent the PDT request for this transaction and obtained transaction data. Then I made field to field comparison of PDT and IPN data. PDT have no some IPN fields such as auth, verify_sign and test_ipn. But all other fields seems must be the same. And the only difference was in the characters case of the charset field. Then I tried to verify modified data and unexpectedly it become successful!
This is a recent PayPal bug, when the customer completes a payment and clicks on "Click here to return.." instead of waiting a few seconds, the parameters passed to the PDT script on your site are sent in lowercase.
This also messes up things like a case-sensitive or encoded cm/custom parameter.
Apparently PayPal are aware of it.

http post request not accepted by php

I am new to php and stackovrflow. So please pardon my initial mistakes.
I am sending post request through extjs4 app. as per Mozilla console Network tab, request is sent. PHP is 5.4.25. Below are the details:
POST /Opp/annt.php HTTP/1.1
Host: localhost
Connection: keep-alive
Content-Length: 83
Origin: http://localhost
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Accept: */*
Referer: http://localhost/opp/index.html?_dc=140
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Form Dataview parsed
aaa=i&bbb=i&ccc=&ddd=&eee=4&fff=5&ggg=&hhh=
PHP file:
header('Content-Type: application/json');
$method = $_SERVER["REQUEST_METHOD"];
$con = new PDO("mysql:host=localhost;dbname=openclass", "root", "") or die("cannot connect to mysql");
$fileContents = file_get_contents("php://input");
echo $fileContents;
json_decode($fileContents, true);
function getPostValue($postData, $fieldName) {
return (!empty($postData[$fieldName]) ? htmlspecialchars($postData[$fieldName]) : NULL);
}
I am not getting any data after post request is executed. Can you pls help in this in pointing out possible issue and solutions
I solved the issue. I was getting error because http post was sending form data in application/x-www-form-urlencoded; charset=UTF-8 formt.
I changed the format sent to json using AJAX requests. This changed the format sent across to json key value pairs.
This helped it read by php.

Javascript + PHP $_POST array empty

While trying to send a POST request via xmlhttp.open("POST", "url", true) (javascript) to the server I get an empty $_POST array.
Firebug shows that the data is being sent. Here is the data string from Firebug: a=1&q=151a45a150.... But $_POST['q'] returns nothing.
The interesting thing is that file_get_contents('php://input') does have my data (the string above), but PHP somehow doesn't recognize it. Tried both $_POST and $_REQUEST, nothing works.
Headers being sent:
POST /test.php HTTP/1.1
Host: website.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://website.com/
Content-Length: 156
Content-Type: text/plain; charset=UTF-8
Pragma: no-cache
Cache-Control: no-cache
Thank you for any suggestions.
It looks like you're missing the correct Content-Type header. This is necessary for POST requests:
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
Send a
Content-Type: application/x-www-form-urlencoded
header instead of text/plain
You have to write it like this:
xmlhttp.open("POST", "script.php", true);
xmlhttp.send("foo=bar&answer=42");
Just spent hours trying to find a fix for this very problem.
I made the idiotic mistake of concatenating several strings which I wanted to be the parameters, and THEN calling encodeURIComponent on the whole lot. This of course meant that
foo=bar&this=that
became
foo%3Dbar%26this%3Dthat
which of course is gibberish to a PHP script. While I doubt there can be many people who would do something as silly as this, I hope it saves someone the headache I just gave myself....

Categories