1

Language Used: PHP
Version: 5.6

I am trying to upload a file to the server with the following function:

move_uploaded_file($source,$destination);

Whenever file fails to upload due to any reason such as

  • Permission denied,
  • No Destination folder found,
  • etc

    It simply raises a warning and continues with other parts of the code. But I want to catch that warning and change the flow of the program if any of the warnings are raised with their name so that I can throw appropriate Exception.

    I am currently using try{}catch(){} block to upload a file but an exception is not raised for the warning.

    Edited Found this...

    move_uploaded_file($source,$destination);
    

    returns true or false based on status of file upload. But it does not specify reason. How to know that?

    • It's a warning, so it won't throw it's own exception. [move_uploaded_file](https://www.php.net/manual/en/function.move-uploaded-file.php) returns false if it fails, so you can always throw your own exception there. – aynber Nov 13 '19 at 18:39
    • @aynber Thanks for your input. But, what if want to know the reason behind failure of file upload? – Jain Rishav Amit Nov 13 '19 at 18:42
    • You might want to look here (https://stackoverflow.com/questions/1241728/can-i-try-catch-a-warning). Using the error handler should allow you to get more information. – aynber Nov 13 '19 at 18:44
    • In the error handler you can then look for `Permission denied` etc... – AbraCadaver Nov 13 '19 at 18:50
    • If you are still using PHP 5 I strongly recommend to upgrade as soon as possible. This version is no longer supported. [Let Rasmus Lerdorf explain it to you](https://youtu.be/wCZ5TJCBWMg?t=2434) – Dharman Nov 13 '19 at 23:48

    1 Answers1

    0

    I guess set_error_handler() would be the right choice. Make sure your read the documentation carefully.

    https://www.php.net/manual/en/function.set-error-handler.php.

    First, you'd need an function (or public class-method) to handle the error. Example:

    function error_handler($code, $text, $file, $line) {
        echo sprintf('code: %s, text: %s, file: %s, line: %s', $code, $text, $file, $line );
    
        return false; // continue with PHPs error handling
    }
    

    Second, call set_error_handler somewhere in your init/bootstrap code. Specify your error_handler method and set appropriate flags for which situations you want to be informed.

    $flags = E_ALL & ~(E_STRICT | E_NOTICE);
    set_error_handler('error_handler', $flags);
    error_reporting($flags);
    

    A word of warning: If you intend to catch errors like out-of-memory, your code should be prepared to use as less memory as possible. Also resources may not be available anymore (like database connections or file handles).

    Dharman
    • 30,962
    • 25
    • 85
    • 135
    Honk der Hase
    • 2,459
    • 1
    • 14
    • 26