Send notification response by php

Asked

Viewed 847 times

-4

I need to send an http 200 response with the 'SUCCESS' string, but my php version of the server is 5.2.17!

In my case, the webhook sends data to the capture to a file called.php notification, I read the content, write to the database and need to send a reply, but I don’t know how to do it!

Does anyone know how to do this in php 5.2.17?

I have tried the following ways without success:

// erro 1
header("Content-Type: text/plain");
echo "SUCCESS";

// erro 2
$httpStatusCode = 200;
$httpStatusMsg  = 'SUCCESS';
$protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0';
header($protocol.' '.$httpStatusCode.' '.$httpStatusMsg);

// erro 3
header("200 SUCCESS");
return "200 SUCCESS";

// erro 4
header('Content-Type: application/json');
echo 'SUCCESS';
////

// erro 5
header('Content-Type: application/json');
return 'SUCCESS';   
////

//erro 6
header('Content-Type: application/json');
header('SUCCESS');

///erro 7
header('Content-Type: application/json');
$success =json_encode('SUCCESS');
header($success);   

///erro 8
header("HTTP/1.1 200 SUCCESS");
header("Content-Type:application/json; charset=utf-8");

///erro 9
header("HTTP/1.1 200");
header("Content-Type:application/json; charset=utf-8");
result 'SUCCESS';

//erro 10
header("Content-Type:application/json;");
header('HTTP/1.0 200 SUCCESS');

//erro 11
header("Content-Type: text/plain");
echo "SUCCESS";
  • 3

    The problem is that you don’t seem to understand the difference between header and body within the HTTP structure and don’t understand the difference between JSON and other formats

  • Okay, William I don’t really know much about html. So, please, you teach me to make in php a simple response to a json request that works?

  • 3

    If you have time on Monday I’ll explain what json, html and http is

  • Are you "serto", do not know the answer and still want to humiliate others? Unfortunate!!!! If you knew the answer would post here....

  • 5

    Friend you are mistaken and your attitude is totally disrespectful, I suggest you try to behave or I will have to report the situation, ok I am in the middle of a job trying to finish to enjoy the little time I have on the weekend but I will answer. Now to return to this type of situation unfortunately I will have to report. Understand? Wait I am providing an answer to your doubt. Meanwhile READ: http://answall.com/help/be-nice if you don’t actually read it pitiful!

  • 1

    @prmas avoids quick judgments. We are all here to share solutions and knowledge about programming. You ended up getting a very good answer from Guilherme.

Show 1 more comment

2 answers

8

The problem is that you don’t understand the difference between JSON and HTML or TEXT, this is the least you have to study before trying to use these formats.

That echo "SUCCESS"; prints this in the reply to the request SUCCESS, this is not JSON, JSON has a format like:

{ "response": "SUCCESS" }

And the header (header) should be UTF-8 (of course you can use other charset types, but the default is UTF-8 for this case) when using json, so PHP should look like this:

<?php
header('Content-Type: application/json; charset=UTF-8');
echo json_encode(array( 'response' => 'SUCCESS' ));

