Cannot modify header information - headers already sent by (output [duplicate] - header

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 8 years ago.
I think I screwed up my website, this is an error I get on one of the pages
Warning : Cannot modify header information - headers already sent by (output started at /home/content/94/9066***/html/websites/{website name}.com/index.php:3) in /home/content/94/9066***/html/websites/{website name}.com/wp-includes/pluggable.php on line 896
How do I get rid of this? Thank you so much for your help!!

You get this error because you're setting a header (most likely with the header function) after some output (body) have already been sent to the client, for example with a echo
The line of code + source file where the body output starts and where you attemp to set a header are in the error you receive.
The rule is first all headers are set then comes the body of the response.

Or just because a line end... Check
<?php // is there a blank line before this one?
...
?> //same question

Usually this warning is thrown when an output (even a space or a blank line) is sent to the browser before the session function call.
As this is happening on a wordpress site, did you modify any code in index.php?
Check if anything is echoed before the session_start() function call.

If we have a little knowledge about HTTP headers, we can fix "Headers already sent" errors. So I will touch just the overview of headers.
During a HTTP request, HTTP headers called [REQUEST HEADERS] are sent from client to the server and during a HTTP response, HTTP headers called [RESPONSE HEADERS] are sent from server to client.
Now, what the hell these headers contain?
REQUEST HEADERS--> Hostname,cookie info, the kind of encoding that the client accepts,etc.
RESPONSE HEADERS--> Content type being sent, info about Content encoding, etc.
You can get a lot of info about the headers in the below link:
http://code.tutsplus.com/tutorials/http-headers-for-dummies--net-8039
In plain English, Headers contain information about the page being requested or sent.
Now Answering the ques:
Php header() function modifies the default RESPONSE headers and includes information that you want to send.
THUMBRULE:
Since response headers contain info about the page being sent to client,
RESPONSE headers should be sent **FIRST** before the page itself.
So when you echo or display something to the browser and then use the header() function,
<?php
echo "hi";
header("As you have already displayed "hi", this info will not be sent.);
?>
In the above code we have actually sent the page and then trying to send our header info,
so the headers will not be modified as the default headers were already sent and hence the error:
"Headers already sent".
Ans:
1) So, always include the header() function before displaying anything to the browser.
2)Another method to avoid the error is to use ob_start() function. This function just stores all the information that needs to be sent to the browser in a buffer memory, and it will output all at once.
Lets take a look at the code which will make more sense:
<?php
ob_start();
echo "hi";
echo "Hello"
header("This info will be sent");
ob_end_flush();
?>
In the above code, header info will be sent as both the echo statements will be stored in a buffer and will not be sent to the browser until the line ob_end_flush(); is executed. ob_end_flush() will just flush out the buffer memory sending all the info to the browser.
NOTE: But again make sure, you use the **ob_start()** function in the beginning.

Related

Google Sheet API batchUpdateByDataFilter PHP Function

https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdateByDataFilter
We have used above function in our code, while we are passing the more than 50 or 100 records within the array records then given 400 bad request array in response.
Can anyone describe the limit of the total values that we are going to pass within the above function?
Here is my code:
$batchupdate = array("valueInputOption" => "RAW", "data" => $dataarray);
try {
$requestBody = new Google_Service_Sheets_BatchUpdateValuesByDataFilterRequest($batchupdate);
$response = $service->spreadsheets_values->BatchUpdateByDataFilter($spreadsheetId, $requestBody);
}
catch(Exception $e) {
echo 'Message: ' . $e->getMessage();
}
Troubleshooting:
Problems with the Request
Until you attach a sanitized version of your Request body we cannot be sure about the root-cause of the problem you are facing.
However, an error 400 means that the request you did is invalid. So, most likely, the problem is in that.
Check if your request object is formatted as detailed on the documentation.
Problems with the Client
If you are able to use the Try this API sidebar with the same Request Body then it could be related to the PHP client.
Note: This is language independent. Create a JSON Object that has the same structure as your request body.
If that's the case, we will need to see more of your code to verify that you are not using your valid Request body in an invalid way (eg. sending it encapsulated in another object).
By referencing the PHP Library documentation you can see the properties of the objects you can use.

How to set content-type in Rest Client step

I'm using the Rest Client as below,
But every time I have the same error message
HTTP Error 400. The request has an invalid header name.
When I use the same config in postman client, (Content-Type:application/x-www-form-urlencoded) I've success message.
What I have to do ?
This might be somewhat reviving an old question, however:
In the headers tab on the Rest Client step the field column refers to a data field in your input stream to this step. The Name refers to the Name of the header. In the screenshot you've added you're trying to add a header called ${CONTENT_TYPE} with the value as contained in your stream field content-type.
Your first step appears to be a data grid. That grid needs to be supplying a field that you reference as your content-type header. If it can't come from that grid you need to inject a step (something like Add Constant) that will add the content-type header.
Hope it helps.

API: Custom 404 not found error response structure

Considering this url: http://example.com/users/1/post/2/likes.
How can I correctly define structure of my 404 response, showing which item is not found? user, post or likes?
You can send an HTTP status code using the header() function, by starting the header with the status code number, followed by the message to send to the user.
header("404 " + $message);
The code that processes the parameters can determine which item isn't found, and put that into $message.

