The Slim Framework support forum has moved to http://discourse.slimframework.com. This Tender forum is no longer maintained or monitored.

Use or not to use "exit"

Kishor's Avatar

Kishor

08 Apr, 2012 06:46 AM

Here is my code:

if ( ! isset($_SERVER['PHP_AUTH_USER'])) {
    send_response('401', "No user supplied");           
            exit; // ****************** Use or no?
} else { 

    $username = trim($_SERVER['PHP_AUTH_USER']); 

     if(!valid email( $username)) { 
        send_response('401', 'Invalid Username');           
        exit; // 
    }

    try {
            // dO something and send response.
        send_response('404', "Something is working");           
        exit; // ******************use or no?

    } catch (PDOException $e) {
                    print "Error!: " . $e->getMessage() . "<br/>";
                        $dbo = NULL;
                    die();
    }

    send_response('500', 'Okay');
}

Send_response function:
{

$app = Slim::getInstance('CommAPI');
$response = $app->response();

//Generate Response headers
$response->header('Content-Type', "application/json");
$response->status(DEFAULT_RESPONSE_CODE);                  
$response->header('Content-Length', '500');

$responseBody = array('message'=> $body);
$response->body(json_encode($responseBody));


$response->send();

}

Problem:
if I don't use "exit", then its executing the last send_response that it hits. It executes all other send_response function too on its way.
I was under assumption, when response->send() is invoked, its the last statement that is executed and execution stops there

But it appears that is not the case here. If I use "exit", it works as expected.

Am I missing something?

  1. Support Staff 1 Posted by Andrew Smith on 08 Apr, 2012 07:04 AM

    Andrew Smith's Avatar

    What version of Slim are you using? have you tested this on 1.6.0 branch?

  2. 2 Posted by Kishore on 09 Apr, 2012 03:41 PM

    Kishore's Avatar

    So its 1.5.

  3. Support Staff 3 Posted by Josh Lockhart on 09 Apr, 2012 03:54 PM

    Josh Lockhart's Avatar

    You shouldn't need to call exit. In your first example code, the else clause may invoke the send_response method twice: once in the try block, and twice after the try block.

    I'd suggest improving your conditional branching. Otherwise, yes, you'll need to call exit where appropriate.

    Also, is there a reason you are directly invoking the send method on the Response object instead of calling the Slim application's run method?

  4. 4 Posted by Kishore on 09 Apr, 2012 04:04 PM

    Kishore's Avatar

    Thanks, Josh.

    "Also, is there a reason you are directly invoking the send method on the Response object instead of calling the Slim application's run method?"

    Maybe, I don't understand this yet. Should I be calling run? In a hook?
    This function is a pre-dispatch hook that validates the request to see if the authentication is sent along with the request. Only if valid, the request is allowed and goes to the specific route. Otherwise, the response should end here.

    Can you shed some light here?

  5. 5 Posted by Kishore on 09 Apr, 2012 04:12 PM

    Kishore's Avatar

    And I am still not clear, how the control goes to next "send", when I already sent the response, regardless of my conditional statements.

    For instance,

    if(!preg_match("/^[a-z0-9_\+-]+(\.[a-z0-9_\+-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,4})$/i", $username)) {   
            send_response('401', 'Invalid Username');           /
            exit;
        }
    

    send_response('500', 'Okay');

    In this case, if its not a valid email address, then it should NOT execute the 500 response.

    correct?

  6. Support Staff 6 Posted by Josh Lockhart on 09 Apr, 2012 04:14 PM

    Josh Lockhart's Avatar

    Ah ok. I would setup the application like this:

    <?php
    $app = new Slim();
    $app->hook('slim.before', function () use ($app) {
        $req = $app->request();
        $isValid = true; //<-- Validate request here
        if ( !$isValid ) {
            $app->contentType('application/json');
            $app->halt(500, '{"error":"Something went wrong"}');
        }
    });
    $app->get('/some/other/route', function () {
        //Something goes here
    });
    $app->run();
    
  7. 7 Posted by Kishore on 09 Apr, 2012 04:17 PM

    Kishore's Avatar

    Hmm.. So I should call halt() instead of send()?
    When do we actually call send()?

    Thanks!

  8. Support Staff 8 Posted by Josh Lockhart on 09 Apr, 2012 04:22 PM

    Josh Lockhart's Avatar

    Let Slim worry about the response. Calling $app->halt(status, message) will tell Slim to prepare the response and send it while then exiting the application.

  9. 9 Posted by Kishore on 09 Apr, 2012 04:26 PM

    Kishore's Avatar

    Thanks!

    If I want to set additional headers, is there a method I can use on slim instance? I looked at the documentation. I don't see anything to set the headers, directly from the slim instance.

    http://dev.slimframework.com/phpdocs/

  10. Support Staff 10 Posted by Josh Lockhart on 09 Apr, 2012 04:37 PM

    Josh Lockhart's Avatar

    You'll want to set headers on the response object like this:

    $res = $app->response();
    $res['Header-Name'] = 'Header value';
    

    Docs available here:

    http://www.slimframework.com/documentation/develop#response-header

  11. 11 Posted by Kishore on 09 Apr, 2012 04:40 PM

    Kishore's Avatar

    Yes, I am using response object to set headers.

    So now I assume, I set the response headers using Response object and then call
    app->halt() (then, $app->run()). Then slim automatically sends the headers from response object and I don not have to invoke send() from response object.

    Correct?

    Thanks again!

  12. Support Staff 12 Posted by Josh Lockhart on 09 Apr, 2012 04:48 PM

    Josh Lockhart's Avatar

    You always must call $app->run() as the last call in your primary index.php front-controller code.

    Only call $app->halt() when you wish to halt the application. Slim will handle everything else.

  13. 13 Posted by Kishore on 09 Apr, 2012 05:01 PM

    Kishore's Avatar

    Thanks, Josh!

    I guess I was not clear on the 2nd part of my questions.

    The only question I have now is, for additional Headers, should I use Response object and then call $app->halt()?

  14. Support Staff 14 Posted by Josh Lockhart on 09 Apr, 2012 05:06 PM

    Josh Lockhart's Avatar

    Yes, you should set headers on the response object. Then call $app->halt() to stop the application from processing further. You should never need to send the response manually. Slim will do that.

  15. 15 Posted by Kishore on 09 Apr, 2012 05:09 PM

    Kishore's Avatar

    Gotcha! Thanks!

  16. Support Staff 16 Posted by Josh Lockhart on 09 Apr, 2012 05:12 PM

    Josh Lockhart's Avatar

    Great. Closing this out.

  17. Josh Lockhart closed this discussion on 09 Apr, 2012 05:12 PM.

Comments are currently closed for this discussion. You can start a new one.

Keyboard shortcuts

Generic

? Show this help
ESC Blurs the current field

Comment Form

r Focus the comment reply box
^ + ↩ Submit the comment

You can use Command ⌘ instead of Control ^ on Mac