在 <a > 标签、锚标签内调用 PHP 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2782208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:39:41  来源:igfitidea点击:

Calling a PHP function within an <a > tag, anchor tag

phphtml

提问by Elitmiar

Is it possible to call a PHP function within an anchor tag. I have a PHP function called logout();

是否可以在锚标记中调用 PHP 函数。我有一个名为的 PHP 函数logout();

Now I want something similar to this.

现在我想要类似的东西。

<a href="logout();" >Logout</a>

I know with Javascript this works but what is the best approach using PHP function?

我知道使用 Javascript 可以工作,但是使用 PHP 函数的最佳方法是什么?

回答by Richard JP Le Guen

No; PHP is a server side scripting language, so it is inaccessible to the HTML like this. JavaScript can do this, as it is a client-side scripting language.

不; PHP 是一种服务器端脚本语言,因此像这样的 HTML 无法访问它。JavaScript 可以做到这一点,因为它是一种客户端脚本语言

Since PHP is a server side language, a message (in the form of an HTTP request) must be sent to the server from the browser (the client) for any PHP to be executed - including your PHP function logout.

由于 PHP 是一种服务器端语言,必须从浏览器(客户端)向服务器发送一条消息(以 HTTP 请求的形式),以便执行任何 PHP - 包括您的 PHP 函数logout

You have a few options...

你有几个选择...

Option 1

选项1

Follow the hyperlink to a script which executes the logout()function...

按照超链接到执行该logout()功能的脚本...

HTML

HTML

<a href="theLogOutScript.php">Logout</a>

PHP

PHP

<?php
   // ...
   logout();
   // ...
?>

Option 2

选项 2

Submit a form to a script which executes the logout()function...

将表单提交给执行该logout()函数的脚本...

HTML

HTML

<form method="POST" action="theLogOutScript.php">
    <input type="submit" value="Logout" />
</form>

Option 3

选项 3

Use an XMLHttpRequest/AJAX request to communicate with the server. (no sample code provided)

使用XMLHttpRequest/AJAX 请求与服务器通信。(没有提供示例代码)

回答by Justin Ethier

No, in order to call PHP you will have to make a request back to the server. You will either need to link to another PHP page:

不,为了调用 PHP,您必须向服务器发出请求。您需要链接到另一个 PHP 页面:

<a href="/logout" >Logout</a>

Or you will have to make a JavaScript AJAX call to a PHP page ("web service") that will perform the logout.

或者,您必须对执行注销的 PHP 页面(“Web 服务”)进行 JavaScript AJAX 调用。

回答by a1ex07

<a href ='logout.php'>Logout</a>

logout.php

登出.php

<?php
  session_start();
  ...... your code....      
?>

回答by davegamez

You didn't specify the format of your document. If your document format is HTMLyou'll need to load an external file but if it's .phpYou can do it by setting your function inside a variable like so:

您没有指定文档的格式。如果您的文档格式是HTML,您将需要加载一个外部文件,但如果它是.php您可以通过将您的函数设置在一个变量中来完成,如下所示:

<?php $myLogout  = logout();?>
<a href="<?php echo $myLogout; ?>">Logout</a>