Using same session ID in ajax can't connect to MySQL DB

☆樱花仙子☆ 提交于 2019-12-13 03:10:00

问题


I have made a generic PHP script to use for an AJAX call. I have the username and password for the mysql connection stored in SESSION variables. In order to start the same session in this ajax script, I pass the session ID via post to the ajax script. The variables are being passed correctly and I checked using error_log that the username and password SESSION variables are the correct values. Here is the ajax_script.php:

<?php

session_id($_POST['session_id']);
session_start();

mysql_connect('10.X.X.X',$_SESSION['username'],$_SESSION['password']);

$results = mysql_query($_POST['query']);

echo json_encode($results);

?>

However, the connection cannot be established. I checked the log file and this is the error:

 PHP Warning:  mysql_connect(): Access denied for user 'username'@'25.1.1.1' (using password: YES) in /ajax_script.php on line 6, referer: http://25.1.1.1/index.php?option=com_content&view=article&id=180

Does anyone know why I cannot connect like this?

Previously I made a similar script, but did NOT start the same session referencing the session_id like above. I passed user names and passwords via post, and the connection worked.

Thanks!

** EDIT ** Sorry, I used the wrong IP for the mysql connection. the following code works:

<?php

session_start();

$ajax_connection = mysql_connect('10.X.X.X',$_SESSION['username'],$_SESSION['password']);

$result_set = array();

while ($result_set[] = mysql_fetch_assoc($results)){
    // do nothing
}

echo json_encode($results);

?>

回答1:


You dont need to

session_id($_POST['session_id']);

Just session_start() is enough

Maybe your session is expiring on close. Use the following snippet on both pages

session_cache_expire(30); //expire in 30 minutes

Check this answer for more information on session expiring.



来源:https://stackoverflow.com/questions/9769795/using-same-session-id-in-ajax-cant-connect-to-mysql-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!