This question already has answers here:
How do I get PHP errors to display?
(27 answers)
Closed 11 days ago.
This post was edited and submitted for review 11 days ago and failed to reopen the post:
Original close reason(s) were not resolved
I have created simple apis using pure php, and uploaded the project to 000webhost, Get request is working good but when try to add data to database with POST request it returns Internal server error, even when the api works good in Postman.
after I added this, as Sir Eboo's answer:
`<?php
// see errors:
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);`
Internal server error disappeared but still not adding the data to the database !!!
I've tried to check all the questions about this problem but still can't find a solution.
is that maybe because 000webhost block my post request?
The function in flutter:
#override
Future<void> addStudent(String name, String grade, String note) async {
final url = Uri.parse(
"https://mystudentsrating.000webhostapp.com/crud/add_student.php");
final http.Response response = await http.post(url,
headers: {
'Content-Type': 'application/json;charset=UTF-8',
'Charset': 'utf-8',
"Accept": "application/json",
"contentType": "application/json"
},
body: jsonEncode(
<String, dynamic>{
'studentname': name,
'studentgrade': grade,
'studentnote': note
},
));
final result = utf8.decode(response.bodyBytes);
final message = jsonDecode(result);
if (response.statusCode != 200) throw Exception(message['status']);
}
}
The Add Student file:
<?php
include '../connection.php';
// see errors:
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
$studentName = filter_request('studentname');
$studentGrade = filter_request('studentgrade');
$studentNote = filter_request('studentnote');
// $studentstars = filter_request('studentstars');
$stmt = $con->prepare(
"INSERT INTO `students` (`student_name`, `student_grade`,`student_total_grades`, `student_note`, `student_stars`)
VALUES ( ?,?,?,?,?)");
$stmt->execute(array(
$studentName, $studentGrade,$studentGrade, $studentNote, 0
));
$count = $stmt->rowCount();
if ($count > 0)
echo json_encode(
array("status" => "Success"));
else echo json_encode(
array("status" => "Fail"));
hope you can help me..
first you can try to add for debug purpose :
`<?php
// see errors:
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);`
and maybe close your file with
"?> "
Related
So here is the deal : I have been working on a huge system (PHP) for a couple years, and now, I decided to give up part of heavy jobs for golang scripts.
So far, I replicated a few php scripts to a go version. Then, I am able to benchmark which option is better ( ok, I know go is faster, but I need curl or sockets to comunication, so, I have to check if it is still worth ) .
One of the scripts just generate a random code, check if this new code is already in use ( on mysql db ), if not, record the new code and return it, if is already in use, just recursive call the function again until find an exclusive code. pretty simple one.
I already had this code generator in php, so, wrote new one in go to be called as http/post with json params.
Using linux terminal, I call it as
curl -H [headers] -d [jsondata] [host]
and I get back a pretty simple json
{"locator" : "XXXXXX"}
After, I wrote a simple php script to call the scripts and check how long each took to complete, something like :
<?php
public function indexAction()
{
$phpTime = $endPHP = $startPHP =
$goTime = $endGO = $startGO = 0;
// my standard function already in use
ob_start();
$startPHP = microtime(true);
$MyCodeLocator = $this->container->get('MyCodeLocator')->Generate(22, 5);
$endPHP = microtime(true);
ob_end_clean();
sleep(1);
// Lets call using curl
$data = array("comon" => "22", "lenght" => "5");
$data_string = json_encode($data);
ob_start();
$startGO = microtime(true);
$ch = curl_init('http://localhost:8888/dev/fibootkt/MyCodeGenerator');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
curl_close($ch);
$endGO = microtime(true);
ob_end_clean();
$result_rr = json_decode($result);
// tst just echo the variable in a nice way, second parameter means no kill execution
tst($result, 1); // HERE IS MY PROBLEM, please read below
tst($result_rr, 1); // IT SHOW NULL
sleep(1);
// just to have params for comparision, always try by shell script
ob_start();
$startShell = microtime(true);;
$exec = "curl -H \"Content-Type: application/json\" -d '{\"comon\":\"22\"}' http://localhost:8888/dev/fibootkt/MyCodeGenerator";
$output = shell_exec($exec);
$endShell = microtime(true);
ob_end_clean();
tst(json_decode($output),1); // here show a stdclass with correct value
tst($output,1); // here shows a json typed string ready to be converted
// and here it is just for show the execution time ...
$phpTime = $endPHP - $startPHP;
$goTime = $endGO - $startGO ;
$shellTime = $endShell - $startShell;
tst("php " . $phpTime, 1);
tst("curl ". $goTime, 1);
tst("shell " . $shellTime, 1);
And I get the results from GO :
By Shell Script :
{"locator" : "DPEWX22"}
So, this one is pretty and easy decode to a stdobj.
But, using curl, the operation is faster ! So, I want to use it.
But, the curl request responds something like :
{"Value":"string","Type":{},"Offset":26,"Struct":"CodeLocatorParams","Field":"lenght"}
{"locator":"DPEWX22"}
And when I try to decode it, I get a null as result !!!
CodeLocatorParams the struct type I use in go to get the post params, as show below
so, here is my question : Why GO is returning this ? how to avoid it.
I have another similar go script which take no params and responds a similar json ( but in this case, a qrcode image path ) and it works fine !
My go function:
type CodeLocatorParams struct {
Comon string `json:"comon"`
Lenght int `json:"lenght"`
}
func Generate(w http.ResponseWriter, r *http.Request) {
data, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil {
fmt.Println(err)
panic(err)
}
if err := r.Body.Close(); err != nil {
panic(err)
}
// retrieve post data and set it to params which is CodeLocatorParams type
var params CodeLocatorParams
if err := json.Unmarshal(data, ¶ms ); err != nil {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(422) // unprocessable entity
if err := json.NewEncoder(w).Encode(err); err != nil {
fmt.Println(err)
panic(err)
}
}
var result struct{
Locator string `json:"locator"`
}
// here actually comes the func that generates random code and return it as string, but for now, just set it static
result.Locator = "DPEWX22"
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
json.NewEncoder(w).Encode(result)
}
There is an error parsing the incoming JSON. This error is written to the response as {"Value":"string","Type":{},"Offset":26,"Struct":"CodeLocatorParams","Field":"lenght"}. The handler continues to execute and writes the normal response {"locator":"DPEWX22"}.
Here's how what to fix:
After writing error response, return from the handler.
The input JSON has lenght as a string value. Either change the struct field from int to string or modify the input to pass an integer.
I'm working on an integration between Slack and Filemaker utilizing PHP. I am successful in having the code create a record in Filemaker based on the json request, and also have no trouble returning the challenge key to Slack.
However, I'm having trouble passing the header response 200 OK to Slack, while passing the challenge back. It looks like it has to be one or the other.
I've tried to move the HTTP header to different areas in the code, but haven't had any success so far.
Here is the current code:
<?php
$data = json_decode(file_get_contents('php://input'), true);
if (!isset($data["challenge"])) {
$body = $_SERVER['HTTP_X_SLACK_RETRY_REASON'];
require_once ('Filemaker.php');
//$body = file_get_contents('php://input');
$fm = new Filemaker();
$fm->setProperty('database', '');
$fm->setProperty('username', '');
$fm->setProperty('password', '');
$command = $fm->newPerformScriptCommand('PHP_RESPONSE', 'script', $body);
$result = $command->execute();
}
else {
header("Content-Type: text/plain");
header('X-PHP-Response-Code: 200', true, 200);
echo $data["challenge"];
}
?>
The result I expect is for the code to return the challenge code for Slack, while also returning an HTTP header of 200 OK.
Currently I can see I am receiving an error of "http_error" from Slack, which is what leads me to believe the problem is that the header is not being passed back successfully.
Any ideas on what is wrong, or suggestions on the right direction to proceed would be greatly appreciated.
The problem was occurring because for events slack doesn't send "challenge" as a parameter when sending events. It looks like echoing "challenge" is only needed when initially setting the URL for the events API.
I enclosed the challenge echo in a if statement that would only trigger if the challenge variable was present. After doing so the 200 OK was successfully passed.
Here is the code I used that solved the problem for me:
$data = json_decode(file_get_contents('php://input'), true);
if (isset($data["challenge"])) {
$message = [
"challenge" => $data["challenge"]
];
header('Content-Type: application/json');
echo json_encode($message);
}
The documentation is actually a bit inconsistent on this topic. It claims you can respond the challenge in plan text, but the example shows it as x-www-form-urlencoded.
To be on the safe side try returning the challenge as JSON. That works perfectly for me. You also do not need to explicitly set the HTTP 200 code.
Example code:
$message = [
"challenge" => $data["challenge"]
];
header('content-type: application/json');
echo json_encode($message);
This question is similar to another one answered, however the solution in that case was to use a country code, which is not feasible for this particular use, as the address is being provided by the user through an input field (so a country may not be provided).
Here is the content of my current request
Request coming from AngularJS:
function getCoordinatesFromApi(address) {
addressApiResponse = $http({
url: 'php/coordinates.php',
method: 'get',
params: {
address: address
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
return addressApiResponse;
}
Request handled in PHP:
$api_maps = 'https://maps.googleapis.com/maps/';
$address = urencode($_GET['address']);
$api_key = 'API_key_here';
$url = $api_maps . 'api/geocode/json?address=' . $address . '&key=' . $api_key;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$curl_response = curl_exec($curl);
curl_close($curl);
echo ($curl_response);
When this is called, I consistently get back a valid response with status: 200, but data is an empty string.
I've checked the validity of the $url being build in PHP and it is ok, accessing that url directly in the browser displays a valid API response with data.
I've also tried using Angular's $http method and that too returns a valid response from the API:
function getCoordinatesFromApi(address) {
addressApiResponse = $http.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + address + '&key=API_key_here');
return addressApiResponse;
}
For some reason, it's ony the curl method that does not behave as expected. Has any one dealt with this problem?
If you are saying that echo ($curl_response); return nothing even if status is 200, it's because it's encoded JSON!
Please try this :
$decodedresponse = json_decode($curl_response);
//send me what var_dump return so I can hellp you accessing the array!
echo var_dump($decodedresponse);
//You would use as an array DEPENDING ON HOW THE ARRAY IS BUILD OF COURSE
echo $decodedresponse['response']['lat'];
echo $decodedresponse['response']['long'];
try again
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false
This question already has answers here:
How to post data in PHP using file_get_contents?
(3 answers)
Closed 8 years ago.
I have 2 files on a web server in the same directory: post.php and receive.php
The post.php file posts a username and password. The receive.php receives the username and password, and prints them out.
The receive.php file looks like this:
<?php
$user=$_POST["user"];
$password=$_POST["password"];
echo("The Username is : ".$user."<br>");
echo("The Password is : ".$password."<br>");
?>
I have this code for the post.php:
<?php
$r = new HttpRequest('http://localhost/receive.php', HttpRequest::METH_POST);
$r->addPostFields(array('user' => 'mike', 'password' => '1234'));
try {
echo $r->send()->getBody();
} catch (HttpException $ex) {
echo $ex;
}
?>
I tried various different ways of coding the post.php file, but none of them worked. I also tried following some tutorials online, but that didn't work either. I'm a PHP noob, please help!!
The following code for post.php worked for me. I'm not 100% sure what it does, but it works.
<?php
$params = array ('user' => 'Mike', 'password' => '1234');
$query = http_build_query ($params);
// Create Http context details
$contextData = array (
'method' => 'POST',
'header' => "Connection: close\r\n".
"Content-Length: ".strlen($query)."\r\n",
'content'=> $query );
// Create context resource for our request
$context = stream_context_create (array ( 'http' => $contextData ));
// Read page rendered as result of your POST request
$result = file_get_contents (
'http://localhost/receive.php', // page url
false,
$context);
// Server response is now stored in $result variable so you can process it
echo($result);
?>
Sending HTTP request with PHP is possible but not trivial. Have a look at cURL, or better yet - a library like Artax.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Parse Json in php
Im using an API to CURL a submitted user image to a remote server, the response is in JSON and I'm not sure how to parse it.
Here is my php CURL file
<?php
$api_key = 'xxxxxx';
$api_secret = 'xxxxx';
$Dirty_uid = $_GET['uid'];
$uid = htmlentities($Dirty_uid);
$Dirty_img = $_GET['img'];
$img = htmlentities($Dirty_img);
$query2 = 'http://rekognition.com/func/api/?api_key='.$api_key.'&api_secret='.$api_secret.'&jobs=face_recognize&urls='.$img.'&name_space=xxx&user_id=xxx';
$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch2, CURLOPT_URL, $query2); // get the url contents
$data2 = curl_exec($ch2); // execute curl request
curl_close($ch2);
$json2 = json_decode($data2);
print_r($json2)
?>
and here is a sample of the JSON data that comes back (Generic)
Code:
{
url: "http://farm3.static.flickr.com/2566/3896283279_0209be7a67.jpg",
face_detection: [
{
boundingbox:
{
tl: {
x: 50,
y: 118
},
size:{
width:232;
height:232;
}
}
name: "mona_lisa:0.92,barack_obama:0.02,mark_zuckerberg:0.01,"
}
]
usage: {
status: "success",
quota: 999,
api_id: "xxx"
}
}
Where the json string says "name" I need my script to only print the username if the number (after the : is higher then a threshold (lets say .70 for now).
How do I do this? I've worked with XML api's before and returning the data was simple with a
Code:
$xml = simplexml_load_string($data);
type thing.
You already have most of it. You have json_decodeed the result. Now you just need to access the data like
$name = $json2->face_detection[0]->name