How to access a variable from one PHP page to another, without a form, link, or button?

隐身守侯 提交于 2020-01-17 03:59:22

问题


TLDR:- What is a good way to pass contents of a variable from one PHP file to another without involving a form, link or a button.

Question:-

So there is a form in a page/file called question_edit_form.php and its action attribute is already set to another file called question.php. The variable of interest is being read-in from the user in question_edit_form.php and is then obviously being sent to question.php using $_POST.

Now, there is a third file, named renderer.php, and which is not linked to the other two files. I want to use that variable of interest in this file. So how can I access that variable which is set in question.php from inside renderer.php?


回答1:


You can store the variables in the session.

http://www.w3schools.com/php/php_sessions.asp




回答2:


first file -

session_start();
$_SESSION['your_variable'] = 'value';

other file -

session_start();
$var = $_SESSION['your_variable'];

this may help.




回答3:


It sounds like you are using Moodle, in which case renderer.php is not an independent file; it contains the class definition for the renderer object used by question.php.

So... there is no need to pass the parameter between the scripts. If you really must access the form value directly from the renderer, just use the standard methods from the Moodle framework: required_param($name, $type) or optional_param($name, $default, $type).




回答4:


Generally there are two methods available for you to pass on the value

  1. Cookies

  2. Sessions

How to use cookies:-

setcookie(name, value, expire);

e.g.

setcookie("user", "Alex Porter", time()+3600);

Access it using echo $_COOKIE['user'];

Second is Sessions. Here is how to use sessions:-

 session_start();
 $_SESSION['varname']=value;

Accessing page:-

session_start();
echo $_SESSION['varname'];

Additional info if required:- Make sure you use session_start() at top of your page if not you may face with an headers already sent error / warning which again can be fixed by output buffering ob_start()



来源:https://stackoverflow.com/questions/25072599/how-to-access-a-variable-from-one-php-page-to-another-without-a-form-link-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!