tags:

views:

46

answers:

3

Can you run some script before the uploading of a file starts in php? Example, I'm POSTing to upload.php, and in that file I want to check their $_SESSION first before I start wasting bandwidth on them and the file stats uploading to my server. I'm using php 5.2.11 on nginx.

<?php
  if ($_SESSION['admin'] == 'YES') {
    // do upload here
  } else {
    exit;
  }
?>
+2  A: 

No. The request doesn't get to the PHP engine until after the file has been uploaded.

Ignacio Vazquez-Abrams
The fundamental reason for this is that the upload is just big chunk of encoded data in the body section of the request. In PHP level, you cannot prevent a client making POST request to arbitrary location with data in the body. In server level it's technically possible (close the connection if no valid session id found in headers), but I think no web server can be configured at this level unless you write a custom module etc. In nginx you can set _client_max_body_size_ limit, but that's about it.
jholster
+1  A: 

No, because the upload is part of the request and is done before PHP even comes into play.

There may be a way around this using the technique of those PHP-/Perl-based uploaders that somehow hook into the uploading process, but then, there also may not. Especially when you're using a different web server.

I would do a quick Ajax-based check for the right session, and bind that to the submit event of the form you are uploading the file with. It may take half a second, but is completely unobtrusive for the user.

Pekka
why just not to show an upload form to unauthorized user?
Col. Shrapnel
@COl. Shrapnel I assume he wants to make sure the session hasn't expired.
Pekka
A: 

You could make an ajax call on the page the form is submitted to check their session state before allowing the form to submit.

Jud Stephenson
that's not an answer. Ajax cannot be used as it's just the same as regular form and can be easily avoided
Col. Shrapnel
+1 - it's the nearest thing to a valid solution for the question asked, although you'd be a bit daft to use an asynchronous call from the onsubmit method.
symcbean
I think the Col. can't read.
Jud Stephenson
I can think. That's much better
Col. Shrapnel
To avoid unnecessary argument:You cannot, using only php, check a session variable *before* a file is uploaded. The only possible way to do what the OP is asking is to bind an ajax request to the onSubmit.90% of users are not going to modify the form to get around the ajax call. If they do, their session is checking in upload.php. Just saying.
Jud Stephenson