Вопрос

Я некоторое время разрывал волосы с этим.

index.php:

$(document).ready(function(){ 
    $(".index_login_subm").click(function(){
        uid = $("input:username").val();
        pwd = $("input:password").val();
        $.post("backend/login.php",{
            uid:uid,
            pwd:pwd
        },function(data){
            alert("Returned data: " + data);
         });
        return false;
    });
});

Login.php:

include("../../settings.php");
echo $uid;
echo $_POST['uid'];

Ни одно из эхо ничего не возвращает.

settings.php:

foreach ($_POST as $key => $value) { 
   $$key = mysql_real_escape_string($value);
}
foreach ($_GET as $key => $value) { 
   $$key = mysql_real_escape_string($value); 
}

Код работает хорошо, если я прокомментирую настройки. У кого -нибудь есть представление о том, что я делаю не так?

index.php также включает настройки.php, если это имеет какое -либо значение.

РЕДАКТИРОВАТЬ: Сообщения ниже заставили меня хотеть уточнить; Пути все верны. Настройки. Они работают хорошо, когда обращаются к сценариям.

Это было полезно?

Решение

Как описано в руководстве PHP, mySQL_REAL_ESCAPE_STRING требует реального соединения базы данных, установленного с MYSQL_CONNECT (во втором параметре). Если нет, он пытается создать его, просто вызывая mysql_connect (). Если это тоже не работает, он возвращает ложь.

Итак, вам нужно сначала создать соединение с базой данных. Но прежде чем начать делать это: обратите внимание, это Действительно действительно плохая идея Просто взять каждый пост и получить переменную и выплюнуть его в глобальное пространство имен.

Другие советы

First, I would avoid the variable variables, they're really not necessary in this context and they make for a moving target if you're not sure what keys are actually reaching that script, and they're bad practice due to the security issues that they create. Instead, I would put the escaped values within settings.php into an array. Then you can simply var_dump() the array after including settings.php, and see what was available.

function extract_requests(){
    $res = array();
    foreach ($_REQUEST as $key => $value) { 
        if($key){
            $res[$key] = $value;
        }
    }
    return $res;
}

Second, manually call login.php with the correct url string, exactly what you would want the javascript to call for, so that you can be sure that any behavioral problems aren't coming from the login.php script itself.

http://localhost/somewhere/login.php?uid=50

include("../../settings.php");
$input = extract_requests();
var_dump($input);
echo $input['uid'];
echo $_POST['uid'];

Finally, I would check your data that you are sending in post(). I'm not a javascript guru, but

uid:uid,
 pwd:pwd

looks like it would cause issues to me, so it'd be good to make sure that your data is being sent in the way that you expect.

$(document).ready(function(){ 
    $(".index_login_subm").click(function(){
        uid = $("input:username").val();
        pwd = $("input:password").val();
        var inputData = {uid:uid, pwd:pwd};
        alert(uid+" "+pwd);
        // If you have a console.log() available, just use it on inputData here instead.
        $.post("backend/login.php",inputData
         ,function(data){
            alert("Returned data: " + data);
         });
        return false;
    });
});

Edit: Based on the mysql_real_escape_string-only-when-a-connection-has-been-initiated thing, I've removed the escaping from the code above, because really, you'll be better off escaping the stuff right before you put it into the sql.

In addition, keep in mind that using javascript for the login WILL come back to bite you, with functionality as basic and necessary as login, you don't want a javascript error to break any ability for a viewer to log in. Here it will do so.

Is there a valid mysql link?

string mysql_real_escape_string  ( string $unescaped_string
                                [, resource $link_identifier  ] )

If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

May be your error reporting setting ignores E_WARNING level errors.

index.php obviously is located in root directory of website, but the script that you are calling is in "backend" catalog.

Try using include_once instead of include and use absolute paths, not relative.

Example:

<?php
    include_once($_SERVER['DOCUMENT_ROOT']."/settings.php"); //absolute path to file
    echo $uid;
    echo $_POST['uid'];
?>

Using absolute paths will make life easier for you if you move files around.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top