The function json_encode does not magically transform strings into JSON, it just converts strings into an accepted format within JSON values, i.e.:

  • Quotes (") in \"
  • And accents like ã in \u00e3

Now using an array as I did in the example will work.

For their uses of header as header("200 SUCCESS"); also note that you do not understand or still do not understand well how HTTP works.

HTTP stands for Hypertext Transfer Protocol which means "Hypertext Transfer Protocol". It is a communication protocol between information systems that allows the transfer of data between computer networks, mainly in the World Wide Web (Internet).

It communicates through Requisition and Answer, or the client (can be a browser or another server) makes a requisition to a server and this server returns a reply.

So much Requisition how much Answer are usually composed of header and body, except GET and HEAD requests, or responses to HEAD requests (has more types of requests but is not the focus to quote them yet).

An example of a request the client makes to a server:

Header:

GET /questions/130929/enviar-resposta-de-notificação-pelo-php HTTP/1.0
Accept: text/html,application/xhtml+xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.8
Cache-Control: max-age=0
Connection: keep-alive
Host: pt.stacokverflow.com
User-Agent: Mozilla/5.0 (Identificação do navegador)

In the case of GET has no "body"

And that the server sends for answer above may be something similar to this:

HTTP/1.0 200 OK
Date: Sat, 28 May 2016 22:03:54 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 17736
Connection: keep-alive
Vary: Accept-Encoding

<html>
...
</html>

See that the header goes from HTTP/1.0 (or 1.1) to the line break that comes after the Vary: Accept-Encoding and the body comes after this line break, where begins the <html> (of course there may be other line breaks or other type of content, but still it would be the BODY).

A basic scope of how the request and response works in HTTP:

http

Using in PHP, the 'header' function in PHP should always come before echo, print, var_dump or any content that goes to "output" in the body of the HTTP response (except if using ob_start), never afterwards, if this does not cause failure, or if errors are turned off this will only cause part of the response to be sent and the default server headers will be sent instead of your own.

Almost all your tests are totally wrong,

  1. There is no "header" or "Verb" called 200 SUCCESS:

    //erro 3
    header("200 SUCCESS");
    return "200 SUCCESS";
    
  2. return is not the same thing as echo and does not serve to send content to answer:

    //erro 5
    header('Content-Type: application/json');
    return 'SUCCESS';
    
  3. There is no "header" or "Verb" called SUCCESS:

    //erro 6
    header('Content-Type: application/json');
    header('SUCCESS');
    
  4. In addition to the first header is missing a part the function result there is no:

    ///erro 9
    header("HTTP/1.1 200");
    header("Content-Type:application/json; charset=utf-8");
    result 'SUCCESS';
    
  5. No "body" data passed in "header":

    ///erro 7
    header('Content-Type: application/json');
    $success =json_encode('SUCCESS');
    header($success);
    
  6. These are almost correct, but lacked the "body" and there is no header or Verb like this HTTP/1.1 200 SUCCESS

    ///erro 8
    header("HTTP/1.1 200 SUCCESS");
    header("Content-Type:application/json; charset=utf-8");
    

    And in this:

    //erro 10
    header("Content-Type:application/json;");
    header('HTTP/1.0 200 SUCCESS');
    

In HTTP as I said 200 is default, but if you have another header that has affected the default then you can use the header function like this:

header("Content-Type: application/json; charset=utf-8", false, 200);

However, if you only want to change the status code then this would be correct:

$protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0';
header($protocol.' 200 OK');

Or on PHP5.4:

http_response_code(200);

Summarized the correct is HTTP/1.1 200 OK for status 200, if you want other status codes see the following links.

List of HTTP codes

Your problem is not quite HTTP, but it’s still good to learn which are the correct status codes, follow two links to study:

Where is the problem then?

About your problem, of sending the answer 200, it is already standard on the server, what should be occurring is that you are using jQuery, as $.ajax or $.get or $.post and the answer is yes coming as 200, but json is in an invalid format (as I quoted at the beginning of the answer), this makes the "PARSE" jQuery fails, then always error occurs.

Then your PHP should look like this:

<?php
header('Content-Type: application/json; charset=UTF-8');

//Funções MYSQL

echo json_encode($data);
?>

Of course if you want to send a status code in case of an error in PHP you can try using ob_start, so you can use the header function after echo, would look like this:

<?php
ob_start();
header('Content-Type: application/json; charset=UTF-8');

if (... EXECUTA A QUERY MYSQL ...) {
    $resposta = 'success';
} else {
    $resposta = 'error';
}

echo json_encode(array( 'response' => $resposta ));

And Jquery must be something like this:

$.ajax({
  type: "POST",
  url: '[SUA PÁGINA PHP].php',
  data: { "DADOS DO POST": "VALOR A SER ENVIADO" },
  dataType: "json" //IMPORTANTE
}).done(function(data) {
    alert(data.response);//response é o mesmo que foi enviado no json_encode
}).fail(function(jqXHR, textStatus, errorThrown) {
    alert( "error:" + textStatus );
});

Documentation

Avoid "shooting in the dark", I recommend to always look at the documentation before using a function, follow the links to the documentation to study:

  • 3

    +1 for the capriciousness of the answer and for not being carried away by the disrespect of the author of the question.

-1


Code 200 is the default if no problem occurred in the request, so this should suffice:

header("Content-Type: text/plain");
echo "SUCCESS";
  • I edited and inserted the shapes I’ve tried unsuccessfully!!!

  • Julio, my solution was: header('HTTP/1.1 200 OK'); echo 'SUCCESS'; Return; Thank you for your contribution!!!

  • @Funny that in Julio’s answer there’s nothing about "200 OK" and in my answer there is. I recommend that you review your behavior in the community and always assume the good intentions of other users, even if a comment sounds strange.

  • Guilherme, I asked the same question in English in the post: http://stackoverflow.com/questions/37502915/send-response-http-200-success-in-php?noredirect=1#comment62518020_37502915 and the answer that helped me was the user Shadi Shaaban! I had already given the points to Julio Neto and I thought it was good to continue with the same ethics. Thank you for your reply, but it came after the above. I’m sorry if I disrespected you, but what I felt after your second answer was not good. When the problem is urgent there is no way to wait until Monday or Tuesday even if the voluntary help. Hug!!!

  • @Since this does not make any sense, the answer that should be chosen nothing should have to do with chronology, the question is that you took wrong a comment that you misinterpreted, if it was an answer from Stackoverflow in English that solved your problem is there and not here, then you should have formalized a correct answer to the problem that is the HTTP/1.1 200 OK, as I had already answered the correct path then it would be recommended you choose it, but this is clear that it is a situation of ill will and lack of recognition...

  • @prmas ... really or you do not understand the functioning of a Q&A or you are upset to have misunderstood my comment. The chosen question and answer should serve you and future users, make a choice of an answer that does not solve the problem for any reason is totally harmful to the site.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.