我有这个HTML表单:
<form action="../functions/createproject.php" method="post">
Name: <input type="text" name="name"><br>
Description: <input type="text" name="description"><br>
<input type="submit">
</form>
这个PHP代码(createproject.php):
<?php
$projectname = $_POST["name"];
$projectdescription = $_POST["description"];
function createproject() {
if (!file_exists("../projects/$projectname")) {
mkdir("../projects/$projectname", 0777, true);
}
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "../projects/$projectname/info.txt","wb");
fwrite($fp,$content);
fclose($fp);
}
createproject();
?>
但是我收到以下错误:
Notice: Undefined variable: projectname in /home/wdele/domains/hypah.org/public_html/functions/createproject.php on line 5 Notice: Undefined variable: projectname in /home/wdele/domains/hypah.org/public_html/functions/createproject.php on line 8 Warning: fopen(/home/wdele/domains/hypah.org/public_html../projects//info.txt): failed to open stream: No such file or directory in /home/wdele/domains/hypah.org/public_html/functions/createproject.php on line 8 Notice: Undefined variable: content in /home/wdele/domains/hypah.org/public_html/functions/createproject.php on line 9 Warning: fwrite() expects parameter 1 to be resource, boolean given in /home/wdele/domains/hypah.org/public_html/functions/createproject.php on line 9 Warning: fclose() expects parameter 1 to be resource, boolean given in /home/wdele/domains/hypah.org/public_html/functions/createproject.php on line 10
我想不出有什么理由不起作用。
有什么想法吗?感谢。
答案 0 :(得分:3)
您在全局范围内定义$projectname
,但在函数范围内使用它。有两种方法可以解决这个问题:
使用global
在函数中提供全局变量:
function createproject() {
global $projectname;
...
或者,更改函数以$projectname
作为参数:
function createproject($projectname) {
...
然后使用createproject($projectname)
调用它。
后者是通常的方式。全局变量的使用通常是不受欢迎的,因为它使代码更难理解而且模块化程度更低。
答案 1 :(得分:0)
您无法在函数外调用已定义的变量。使用global
关键字。像这样:
function createproject() {
global $projectname;
if (!file_exists("../projects/$projectname")) {
mkdir("../projects/$projectname", 0777, true);
}
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "../projects/$projectname/info.txt","wb");
fwrite($fp,$content);
fclose($fp);
}