How to access a variable from one PHP page to anot

2019-08-16 07:50发布

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?

4条回答
虎瘦雄心在
2楼-- · 2019-08-16 07:54

You can store the variables in the session.

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

查看更多
一纸荒年 Trace。
3楼-- · 2019-08-16 08:00

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()

查看更多
Ridiculous、
4楼-- · 2019-08-16 08:07

first file -

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

other file -

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

this may help.

查看更多
一夜七次
5楼-- · 2019-08-16 08:07

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).

查看更多
登录 后发表回答