Search code examples
phpexecuteresume

is it possible for a php script to stop at a certain point and resume executing from before that?


i don't know if this can be done using php but it would be awesome for me if it did and php is pretty powerful so i think it is possible and i just can't figure out how.

i know that a php file is executed from top to bottom but i would like to know if there is a way of stopping the execution at some point to then resume it on a later occasion or is there a way of reaching a certain part of it and then resuming from a part that is before it or something like that?

i know how to make this if i simply put each individual block of code on a separate php file, in this way it will stop because it reached the end of the file and if something happens it will resume from another file so it makes pretty much the same thing, but i would like to make a php script that would behave like this but contained in 1 php file.

i don't need code examples i just need a nod in the right direction, like, some function names or something that could be useful to serve this purpose.


Solution

  • If you're trying to do things based on user input, you should probably either:

    1. Structure your program as a web application, such that each bit of user input spawns a new request to the page with the block of code that input should execute, or...
    2. Use a different language than PHP.

    Assuming you're doing #1, it's not all that hard to have a particular GET parameter that specifies what "step" you're on in the interaction - for instance, say you have a sequence of "A <user input> B or C <user input> D or E". You could have a URL scheme that looks like this:

    /app/code.php - this runs the code block A
    /app/code.php?step=B or /app/code.php?step=C - this runs either code block B or C
    /app/code.php?step=D or /app/code.php?step=E - this runs either code block D or E
    

    where the links/Javascript/whatever on the served pages allow choosing which page loads next. Your PHP file would look something like this:

    if(!isset($_GET['step'])) {
        // code block A
    } elseif($_GET['step'] == 'B') {
        // code block B
    } elseif($_GET['step'] == 'C') {
        // code block C
    } elseif($_GET['step'] == 'D') {
        // code block C
    } elseif($_GET['step'] == 'E') {
        // code block C
    } else {
        // error, invalid step specified
    }
    

    You could also simply split the steps up into different PHP files. Which approach would be best probably depends on how much functionality is shared between the different options, and how much is different - if lots is shared, a single file might be easier; if most is different, separate files are probably simpler.