Search code examples
phpfunctionscopeglobal-variablesfwrite

How to use PHP global variable for 2 functions?


I'm trying to create an interface where a workshop description can be updated on the server after it has been created by a user. There is a text field and a button that brings up the workshop by the number it was assigned. (This is also the name of the directory in the submissions/workshop# on the server). When I set the variable $workshopPath using this method, I want to be able to access this global variable when a text input is filled out with the string to update the title of the workshop. The $workshopPath is registering as an empty string in the 'updateTextItems' function, so it is writing the text file to the root directory instead of to the correct workshop directory. I thought I was correctly referencing the global variable within the functions, but this isn't working. I also tried using $GLOBALS['workshopPath'], but that isn't working either. Can someone help me figure out how to pass the variable to the second function? Thanks :-)

<?php

$workshopPath;

if (isset($_POST['gotoWorkshop'])) {
  if (empty($_POST['numberInput'])) {
    echo "Please enter a valid workshop number";
  } else { //Assign the name variable form the posted field info if one was entered.
    $workshopNumber = stripslashes($_POST['numberInput']);
    global $workshopPath;
    $workshopPath = "submissions/" . $workshopNumber . "/";
  }
}

if (isset($_POST['updateTextItems'])) {
  if ($_POST['titleInput']) {
    //Assign the name variable form the posted field info if one was entered.
    $titleInput = stripslashes($_POST['titleInput']);
  }
  
  if ($titleInput) {
    global $workshopPath;
    $titleFile = fopen($workshopPath . "title.txt", "w") or die("There was an error creating the title file.");
    fwrite($titleFile, $titleInput);
    fclose($titleFile);
  }
}

?>

Solution

  • Do I understood you correct? The user fill in the a form for the workshop click on submit and get an other form for the text?

    My guess is you sent the requests to the server.

    So $GLOBAL will not work for you. It only works per request and I think most time you do not really need it.

    If you want to save some values across requests, you need a session.

    You need to start the session on both scripts with session_start(). After that you can use $_SESSION[] to store and get your values.