5

I've a CGI module written in C & for some condition I want to return HTTP error 400 from this module. The problem is - I don't know how to return HTTP error from the module.

Looks like the 'return(-1)' in my module, returns the 500 internal server error. I've tried returning 400 etc. but in vein. I've even tried "printf("Status:400");" before returning -1 (as suggested here: How to return a 500 HTTP status from a C++ CGI program ) but that didn't work.

Any advice on this would be appreciated.

Edit: [solved] I was able to return HTTP error code from the python module (which is called later by this C CGI module). So didn't get to try the suggestion mentioned in comments below. Thanks for offering help, though.

2
  • return 0, but set the header appropriately - it returns it's own error when the exit code of the script is non-zero Commented Mar 27, 2013 at 10:28
  • 1
    Please show us what you have tried, in it's exact form. Commented Mar 27, 2013 at 10:47

2 Answers 2

11

To return HTTP error 400 to the HTTP client, you have to write the HTTP status line to stdout, like this:

printf("Status: 400 Bad Request\n");

Ref: https://www.rfc-editor.org/rfc/rfc3875

The Status header field contains a 3-digit integer result code that indicates the level of success of the script's attempt to handle the request.

  Status         = "Status:" status-code SP reason-phrase NL
  status-code    = "200" | "302" | "400" | "501" | extension-code
  extension-code = 3digit
  reason-phrase  = *TEXT
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Never get to try that as the problem got solved the other way. Thanks anyways... :)
My mistake. I updated my answer. (my previous answer was not CGI compliant, but HTTP compliant suitable for callbacks within HTTP servers like civetweb)
-1

To return HTTP error code from your CGI script, you have to write it into stdout, such as:

#include <stdio.h>

int main()
{
    printf("status: 400\n\n");

    return 0;
}

Just the status: status-code\n\n is necessary.

1 Comment

This is wrong. The RFC say \r\n is the correct delimiter als "Status: 400"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.