Search code examples
php2captcha

Why can't these functions see my variable?


Why do I get this error:

Undefined variable key_2captcha

I run this code to pass a CAPTCHA to 2captcha server:

<?php
$id_Captcha=0;
$key_2captcha="key2captcha";
function send_captcha($base_file){

   $ch = curl_init("http://2captcha.com/in.php");
   curl_setopt($ch, CURLOPT_POSTFIELDS,
               array('method'=>"base64",
                     'key'=>$key_2captcha,
                     'numeric'=>1,
                     'max_len'=>1,
                     'body'=>$base_file,
                     'submit'=>'download and get the ID'));


   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);


   $postResult = curl_exec($ch);


   curl_close($ch);

   return $postResult;
}

function getSolveCaptcha($id_captcha){
  $c = curl_init("http://2captcha.com/res.php?key=".$key_2captcha."&action=get&id=".$id_captcha);
  curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
  $postResult = curl_exec($c);
  curl_close($c);
  return $postResult;
}
?>

I run this code in XAMPP.


Solution

  • Use below code use $key_2captcha with global. in both function. read variable scope in PHP

    function getSolveCaptcha($id_captcha){
      global $key_2captcha;
    
      $c = curl_init("http://2captcha.com/res.php?key=".$key_2captcha."&action=get&id=".$id_captcha);
      curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
      $postResult = curl_exec($c);
      curl_close($c);
      return $postResult;
    }