我目前正在开发一个登录系统(通过使用两个文本字段来工作,然后用户被重定向)。然而,由于我正在开发一个移动应用程序,在JSON中这样做要容易得多,而且我也不完全确定从哪里开始。我主要想做的是使用https post请求(来自我的应用程序),这样它就会请求:https://www.example.com/login.php?username=username&password=password
我已经创建了一个基本示例,但这不是我希望通过URL传递参数的方法,因为我的代码目前只是在MySQL数据库中查找用户并以JSON输出用户。我想要做的是通过URL传入用户名和密码参数,然后输出一个“成功”或“错误”的JSON响应(如果用户名/密码是否在数据库中)。
<?php
$host = "localhost";
$username = "root";
$password = "password";
$db_name = "test";
$con = mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name") or die("cannot select DB");
$sql = "select * from test_table";
$result = mysql_query($sql);
$json = array();
if (mysql_num_rows($result))
{
while ($row = mysql_fetch_row($result))
{
$json['items'] = $row;
}
}
mysql_close($db_name);
echo json_encode($json, JSON_PRETTY_PRINT);
?>编辑
我现在已经开始了另一个系统的工作,这就是我想要做的事情(在这里找到了一个例子:http://www.dreamincode.net/forums/topic/235556-how-to-create-a-php-login-with-data-from-mysql-database/),除非每次我请求类似于https://www.example.com/login.php?username=root&password=password的东西--我得到JSON 1代码
<?php
$host = "localhost"; // Host name
$db_username = "root"; // Mysql username
$db_password = "password"; // Mysql password
$db_name = "test"; // Database name
$tbl_name = "test_table"; // Table name
// Connect to server
mysql_connect("$host", "$db_username", "$db_password") or die("cannot connect");
// Select the database
mysql_select_db("$db_name") or die("cannot select DB");
// Get the login credentials from user
$username = $_POST['username'];
$userpassword = $_POST['password'];
// Secure the credentials
$username = mysql_real_escape_string($_POST['username']);
$userpassword = mysql_real_escape_string($_POST['password']);
// Check the users input against the DB.
$query = "SELECT * FROM test_table WHERE user = '$username' AND password = '$userpassword'";
$result = mysql_query($query) or die("Unable to verify user because " . mysql_error());
$row = mysql_fetch_assoc($result);
if ($row['total'] == 1) {
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
}
else {
// username and password not found
// failed
$response["failed"] = 1;
// echoing JSON response
echo json_encode($response);
}
?>发布于 2015-06-29 23:08:50
试着改变下面的行,它应该可以工作。我让它开始工作,就像你描述的那样。
在这里,您将得到URL参数和消毒。
$username = $_GET['username'];
$userpassword = $_GET['password'];
$username = mysql_real_escape_string($username);
$userpassword = mysql_real_escape_string($userpassword);2-在这里,你数数你有多少行
改变$row = mysql_fetch_assoc($result);
转到$total_rows = mysql_num_rows($result);
3-在这里你检查你是否至少有一排。
并将if ($row['total'] == 1) {更改为if ($total_rows == 1) {
这应该给出输出{"success":1}
Note1: --这是为了解决您的请求和问题,但并不一定意味着正确的方法或一般的完美解决方案。
Note2: --我建议您考虑密码散列、post方法而不是get、使用mysqli或PDO来计算mysql和输入敏感信息,而不是使用传递用户名和密码。我建议您看看这个链接,它描述了我在note1中提到的一些东西。
http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
https://stackoverflow.com/questions/31106785
复制相似问题