Get custom request header - php

Im running PHP version 5.5 on WAMP. I have a very simple API. I want to get the custom request header called "api_key". First of all, I made the GET request and logged the headers like this:
foreach (getallheaders() as $name => $value) {
$message .= "$name: $value\n";
}
file_put_contents('headers.log', $message);
This resulted in:
Host: localhost
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json, text/javascript, */*; q=0.01
device_id: 63843
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36
api_key: hv7Vgd4jsbb
Referer: http://localhost/server/cli/beaufort/www/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Cookie: PHPSESSID=bd3c8ce878ebc504b2128686efbe30cf;
bd3c8ce878ebc504b2128686efbe30cf=DEFAULT%7C0%7C2M3TMlgUx3gTlaarYzHIdD28l8q9FTcNubt55%2BUGpAo%3D%7C7456bf61db3500c8bb7b3bc38082a470ce4a2ad3
So "api_key" is there. However, somehow, when I do:
$message = $_SERVER['HTTP_API_KEY'];
I get the error:
Fatal error: Uncaught exception 'ErrorException' with message 'Undefined index: HTTP_API_KEY'
Why can I not get this header??

$headers = getallheaders();
$message = $headers['api_key'];

Related

how to check if i am having correct file at laravel controller from post request

trying to upload an image at laravel: On echo $request; i am getting this: POST /infoshore0/api/public/v1/product/addProductImg?lang=en-us HTTP/1.1 Accept: application/json, text/plain, */* Accept-Encoding: gzip, deflate, br Accept-Language: en-IN,en-GB;q=0.9,en-US;q=0.8,en;q=0.7 Authorization: Bearer eyJ0eXAiOiJKV1QiLNjc0MTcsIm5iZiI6MTYwMjI2MzgxNywianRpIjoiZmxhdHJ1Mk5BeGdLc0JWRCJ9.lFcZOOSZx_94eZY97L-OfR36XLX_KLqvbZFJo5l2FW8 Connection: keep-alive Content-Length: 209141 Content-Type: text/plain;charset=UTF-8 Cookie: laravel_session=7dab0a4fdba93fbec911f Host: localhost:8080 Origin: http://localhost:8080 Referer: http://localhost:8080/cp/ Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: same-origin User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36 {"file":"ÿØÿà\u0000\u00.......very long text","product_id":499859489}
I have tried if ($request->hasFile('file')) { echo 'File Found'; } and nithing is happeningAlso Passing product_id and image file using angularJS

Can't get data from AJAX response in PHP