Why does PHPUnit interfere with setting HTTP headers in this code?

I have a function that creates CSV data and lets the user download it in the browser, basically like this:
function f() {
if ($fp = fopen('php://output', 'w')) {
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=\"foo.csv\"");
fputcsv($fp, $someArrayGoesHere);
flush();
fclose($fp);
// debugging, explained below
error_log(print_r(xdebug_get_headers(), true));
}
}
The code works, presenting the user with a download dialog.
Now, I'm trying to write a PHPunit test to confirm that the two HTTP headers get set. Realizing that headers_list() doesn't work in CLI context (php_sapi_name() == 'cli'), I'm using xdebug_get_headers() to retrieve the headers for testing.
Now comes the trouble. The debugging line in my code above, when run on the web, always prints the headers I expect:
Array
(
[0] => X-Content-Type-Options: nosniff
[1] => Content-Type: text/csv
[2] => Content-Disposition: attachment; filename="foo.csv"
)
But when I run this code in phpunit, the PHPUnit_Util_Printer::write function appears to be producing output before my code sets the headers, and prevents them from being set, producing this debug output:
Cannot modify header information - headers already sent by (output started
at /usr/share/pear/PHPUnit/Util/Printer.php:172)
Array
(
[0] => Content-type: text/html
)
This earlier write is not being produced by me, so is there a way around it? How do I test for my CSV-related headers using phpunit?
I've already read the advice given in these questions, but it hasn't helped:
Headers already sent by PHP
PHPUnit - test for expected headers
PHPUnit - Unit Testing with items that need to send headers
Test PHP headers with PHPunit
Setting HTTP headers to be able to run test cases
I also tried using #runInSeparateProcess with the unit test, but the test crashes horribly: ".Unexpected non-MediaWiki exception encountered, of type "Exception", exception 'Exception' with message 'Serialization of 'Closure' is not allowed' in /usr/share/pear/PHPUnit/Util/GlobalState.php:354". (This is a MediaWiki unit test for a custom extension.)
The answer to your literal question "Why does PHPUnit interfere with setting HTTP headers in this code?" is given fairly clearly in the answer to Test PHP headers with PHPunit. PHP's header() will fail with the Cannot modify header information warning if anything has been written to stdout. When running your code via PHPUnit, content has been sent to stdout long before your code under test has been reached.
You noted a separate issue when using the #runInSeparateProcess annotation to fork a clean PHP process for your test:
Unexpected non-MediaWiki exception encountered, of type "Exception", exception 'Exception' with message 'Serialization of 'Closure' is not allowed' in /usr/share/pear/PHPUnit/Util/GlobalState.php:354
By default PHPUnit attempts to backup all of the $GLOBALS data before each test and restore it afterwards. MediaWikiTestCase turns this behavior off but it looks like your extension's tests are not. It seems likely that the configuration for your extension includes a closure and is causing the serialization failure. Adding a #backupGlobals disabled annotation to your PHPUnit_Framework_TestCase class should get you past this problem.

Upload file to Solr with HttpClient and MultipartEntity

httpclient, httpmime 4.1.3
I am trying to upload a file through http to a remote server with no success.
Here's my code:
HttpPost method;
method = new HttpPost(solrUrl + "/extract");
method.getParams().setParameter("literal.id", fileId);
method.getParams().setBooleanParameter("commit", true);
MultipartEntity me = new MultipartEntity();
me.addPart("myfile", new InputStreamBody(doubleInput, contentType, fileId));
method.setEntity(me);
//method.setHeader("Content-Type", "multipart/form-data");
HttpClient httpClient = new DefaultHttpClient();
HttpResponse hr = httpClient.execute(method);
The server is Solr.
This is to replace a working bash script that calls curl like this,
curl http://localhost:8080/solr/update/extract?literal.id=bububu&commit=true -F myfile=#bububu.doc
If I try to set "Content-Type" "multipart/form-data", the receiving part says that there's no boundary (which is true):
HTTP Status 500 - the request was rejected because no multipart boundary was found
If I omit this header setting, the server issues an error description that, as far as I discovered, indicates that the content type was not multipart [2]:
HTTP Status 400. The request sent by the client was syntactically incorrect ([doc=null] missing required field: id).
This is related to [1] but I couldn't determine the answer from it. I was wondering,
I am in the same situation but didn't understand what to do. I was hoping that the MultipartEntity would tell the HttpPost object that it is multipart, form data and have some boundary, and I wouldnt set content type by myself. I didn't quite get how to provide boundaries to the entities - the MultipartEntity doesn't have a method like setBoundary. Or, how to get that randomly generated boundary to specify it in addHeader by myself - no getBoundary methor either...
[1] Problem with setting header "Content-Type" in uploading file with HttpClient4
[2] http://lucene.472066.n3.nabble.com/Updating-the-index-with-a-csv-file-td490013.html
I am suspicious of
method.getParams().setParameter("literal.id", fileId);
method.getParams().setBooleanParameter("commit", true);
In the first line, is fileId a string or file pointer (or something else)? I hope it is a string. As for the second line, you can rather set a normal parameter.
I am trying to tackle the HTTP Status 400. I dont know much Java (or is that .Net?)
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_Error