Created
April 30, 2014 22:48
-
-
Save anonymous/80080060869f875e7214 to your computer and use it in GitHub Desktop.
Allow for non-blocking continue confirmations in long running php processes on win32 platforms...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Allows for asking the user if they want to continue a long running process without blocking PHP if the user doesn't respond on Win32 platforms | |
* @param int $duration - number of seconds to wait until we continue anyway | |
* @note: Inspired from this stackoverflow post | |
* @author http://stackoverflow.com/users/2581/martin | |
* @link http://stackoverflow.com/a/9711142 | |
* @license http://creativecommons.org/licenses/by-sa/3.0/ | |
*/ | |
function confirm_continue($duration = 30) | |
{ | |
if (!is_numeric($duration) || $duration > 1000 || $duration < 1) | |
{ | |
throw new Exception("Invalid readline timeout duration, must be numeric and between 1 and 1000"); | |
} | |
echo "Press Enter Key to stop processing... ($duration seconds to answer)\n?: "; | |
while($duration--) | |
{ | |
//Check on STDIN stream | |
$read = [STDIN]; | |
$result = stream_select($read, $write = [], $except = [], 0); | |
//handle results | |
if ($result === false || $result === 0) | |
{ | |
//nothing was entered on stdin so wait another second | |
sleep(1); | |
} | |
else | |
{ | |
//On windows if the cmd prompt process loses focus, we get a false positive response of 1 from stream_select | |
//So we ask for a confirmation from the user. If losing focus was unintentional, answering this question will reset the | |
//stream_select() result. In the event that the user had actually pressed Enter to stop the process, the dangling newline | |
//character will cascade into this stream_get_line() request and automatically confirm that we should end the process. | |
echo "Process interrupted... Are you sure you want to stop this process? [y/n]"; | |
return trim(stream_get_line(STDIN, 1024, PHP_EOL)) == "n" ? true : false; | |
} | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment