Question

How to return a HTTP status code with PHP serverless function

I want to return a custom HTTP status code in a PHP serverless function. But the following code:

return ['body' => ['test'=>'Lorem ipsum'], 'statusCode' => 404];

Has this output (with HTTP status 200):

{"body":{"test":"Lorem ipsum"},"statusCode":404}

Expected output (with HTTP status 404):

{"test":"Lorem ipsum"}

Submit an answer


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

alexdo
Site Moderator
Site Moderator badge
March 7, 2023

hello @accountmorel

Here is a minimal example that the function returns an error repose along with an HTTP status code and additional HTTP headers:

  1. function main(): array {
  2. return [
  3. 'body' => 'The requested resource is not found.',
  4. 'statusCode' => 404,
  5. 'headers' => (object)
  6. [
  7. 'Cache-Control' => 'no-cache',
  8. ],
  9. ];
  10. }

You can find more information here:

https://www.digitalocean.com/community/tags/serverless

https://php.watch/articles/php-serverless-digital-ocean

Hope that this helps!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

card icon
Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Sign up
card icon
Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We’d like to help.

Learn more
card icon
Become a contributor

You get paid; we donate to tech nonprofits.

Learn more
Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow – whether you’re running one virtual machine or ten thousand.

Learn more ->
DigitalOcean Cloud Control Panel
Get started for free

Enter your email to get $200 in credit for your first 60 days with DigitalOcean.

New accounts only. By submitting your email you agree to our Privacy Policy.

© 2023 DigitalOcean, LLC.