I just started programming but I don't know how to get this POST response into a PHP file,
Request URL: http://localhost/getEmployees.php
Request Method: POST
Status Code: 200 OK
Remote Address: 127.0.0.1:63342
Referrer Policy: no-referrer-when-downgrade
access-control-allow-credentials: true
access-control-allow-origin: http://localhost:63342
content-length: 4850
Content-type: text/html; charset=UTF-8
server: PhpStorm 2020.1
vary: origin
X-Powered-By: PHP/7.3.6
Accept: application/json, text/javascript, */*; q=0.01
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,es-US;q=0.8,es;q=0.7,sm;q=0.6
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 105
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Cookie: Phpstorm-7e92279c=4f7ff7c6-1a41-4c9e-90dd-dcc6680dcb42; loginAuthorised=loginAuthorised; companyId=1; userId=10; userName=Claudia+Najera; PHPSESSID=nequ49622cdstv6oh0ahsmis10
Host: localhost:63342
Origin: http://localhost:63342
Pragma: no-cache
Referer: http://localhost:63342/htdocs/flavorite.io/tools/tests.php?_ijt=buaa7pmm8icavombffnis1htfu
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-origin
User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Mobile Safari/537.36
X-Requested-With: XMLHttpRequest
query[generalSearch]: Mario
selectedAllRows: false
requestIds: true
sort[field]:
sort[sort]: asc
What I am trying to do is get query[generalSearch] string. I have in another PHP file to fet the results:
$dbConnection = connection();
$generalSearchJSON = #$_POST['generalSearch'];
$generalSearch = json_decode($generalSearchJSON);
I want to use the $generalSearch variable to search the database. But it doesn't seem to get the result. Any suggestions?
You have a typo.Remove the # from $_POST['generalSearch'];
So you'll get this:
$dbConnection = connection();
$generalSearchJSON = $_POST['generalSearch'];
$generalSearch = json_decode($generalSearchJSON);

How to extract Host (domain) form apache_request_headers();

How to extract the domain (host value) from the apache_request_headers(); output?
the original code:
$headers = apache_request_headers();
foreach ($headers as $header => $value) {
echo "$header: $value <br />\n";
}
the result:
Host: yatko.net
Connection: keep-alive
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
the desired output would be
yatko.net
I am having a strange issue with a mail form (http://goo.gl/Wr4sfC) and seems that apache_request_headers(); would work; however, I need to extract it from the generated array. Thank you!
You've answered your own question.
echo $headers['Host'];
// yatko.net

file_get_contents() with modified HTTP headers returning garbage html output

The following code is being used to extract html using SIMPLETHTMLDOM parser for php.
include('simple_html_dom.php');
$context = stream_context_create(array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept: text/html,application/xhtml+xml,application/xml\r\n" .
"Accept-Charset: ISO-8859-1,utf-8\r\n" .
"Accept-Encoding: gzip,deflate,sdch\r\n" .
"Accept-Language: en-US,en;q=0.8\r\n",
'user_agent'=>"User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.66 Safari/535.11\r\n"
)
));
$html = file_get_contents('http://www.nseindia.com/content/equities/cmbhav.htm', false, $context);
echo $html;
foreach($html->find('a') as $e)
echo $e->href . '<br>';
The output generated is Garbage html :
‹µVßsâ6~Ï_¡s§¹ð2¹^:ìNˆÝ†)!ið=äéFØV"K>I˜pMÿ÷®lCšéÝKy#+í­¾ý´òè]t}‘ÜÝÄä2¹š’›Oãéä‚x]J'qò¥Q5š=ŸÒxæ…G£Ü À2,·ÂÙ<&]YsËÁ 8eŒ%ãœU©*·#Úئ“Ù$×°<* ôRc<¢AóänÏ/ã8!v[B`áÑRÔâ&Õ¼´D0¹Z³Þ=«X³è£SuohªŠBÉåZ¦¦wo¼pD“o*¦ 7“88ÉTº.#Ú¢ókà[ålþÓ­`[ÐæÀà,8yö_¸Pãí$ëŸHVñ³J÷XYÎXAð~Ö¤¬„÷ƒXŠÜ³óôTg/ "Wª×'ñÓSmÖgm‡€åJ’œÉL#¬µÒ'ò—»Ö’X½†áßdÃe¦6=%ÁéIðÒzH0«¸ÂìÍIgxô#>W¾|°´xäÃBЖ5ãëèŽ,V©JÞËúççU0½â2ð‰Uå^n„ø*·¨j¦žÙ<𱾯ˆt˜zùº.GxöjjìV AÅ _pÁívó,9$¥2H[%la”X[":zÐ/‡¤Ù´‘¿v5xô‡uªnÄ,}G6Ì3IÎÇÓ˜¤ „)YÊå ³](FÁ-—,Ëšåö4}ßÿ­Æ¿wÝî! 3V‘1²rn™¶†\‚†nõÿu£æœ?ºÔí0p,³aQ{¡¤Åz“s ì_ÛÚ¬$8ó}R1ÁW2Àsï{O§7çQ4™ýŽ§t³ùÍùE3_ßFñ-.7ÕúøËi‹h°?øná£+%î…¬#ðdðáÅ^$̘Àx3—&±¶ä˜‰ÃŸ¡óB‡ÇraÊaó&m§ÉU%¶Ž6//¼Ä™s Ç+;$;+l 5Ú6†Âg.­VÙº¾PÎ9Üõ¸ïô/,—U»^1ý–Lp®æ·²ËÁ{3 ¤;:Z•±ms€6RâVÈ>ÈaÓ­ñp˜à ¶BTs,¹uu‹Úzôý±M¢FñªÀKĤÅÞ]]ÐáAgÇíMèöiö*[ûN×Ç]±ÚJì#ιÁfÈS&hüç§I2‰çôÔïŸÒ«ó[šþÏ8ºù_|$ªÞW^zï¶Ö#Â&ŒÔF Å2²ä—Hƒ¬CdD?ÿ‡\²ÅòÛ¹ ÑA.Ïø¤xÏ#¿Iè£7)à`pi¢¬Ét‰ÖÐæÄæ°gk0jB<=óšé4çºês>¿Ð.]¤Âhš ­›\jvìÒ¦æ”S8>Ѻï9‰V÷±W åu»ixH-[à—º¸ÇÀ͇Å?§m2“
Where am i doing Wrong !! I checked the headers info from fiddler. These are the actual header information when the link is opened with browser !!
[Client]
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.66 Safari/535.11
[Transport]
Host: www.nseindia.com
Proxy-Connection: keep-alive
In the HTTP request you are explicitly declaring that you can handle compressed data, so that is what the server is returning:
Accept-Encoding: gzip,deflate,sdch\r\n
You must now decode that compressed data:
$html = gzuncompress($html);
As piotrekkr mentions in a comment, you can alternatively remove the Accept-Encoding header and the web server should return plain text instead.

Content not being Posted properly?

I am using simpleTest WebBrowser for DataScraping on this URL http://www.magicbricks.com/bricks/agentSearch.html. But though everything seems right I always get the error City Field is required. I guess the problem might be with the fact that values in city field changes dynamically when value of State changes. Any solutions? Here is my code.
<?php
require_once('simpletest/browser.php');
$browser = &new SimpleBrowser();
$browser->addHeader('User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0.2) Gecko/20100101 Firefox/6.0.2');
$browser->get('http://www.magicbricks.com/bricks/agentSearch.html');
$browser->setField('source','agentSearch');
$browser->setField('_transactionType','1');
$browser->setField('_propertyType','1');
$browser->setField('resultPerPage','50');
$browser->setField('agentSearchType','B');
$browser->setField('state','520');
$browser->setField('city','4320');
$browser->setField('keyword','');
$browser->setField('country','50');
print $browser->submitFormById('searchFormBean');
print $browser->getResponseCode()
?>
Here are some errors i noticed
Field Missing
Missing agentSearchType field
Missing transactionType ( There is Both transactionType & _transactionType)
missing propertyType ( There is both propertyType & _propertyType)
There are some header information you need to add such as
Referer
Cookie
A typical post test should come this format if you view the headers
POST http://www.magicbricks.com/bricks/agentSearch.html HTTP/1.1
Host: www.magicbricks.com
Connection: keep-alive
Content-Length: 173
Cache-Control: max-age=0
Origin: http://www.magicbricks.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.79 Safari/535.11
Content-Type: application/x-www-form-urlencoded
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Referer: http://www.magicbricks.com/bricks/agentSearch.html
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
Cookie: JSESSIONID=nF1UqV3DM2tZC42zByYm6Q**.MBAPP09; __utma=163479907.1423216630.1331970312.1331970312.1331970312.1; __utmb=163479907.1.10.1331970312; __utmc=163479907; __utmz=163479907.1331970312.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); _mbRunstats=3k0ilrpcgprh4tea
source=agentSearch&agentSearchType=B&country=51&state=601&city=8417&transactionType=11951&_transactionType=1&propertyType=10001&_propertyType=1&keyword=tesy&resultPerPage=50
I hope this helps
:D

Categories