php does not recognize JSON post message - php

Im struggling with sending JSON data via XMLhttp post request.
Data is:
"{"reqData":{"reqType":"post","reqName":"getCurrTemp","reqPayload":""}}"
JS code is:
var reqData = {
reqType : "post", //isDateRequested : 1,
reqName : "getCurrTemp",
reqPayload : ""
};
var dataToSend = {'reqData' : reqData };
var jData = JSON.stringify(dataToSend);
alert(jData);
var oReq = new XMLHttpRequest();
oReq.onload = function() {
data = JSON.parse(this.responseText);
};
oReq.open("POST", "handleRequests.php", true);
oReq.send(jData);
Im having problem on php side, looks like server does not recognize JSON, or even message lost...
I used wireshark to sniff traffic:
POST /autHouse/handleRequests.php HTTP/1.1
Host: 192.168.0.12
Connection: keep-alive
Content-Length: 70
Origin: http://192.168.0.12
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36
Content-Type: text/plain;charset=UTF-8
Accept: */*
Referer: http://192.168.0.12/autHouse/ah.html
Accept-Encoding: gzip, deflate
Accept-Language: pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4
{"reqData":{"reqType":"post","reqName":"getCurrTemp","reqPayload":""}}HTTP/1.1 200 OK
Date: Tue, 19 Jan 2016 10:53:22 GMT
Server: Apache/2.2.22 (Debian)
X-Powered-By: PHP/5.4.45-0+deb7u2
Content-Length: 84
Keep-Alive: timeout=5, max=99
Connection: Keep-Alive
Content-Type: text/html
string(70) "{"reqData":{"reqType":"post","reqName":"getCurrTemp","reqPayload":""}}"
here is php code:
$body = file_get_contents('php://input');
error_log(var_dump($body));
$reqData= json_decode($_POST['reqData'], true);
$reqType = $reqData["reqType"];
$reqName = $reqData["reqName"];
and realted php error log:
[Tue Jan 19 11:54:23 2016] [error] [client 192.168.0.121] , referer: http://192.168.0.12/autHouse/ah.html
[Tue Jan 19 11:54:23 2016] [error] [client 192.168.0.121] PHP Notice: Undefined index: reqData in /var/www/autHouse/handleRequests.php on line 15, referer: http://192.168.0.12/autHouse/ah.html
Can you please tell me why php complians while im sending proper JSON data?
regards
J.

Try this
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "handleRequests.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(jData);

You have missed a level in the resulting array.
$body = file_get_contents('php://input');
error_log(var_dump($body));
$reqData= json_decode($_POST['reqData'], true);
$reqType = $reqData['reqData']["reqType"];
$reqName = $reqData['reqData']["reqName"];
If you prefer using the objects that the data is being passed as rather than converting the objects to arrays you can do
$body = file_get_contents('php://input');
error_log(var_dump($body));
$reqData= json_decode($_POST['reqData']);
$reqType = $reqData->reqData->reqType;
$reqName = $reqData->reqData->reqName;

Related

Is it possible to get ALL response headers from from Apache using PHP?

I get the request headers from the browser like this.
<?php
$DataFromBrowser='';
$DataToBrowser='';
$headers = getallheaders();
foreach($headers as $key=>$val){
$DataFromBrowser = $DataFromBrowser . $key . ': ' . $val . "\n";
}
//echo get_raw_http_request();
echo "Data from browser";
echo '<textarea rows="12" style="width:100%;">' . $DataFromBrowser . '</textarea>';
?>
And the output will look like this.
Host: 127.0.0.1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:101.0) Gecko/20100101 Firefox/101.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,/;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Cookie: foo=bar
Upgrade-Insecure-Requests: 1
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: none
Sec-Fetch-User: ?1
Now I want to do exactly the same but for the response headers from the server. I'm aware I can do the following but it will create another connection I need the response headers of the current served page.
<?php
$URL = 'https://www.google.com';
$headers = get_headers($URL);
foreach($headers as $value) {
echo $value;
echo "<br>";
}
?>
If I change the above to http://127.0.0.1 It get's it self in a deadlock and will loop until it bombs out.
The response headers should look like this.
HTTP/1.1 200 OK
Date: Wed, 08 Jun 2022 16:53:45 GMT
Server: Apache/2.4.46 (Win64) OpenSSL/1.1.1j PHP/8.0.3
X-Powered-By: PHP/8.0.3
Content-Length: 589
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8

PHP get some parts from shell_exec

I need your help guys i have some php code running on my server:
<?php
if ($_GET['id'])
$id = $_GET['id'];
$json = file_get_contents('http://www.youtubeinmp3.com/fetch/?format=JSON&video=http://www.youtube.com/watch?v=' . $id);
$data = json_decode($json, true);
$stream = $data['link'];
$url = $stream;
$output = shell_exec ('curl -I -L ' . $url);
echo "<pre>$output</pre>";
?>
and it outputs this when i go to:http://146.185.137.252/new.php?id=HgzGwKwLmgM
it outputs this:
HTTP/1.1 302 Moved Temporarily
Date: Sat, 11 Feb 2017 01:25:56 GMT
Content-Type: text/html
Connection: keep-alive
Set-Cookie: __cfduid=db002cf41b2472eb20de42ec65b16029a1486776356; expires=Sun, 11-Feb-18 01:25:56 GMT; path=/; domain=.youtubeinmp3.com; HttpOnly
X-Powered-By: PHP/5.5.38
Location: //w23.youtubeinmp3.com/download/get/?id=HgzGwKwLmgM&r=kT7YFcbHgX3m25ULP3GeWulVx9OmT2qd&t=Queen+-+Don%27t+Stop+Me+Now+%28Official+Video%29
Server: cloudflare-nginx
CF-RAY: 32f40283e57d148b-AMS
HTTP/1.1 200 OK
Server: nginx
Date: Sat, 11 Feb 2017 01:25:56 GMT
Content-Type: audio/mpeg
Content-Length: 3499136
Last-Modified: Fri, 18 Nov 2016 18:09:22 GMT
Connection: keep-alive
Content-Disposition: attachment; filename="Queen - Don't Stop Me Now (Official Video).mp3"
Accept-Ranges: bytes
Expires: 0
ETag: "582f43d2-356480"
Accept-Ranges: bytes
but i don't need al that stuff i only need to two things:
the (Location:) and the (Content-Disposition: attachment; filename=)
in two different variables so in this case i need:
//w23.youtubeinmp3.com/download/get/?id=HgzGwKwLmgM&r=kT7YFcbHgX3m25ULP3GeWulVx9OmT2qd&t=Queen+-+Don%27t+Stop+Me+Now+%28Official+Video%29
and
Queen - Don't Stop Me Now (Official Video) (i dont want the .mp3 btw)
i've searched the web everywhere but to be honest i'm a total noob at this
so if anyone can help me out that would be amazing
This code is tested. Response was copied from my Browser.
I just used curl to do the curl request and used curl_getinfo($ch,CURLINFO_REDIRECT_URL) to get the redirect link.
I also added getting the header which you do not need unless there are issues and you'd like to see the response header.
PHP
<?php
header('content-type: text/plain');
$id='HgzGwKwLmgM';
$json = file_get_contents('http://www.youtubeinmp3.com/fetch/?format=JSON&video=http://www.youtube.com/watch?v=' . $id);
$json = json_decode($json, true);
$url = $json['link'];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
$header = curl_exec($ch);
$link = curl_getinfo($ch,CURLINFO_REDIRECT_URL);
echo "\nLINK: $link\n\nHEADER: $header";
?>
RESPONSE:
LINK: http://w23.youtubeinmp3.com/download/get/?id=HgzGwKwLmgM&r=aRDQ1MGdfkY3Mm6EFxQqEVqgd9FHf81q&t=Queen+-+Don%27t+Stop+Me+Now+%28Official+Video%29
HEADER: HTTP/1.1 302 Moved Temporarily
Date: Sun, 12 Feb 2017 16:23:39 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
Set-Cookie: __cfduid=d27df4bad722b0449b88b37d4b9d9b7341486916619; expires=Mon, 12-Feb-18 16:23:39 GMT; path=/; domain=.youtubeinmp3.com; HttpOnly
X-Powered-By: PHP/5.5.38
Location: //w23.youtubeinmp3.com/download/get/?id=HgzGwKwLmgM&r=aRDQ1MGdfkY3Mm6EFxQqEVqgd9FHf81q&t=Queen+-+Don%27t+Stop+Me+Now+%28Official+Video%29
Server: cloudflare-nginx
CF-RAY: 330162e8b07e115f-DFW
If you only want the filename and the the title as you wrote on your question.
you can simply use them like this
$link = $data['link'];
$title = $data['title'];
once you have that, you can print it or make a link with it like this
echo "<a href=$link>$title</a>";
Unless you want to save the file, you don't need the curl (and the shell_Exec) part
it would look something like this:
<?php
if (isset($_GET['id'])) {
$id = $_GET['id'];
$json = file_get_contents('http://www.youtubeinmp3.com/fetch/?format=JSON&video=http://www.youtube.com/watch?v=' . $id);
$data = json_decode($json, true);
$link = $data['link'];
$title = $data['title'];
echo "<a href=$link>$title</a>";
}
?>

PHP Built in web server and Range Requests with Safari

I am working on this prototype and i have used the php built in web server, and all works perfect except handling a range request from Safari for a mp4 file. i have the following bootstrap code that gets executed for every incoming request for the php built in server
$extensions = array("html");
$path = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
$ext = pathinfo($path, PATHINFO_EXTENSION);
if (!in_array($ext, $extensions)) {
return isRangeRequest();
}
require_once(__DIR__ . $path);
function isRangeRequest()
{
$filelength = filesize(__DIR__ . '/video/video.mp4');
if (isset($_SERVER['HTTP_RANGE'])) {
$ranges = explode(',', substr($_SERVER['HTTP_RANGE'], 6));
$parts = explode('-', $ranges[0]);
$start = $parts[0]; // If this is empty, this should be 0.
$end = $parts[1]; // If this is empty or greater than than filelength - 1, this should be filelength - 1.
if (intval($end) == 0) return false;
$readBytes = $end - $start + 1;
header('HTTP/1.1 206 Partial Content');
header("Content-Length: " . $readBytes);
header('Content-Type: video/mp4');
header('Content-Range: bytes '.$start.'-'.$end.'/'.$filelength);
ini_set('memory_limit', "512M");
$fp = fopen(__DIR__ . '/video/video.mp4', 'rb');
if ($readBytes < 4096) {
print(fread($fp, $readBytes));
flush();
} else {
fpassthru($fp);
}
fclose($fp);
exit;
}
return false;
}
i have verified using tcpdump that the code above sends all the correct headers and i manage to get safari to start playing the video. however safari only is able to play the first few frames and then video stops.
here is response headers from a nginx server for the same request from safari
GET /video/video.mp4 HTTP/1.1
Host: job.local
Accept-Language: en-us
X-Playback-Session-Id: CD33782F-F257-4506-95C4-94ABD4E200CE
Cookie: PHPSESSID2=avrunqgk9rkb3941fe24q9asd6
Range: bytes=0-1
Accept: */*
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/601.4.4 (KHTML, like Gecko) Version/9.0.3 Safari/601.4.4
Referer: http://job.local/test.html
Accept-Encoding: identity
Connection: keep-alive

