Suppose we do an authorization task on the site. The following files are used:

  • index.php - file with login form
  • captcha.php - captcha file
  • singnin.php - file with the send script.

Experimentally, I found that the call to session_start is required in each file:

  • If we entered something wrong, then an error message is recorded in the session and displayed on the main page (I had a separate question about this)

     if(isset($_SESSION['error'])){echo $_SESSION['error'];} 
  • In captcha.php you need to generate numbers, which we again write to the session.

  • In signin.php we verify the entered data with the captcha, that is, we need data from the session.

Considering that all files are interconnected ( captcha.php is output via img to index.php , and singnin is called from index.php via the action attribute), which explains the need to call session_start in each of them?

    2 answers 2

    For a better solution, you need to use the single entry point index.php , and everything else should be connected to index.php , through the same routing and then you will not have to constantly call session_start() in each file. And you do not need to record errors in the session, - you send POST, GET, PUT, etc requests and should receive an answer right away, not write to the session and it is not clear where to output.

      if I correctly understood about the "action", then thinking that the files are connected in this case is not true.

      • the user requests the main page from the web server (index.php)
      • web server sends request to php interpreter
      • php runs index.php which displays a page with a form
      • php returns the data to the server and the server to the client (user)

      At this communication with the server is over. upd: (when the client receives the page, he will execute another request for captcha.php uploading a picture)

      When the user drives a captcha, it is sent to the address specified in

       <form action="signin.php"> 

      Here it all starts from the beginning, according to the scheme above.

      The web server will no longer run index.php, because the “request parameters” call signin.php. If there is no session_start () there as in index.php, then we will not be able to access session variables. Actually that's all.

      Look at the "single entry point" template or better start watching some popular framework.