我有这个 PHP 脚本:
<?php
if($_GET["name"] != null && $_GET["name"] != ""){
$name = urlencode($_GET["name"]);
$name = htmlentities($name);
$title = urlencode($_GET["title"]);
$title = htmlentities($title);
$art = urlencode($_GET["art"]);
$art = htmlentities($art);
$output = array();
exec("python add.py $name $title $art",$output);
}
?>
这是 add.py 文件:
import sys
import sqlite3
name = sys.argv[1]
title = sys.argv[2]
art = sys.argv[3]
tup = (name,title,art)
conn = sqlite3.connect('arts.db')
c = conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS arts(name,title,art)')
c.execute('INSERT INTO arts VALUES(?,?,?)',tup)
conn.commit()
conn.close()
当文件运行时,我的当前目录中没有 arts.db 文件。不仅如此,当我通过到处添加 print 语句来调试程序时,我意识到我的程序运行到 conn = sqlite3.connect('arts.db')
为止,然后在该语句之前退出已执行。
我的程序没有错误,因为我在终端中使用了 python 编辑器(我使用 Ubuntu),然后我可以成功执行该程序,但当我从 PHP 脚本执行该程序时,不会发生这种情况。
最佳答案
如果您尝试引用现有的 arts.db
文件,而该文件在 PHP 脚本运行时不在当前目录中,那么最简单的方法可能是通过其完整路径引用该文件,即更改线路...
conn = sqlite3.connect('arts.db')
...类似...
conn = sqlite3.connect('/the/full/path/to/arts.db')
如果您尝试创建新的 arts.db
,则很可能 Web 服务器进程无权在 PHP 脚本运行时在当前目录中创建该文件。
不授予 PHP 写入包含 PHP 脚本的目录的权限可能更安全,因此在其他位置创建一个目录来存储文件,为其授予适当的权限,并使用该目录的完整路径脚本。
更新
i have figured out that i dont have permissions to write hence i created a db using another program and created a table in it but still for inserting values into it i require permissions, can you tell me how to do that?
问题是 PHP 脚本生成的任何进程都会继承父进程的权限,并且具有相同的限制。
在最新版本的 Ubuntu 上,/var/tmp
目录始终可以由任何用户写入,因此您可以将其放在那里...
conn = sqlite3.connect('/var/tmp/arts.db')
...或者您可以通过修改权限将其放在其他任何地方,...
$ sudo chgrp www-data /the/full/path/to/directory
$ sudo chmod g+ws /the/full/path/to/directory
当然,这意味着使用单独的 Python 脚本没有多大意义,因此您最好在 PHP 中完成这一切。
关于php - 从 PHP 调用 Python 但 SQLite3 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16119764/