HTTP/1.1 206 Partial Content
Server: nginx/1.6.2 (Ubuntu)
Date: Fri, 27 May 2016 03:29:16 GMT
Content-Type: video/mp4
Content-Length: 2
Last-Modified: Thu, 26 May 2016 17:53:49 GMT
Connection: keep-alive
ETag: "5747382d-8c6c509"
Expires: Thu, 31 Dec 2037 23:55:55 GMT
Cache-Control: max-age=315360000
Content-Range: bytes 0-1/147244297

GET /video/video.mp4 HTTP/1.1
Host: job.local
Accept-Language: en-us
X-Playback-Session-Id: CD33782F-F257-4506-95C4-94ABD4E200CE
Cookie: PHPSESSID2=avrunqgk9rkb3941fe24q9asd6
Range: bytes=0-147244296
Accept: */*
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/601.4.4 (KHTML, like Gecko) Version/9.0.3 Safari/601.4.4
Referer: http://job.local/test.html
Accept-Encoding: identity
Connection: keep-alive

HTTP/1.1 206 Partial Content
Server: nginx/1.6.2 (Ubuntu)
Date: Fri, 27 May 2016 03:29:16 GMT
Content-Type: video/mp4
Content-Length: 147244297
Last-Modified: Thu, 26 May 2016 17:53:49 GMT
Connection: keep-alive
ETag: "5747382d-8c6c509"
Expires: Thu, 31 Dec 2037 23:55:55 GMT
Cache-Control: max-age=315360000
Content-Range: bytes 0-147244296/147244297
and here is the headers from the php built in server using the bootstrap code above
GET /video/video.mp4 HTTP/1.1
Host: localhost:8005
Accept-Language: en-us
X-Playback-Session-Id: 740A36CB-C116-4F5E-A3BD-5B4B3A27B543
Range: bytes=0-1
Accept: */*
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/601.4.4 (KHTML, like Gecko) Version/9.0.3 Safari/601.4.4
Referer: http://localhost:8005/index.html
Accept-Encoding: identity
Connection: keep-alive
HTTP/1.1 206 Partial Content
Host: localhost:8005
Connection: close
X-Powered-By: PHP/5.5.30
Content-Length: 2
Content-Type: video/mp4
Content-Range: bytes 0-1/147244297
GET /video/video.mp4 HTTP/1.1
Host: localhost:8005
Accept-Language: en-us
X-Playback-Session-Id: 740A36CB-C116-4F5E-A3BD-5B4B3A27B543
Range: bytes=0-147244296
Accept: */*
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/601.4.4 (KHTML, like Gecko) Version/9.0.3 Safari/601.4.4
Referer: http://localhost:8005/index.html
Accept-Encoding: identity
Connection: keep-alive
HTTP/1.1 206 Partial Content
Host: localhost:8005
Connection: close
X-Powered-By: PHP/5.5.30
Content-Length: 147244297
Content-Type: video/mp4
Content-Range: bytes 0-147244296/147244297
apart from Connection: keep-alive not being supported by the built-in php server i don't see any other difference in the response. Do you see any potential issues here? The mp4 files is about 100MB and if i use a data-url instead of a file reference would that be ok?
This project is for a prototype that used only on a local machine, so there is no performance or security concerns and please avoid making such comments. the core concern is the reason why safari only plays the first few frames. (i also observed if the range request is not handled correctly safari will not even play the first few frames. So there is some other issue that maybe not so obvious.

Angularjs Post Php, issues with reading $_Post data after reading some solutions

The problem is that angularjs sends post data as json. There are several solutions:
Serverside:
Angularjs - Form Post Data Not Posted?
Clientside:
http://sebgoo.blogspot.de/2013/05/angularjs-post-data-to-php.html
More fancy one?:
http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/
I want to use the server side one:
PHP file:
<?php
$data = file_get_contents("php://input");
$errors['EncodeI']=$data->customerFirstName;
$data = json_decode($data, TRUE);
$errors['EncodeII']=$data['customerFirstName'];
echo return_sql2json($errors, $rows);//just a function which returns the error messages
?>
Js:
...
$http({
url: 'read.php',
method: "POST",
// headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
params: {
customerFirstName: $scope.customerFirstName,
customerLastName: $scope.customerLastName,
customerEmail: $scope.customerEmail
}
}).success(function(data) {
....
My Header: The data customerFirstName is sent
Remote Address:::1:80
Request URL:http://localhost/360/app/read.php?customerEmail=aa&customerFirstName=aa&customerLastName=aa
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
Cache-Control:no-cache
Connection:keep-alive
Content-Length:0
Cookie:AccessKey=somePW; Email=someemail; PHPSESSID=somesession
Host:localhost
Origin:http://localhost
Pragma:no-cache
Referer:http://localhost/360/app/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36
Query String Parametersview sourceview URL encoded
customerEmail:aa
customerFirstName:aa
customerLastName:aa
Response Headersview source
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:Keep-Alive
Content-Length:310
Content-Type:text/html
Date:Wed, 07 May 2014 11:21:46 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive:timeout=5, max=96
Pragma:no-cache
Server:Apache/2.4.9 (Win32) OpenSSL/0.9.8y PHP/5.4.27
X-Powered-By:PHP/5.4.27
And the Response:
errors: {EncodeI:null, EncodeII:null, customerFirstName:First Name is required,…}
EncodeI: null
EncodeII: null
customerEmail: "Email is required"
customerFirstName: "First Name is required"
customerLastName: "Last Name is required"
success: false
Conclusion: Not working. Also the server side solutions I didn't manage to be successful but they anyways look more complicated for me.
The answer is rename params into data.

jQuery AJAX response error (FF and Safari not working)

In Safari and Firefox, the response part of the code is not working (i.e. from PHP-->Ajax-->jQuery). The variables definitely make it to the PHP fine (tested using mail() ), so it's probably some small error on my behalf!
jQuery:
$.ajax({
type: "POST",
dataType: "json",
data: postData,
url: "http://www.kudiclub.com/test/login/?loginsub",
success: function(data){
if(data.success==false){
$("#login .error").html(data.reply).show();
$("#login-email").val(data.email);
$("#password").val("");
}else{
window.location = data.ref;
}
}
});
PHP:
$data = array('success' => false, 'reply' => 'Username and password did not match.', 'email' => $email);
print json_encode($data);
return;
Hoping somebody can help. Thanks, Nick.
SOLUTION
After much fiddling about, it turns out that it doesn't see a full URL as a relative path. Changing the url to '/test/login/?loginsub' did the trick.
The server says: Content-Type: text/html. Is not a json document (application/json).
http://www.kudiclub.com/test/login/?loginsub
GET /test/login/?loginsub HTTP/1.1
Host: www.kudiclub.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:13.0) Gecko/20100101 Firefox/13.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: es-es,es;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
DNT: 1
Connection: keep-alive
Cookie: PHPSESSID=060b8210adfb3c67ff792b9471c7fa1c
Cache-Control: max-age=0
HTTP/1.1 200 OK
Date: Thu, 02 Aug 2012 22:12:10 GMT
Server: Apache
X-Powered-By: PHP/5.2.17
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Keep-Alive: timeout=2, max=200
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html

Categories