"Uncaught Error: Call to undefined method" - PHP [RESOLVIDO]

1. "Uncaught Error: Call to undefined method" - PHP [RESOLVIDO]

Rui Guilherme da Cunha
RuiGuilherme

(usa Manjaro Linux)

Enviado em 06/10/2017 - 23:33h

Cara, esse é meu ultimo recurso, já tentei de várias formas resolver esse problema....
Vou mostrar o erro completo: Uncaught Error: Call to undefined method usuarioDAO::enviaremail() in C:\44444444444\00000\88888888\registration.php:253
Stack trace:
#0 {main}
thrown


<?php
$POST = filter_input_array(INPUT_POST, FILTER_DEFAULT);
$SERVER = filter_input_array(INPUT_SERVER, FILTER_DEFAULT);
if(isset($POST['idCadastrar'])){
$usuario->setIdNome($POST['idNome']);
$usuario->setIdMail($POST['idMail']);
$usuario->setType_idtype($POST['type_idtype']);
$usuario->setIdSenha($POST['idSenha']);

/*Inicio do reCAPTCHA*/
$secret = "00000000000000000";
$response = null;
$reCaptcha = new ReCaptcha($secret);
if ($POST["g-recaptcha-response"]) {
$response = $reCaptcha->verifyResponse(
$SERVER["REMOTE_ADDR"],
$POST["g-recaptcha-response"]
);
}
/*Fim do reCAPTCHA*/
$mail = $usuarioDAO->enviaremail();
if ($response != null && $response->success) {

if (!$usuarioDAO->consultarEmail($POST['idMail'])) {

if($mail == true){

if($usuarioDAO->cadastrar($usuario)){
echo '<script type="text/javascript">';
echo 'setTimeout(function () {';
echo "swal({
title: 'Registration successfully Complete!',
text: 'Confirm the registration in your email, check spam folder!',
timer: 5000,
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
onOpen: function () {
swal.showLoading()
}
}).then(
function () {},
function (dismiss) {
if (dismiss === 'timer') {
window.location.href='index.php';
}
}
)";
echo '}, 10);';
echo '</script>';
}

else{
echo '<script type="text/javascript">';
echo 'setTimeout(function () { swal("OPS...!","There were some errors during registration, reload the page and try again!","error");';
echo '}, 10);</script>';
}

}
else{
echo '<script type="text/javascript">';
echo 'setTimeout(function () { swal("OPS...!","Failed to send confirmation for your email, try login and resend confimation! If the error recurs, contact dev of the site!","error");';
echo '}, 10);</script>';
}

}

else{
echo '<script type="text/javascript">';
echo 'setTimeout(function () { swal("OPS...!","Email in use, use other email!","error");';
echo '}, 10);</script>';
}

}

else {
echo '<script type="text/javascript">';
echo 'setTimeout(function () { swal("OPS...!","reCAPTCHA detected a spammer, FUCK $%#!","error");';
echo '}, 10);</script>';
exit;
}
}
?>



Meu problema está nessa parte: $mail = $usuarioDAO->enviaremail(); TODO resto funciona numa boa, fiz umas alterações, mas essa linha ficava em dentro do if do 'consultaremail', ele passa por todos os passos, menos o de enviar e-mail.


function enviaremail(usuario $entUsuario) {
try {
$idMail = $entUsuario->getIdMail();
//Create a new PHPMailer instance
$mail = new PHPMailer;
// Set PHPMailer to use the sendmail transport
$mail->isSendmail();
//Set who the message is to be sent from
$mail->setFrom('0000000000@heliohost.org');
//Set who the message is to be sent to
$mail->addAddress($idMail);
//Set the subject line
$mail->Subject = 'PHPMailer sendmail test';
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
$mail->addAttachment('images/phpmailer_mini.png');
if($mail->Send()){
return true;
}
else{
return false;
}
}
catch (PDOException $ex) {
echo "ERRO: {$ex->getMessage()}";
}
}


Essa aí é minha função dentro do usuariosDAO.php que está sendo chamada no registration.php e que está resultando no problema, todas as outras funções estão funcionando, tentanto solucionar eu peguei essa estrutura em exemples no github no phpmailer, pq achei que minha lógica para enviar o e-mail estaria errada, porém o erro continua o mesmo.


  


2. Re: Uncaught Error

Adiel Esdras Schonevald Tolentino
esdraschonevald

(usa Ubuntu)

Enviado em 07/10/2017 - 00:25h

Boa noite amigo,
Este erro acontece porquê o objeto usuarioDAO não foi instanciado. Está faltando uma linha chamando a classe
$usuarioDAO = new UsuarioDAO;

Caso o método enviaremail esteja definido como static você pode acessar sem instanciar a classe, desta forma
UsuarioDAO:: enviaremail ();


Tenta assim!


3. Re:

Rui Guilherme da Cunha
RuiGuilherme

(usa Manjaro Linux)

Enviado em 07/10/2017 - 10:06h

esdraschonevald escreveu:

Boa noite amigo,
Este erro acontece porquê o objeto usuarioDAO não foi instanciado. Está faltando uma linha chamando a classe
$usuarioDAO = new UsuarioDAO;

Caso o método enviaremail esteja definido como static você pode acessar sem instanciar a classe, desta forma
UsuarioDAO:: enviaremail ();


Tenta assim!


Obrigado por responder. ^^
Infelizmente não consegui resolver, mesmo usando o
UsuarioDAO:: enviaremail ();
:/

Retornou o mesmo problema, vou deixar o código completo do site incluindo o usuario.php e usuarioDAO.php:

Registration.php
<?php
require_once 'php/DAO/usuarioDAO.php';
require_once 'php/Ent/usuario.php';
$usuarioDAO = new usuarioDAO();
$usuario = new usuario();
require_once "php/DAO/recaptchalib.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chromatic Mods</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="css/bootstrap.css" />
<link rel="stylesheet" href="css/bootstrap-theme.css" />
<link rel="stylesheet" href="css/css.css" />
<link rel="stylesheet" href="css/sweetalert.min.css" />
<script src="js/js.js"></script>
<script src="js/jquery-3.2.1.min.js"></script>
<script src='https://www.google.com/recaptcha/api.js'></script>
<script src="js/sweetalert2.js"></script>
<script src="js/core.js"></script>
<script src="js/popper.min.js"></script>
<script src="js/bootstrap.js"></script>
</head>
<body>
<div class="hidden-xs">
<nav class="navbar navbar-inverse sidebar" role="navigation">
<div class="container-fluid">
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li>
<a class="navbar-brand toggle-btn toggle-whi" href="index.php">
Chromatic Mods
</a>
</li>
<li>
<a href="index.php">
Home
<span style="font-size:16px;" class="pull-right hidden-xs showopacity glyphicon glyphicon-home"></span>
</a>
</li>
<li>
<a href="free.php">
Free Mods
<span style="font-size:16px;" class="pull-right hidden-xs showopacity glyphicon glyphicon-gift"></span>
</a>
</li>
<li>
<a href="premium.php">
Premium Mods
<span style="font-size:16px;" class="pull-right hidden-xs showopacity glyphicon glyphicon-shopping-cart"></span>
</a>
</li>
<li>
<a href="freemium.php">
Freemium Mods
<span style="font-size:16px;" class="pull-right hidden-xs showopacity glyphicon glyphicon-credit-card"></span>
</a>
</li>
<li>
<a href="user.php">
Your Account
<span style="font-size:16px;" class="pull-right hidden-xs showopacity glyphicon glyphicon-user"></span>
</a>
</li>
</ul>
<center>
<p> </p>
<p>
<a class="esp" href="http://steamcommunity.com/app/271590/">Community GTA V</a>
</p>
<br />
<p>
<a class="esp" href="contact.php">About</a>
</p>
<p>
<a class="esp" href="terms.php">Terms</a>
</p>
<p>
<a class="esp" href="#">GitHub</a>
</p>
<br />
<br />
<br />
<br />
<p class="whiter"><span class="glyphicon glyphicon-copyright-mark"></span> Copyright. Developed by Rui</p>
</center>
</div>
</div>
</nav>
</div>
<!--- Nav for Mobile -->
<nav class="nav-bar navbar-inverse sidebar" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-sidebar-navbar-collapse-1">
<span class="sr-only">Navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand toggle-btn toggle-whi" href="index.php">
     Chromatic Mods
</a>
</div>
<div class="collapse navbar-collapse" id="bs-sidebar-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>
<a href="index.php">
Home
<span style="font-size:16px;" class="pull-right hidden-xs showopacity glyphicon glyphicon-home"></span>
</a>
</li>
<li>
<a href="free.php">
Free Mods
<span style="font-size:16px;" class="pull-right hidden-xs showopacity glyphicon glyphicon-gift"></span>
</a>
</li>
<li>
<a href="premium.php">
Premium Mods
<span style="font-size:16px;" class="pull-right hidden-xs showopacity glyphicon glyphicon-shopping-cart"></span>
</a>
</li>
<li>
<a href="freemium.php">
Freemium Mods
<span style="font-size:16px;" class="pull-right hidden-xs showopacity glyphicon glyphicon-credit-card"></span>
</a>
</li>
<li>
<a href="user.php">
Your Account
<span style="font-size:16px;" class="pull-right hidden-xs showopacity glyphicon glyphicon-user"></span>
</a>
</li>
</ul>
<center>
<p> </p>
<p>
<a class="esp" href="http://steamcommunity.com/app/271590/">Community GTA V</a>
</p>
<br />
<p>
<a class="esp" href="contact.php">About</a>
</p>
<p>
<a class="esp" href="terms.php">Terms</a>
</p>
<p>
<a class="esp" href="#">GitHub</a>
</p>
<br />
<br />
<br />
<br />
</center>
</div>
</div>
</nav>
<div class="main">
<div class="container auth">
<div id="big-form" class="well auth-box">
<form action="" method="post">
<fieldset>
<!-- Text input-->
<div class="form-group">
<label class=" control-label" for="idNome">Username</label>
<div class="">
<input id="idNome" name="idNome" placeholder="Your username" class="form-control input-md" type="text" required>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class=" control-label" for="idMail">Email</label>
<div class="">
<input id="idMail" name="idMail" placeholder="Your Email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" oninvalid="setCustomValidity('E-mail invalid')" oninput="setCustomValidity('')" class="form-control input-md" type="email" required>
</div>
</div>
<!-- Select Basic -->
<div class="form-group">
<label class=" control-label" for="type_idtype">Type Account</label>
<div class="">
<select id="type_idtype" name="type_idtype" class="form-control" required>
<?php
$nomeload = $usuarioDAO->nomeload();
$value = 0;
while($nome = $nomeload->fetch(PDO::FETCH_COLUMN)){
?>
<option value="<?php echo $value = $value +1; ?>"><?php print_r($nome);?></option>
<?php
}
?>
</select>
</div>
</div>
<!-- Password input-->
<div class="form-group">
<label class=" control-label" for="idSenha">Password</label>
<div class="">
<input id="idSenha" name="idSenha" placeholder="**********" class="form-control input-md" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" oninvalid="setCustomValidity('Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters')" oninput="setCustomValidity('')" type="password" required>
</div>
</div>
<!-- Password input-->
<div class="form-group">
<label class=" control-label" for="idCSenha">Confirm Password</label>
<div class="">
<input id="idCSenha" name="idCSenha" placeholder="**********" class="form-control input-md" type="password" required>
</div>
</div>
<!--Google ReCAPTCHA-->
<div class="form-group">
<div class="">
<div class="g-recaptcha" data-sitekey="0000000000000000000000000000"></div>
</div>
</div>
<!-- Button -->
<div class="form-group">
<div class="">
<button id="idCadastrar" type="submit" name="idCadastrar" class="btn btn-primary blackblal">Complete Register</button>
<span class="help-block">By registering you agree to the rules and terms of the site. Read the rules and terms here.</span>
</div>
</div>
</fieldset>
</form>
</div>
</div>
<br/>
<br/>
</div>
<?php
$POST = filter_input_array(INPUT_POST, FILTER_DEFAULT);
$SERVER = filter_input_array(INPUT_SERVER, FILTER_DEFAULT);
if(isset($POST['idCadastrar'])){
$usuario->setIdNome($POST['idNome']);
$usuario->setIdMail($POST['idMail']);
$usuario->setType_idtype($POST['type_idtype']);
$usuario->setIdSenha($POST['idSenha']);

/*Inicio do reCAPTCHA*/
$secret = "00000000000000000000000000";
$response = null;
$reCaptcha = new ReCaptcha($secret);
if ($POST["g-recaptcha-response"]) {
$response = $reCaptcha->verifyResponse(
$SERVER["REMOTE_ADDR"],
$POST["g-recaptcha-response"]
);
}
/*Fim do reCAPTCHA*/
if ($response != null && $response->success) {

if (!$usuarioDAO->consultarEmail($POST['idMail'])){

if($usuarioDAO-> enviaremail($POST['idMail'])){

if($usuarioDAO->cadastrar($usuario)){
echo '<script type="text/javascript">';
echo 'setTimeout(function () {';
echo "swal({
title: 'Registration successfully Complete!',
text: 'Confirm the registration in your email, check spam folder!',
timer: 5000,
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
onOpen: function () {
swal.showLoading()
}
}).then(
function () {},
function (dismiss) {
if (dismiss === 'timer') {
window.location.href='index.php';
}
}
)";
echo '}, 10);';
echo '</script>';
}

else{
echo '<script type="text/javascript">';
echo 'setTimeout(function () { swal("OPS...!","There were some errors during registration, reload the page and try again!","error");';
echo '}, 10);</script>';
}

}
else{
echo '<script type="text/javascript">';
echo 'setTimeout(function () { swal("OPS...!","Failed to send confirmation for your email, try login and resend confimation! If the error recurs, contact dev of the site!","error");';
echo '}, 10);</script>';
}

}

else{
echo '<script type="text/javascript">';
echo 'setTimeout(function () { swal("OPS...!","Email in use, use other email!","error");';
echo '}, 10);</script>';
}

}

else {
echo '<script type="text/javascript">';
echo 'setTimeout(function () { swal("OPS...!","reCAPTCHA detected a spammer, FUCK $%#!","error");';
echo '}, 10);</script>';
exit;
}
}
?>
<div class="hidden-sm hidden-lg">
<hr>
<footer class="container-fluid text-center">
<div class="col-md-12">
<p><span class="glyphicon glyphicon-copyright-mark"></span> Copyright. Developed by Rui</p>
</div>
</footer><!--Fim do rodapé-->
</div>
</body>
</html>

<script type="text/javascript">
var password = document.getElementById("idSenha")
, confirm_password = document.getElementById("idCSenha");

function validatePassword() {
if (password.value != confirm_password.value) {
confirm_password.setCustomValidity("Passwords Don't Match");
} else {
confirm_password.setCustomValidity('');
}
}

password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;
</script>


usuarioDAO.php
<?php
require_once 'php/Ent/usuario.php';
$usuario = new usuario();
require_once("Conexao.php");
include ('PHPMailer/PHPMailerAutoload.php');
require_once "recaptchalib.php";
class usuarioDAO {

function __construct(){
$this->con = new Conexao();
$this->pdo = $this->con->Connect();
}

function cadastrar(usuario $entUsuario) {
try{
$stmt = $this->pdo->prepare("INSERT INTO usuarios (idNome, idMail, type_idtype, idSenha) VALUES (:idNome, :idMail, :idType, :idSenha)");
$param = array(
":idNome" => $entUsuario->getIdNome(),
":idMail" => $entUsuario->getIdMail(),
":idType" => $entUsuario->getType_idtype(),
":idSenha" => $entUsuario->getIdSenha(),
);
return $stmt->execute($param);
}
catch (PDOException $ex){
echo "ERRO: {$ex->getMessage()}";
}
}

function nomeload(){
try {
$nomeload= $this->pdo->prepare ("SELECT Ctypes FROM contastypes");
$nomeload -> execute();
return $nomeload;
}
catch(PDOException $ex){
echo "ERRO: {$ex->getMessage()}";
}
}

function consultarEmail($idMail) {
try {
$stmt = $this->pdo->prepare("SELECT idMail FROM usuarios WHERE idMail = :idMail");
$stmt->bindValue(':idMail', $idMail);
$stmt->execute();
if ($stmt->rowCount() > 0) {
return true;
}
else {
return false;
}
}
catch (PDOException $ex) {
echo "ERRO: {$ex->getMessage()}";
}
}
}

function enviaremail(usuario $entUsuario) {
try {
$idMail = $entUsuario->getIdMail();
//Create a new PHPMailer instance
$mail = new PHPMailer;
// Set PHPMailer to use the sendmail transport
$mail->isSendmail();
//Set who the message is to be sent from
$mail->setFrom('chromaticmods@heliohost.org');
//Set who the message is to be sent to
$mail->addAddress($idMail);
//Set the subject line
$mail->Subject = 'PHPMailer sendmail test';
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
if($mail->Send()){
return true;
}
else{
return false;
}
}
catch (PDOException $ex) {
echo "ERRO: {$ex->getMessage()}";
}
}


Como pode ver o erro corre na hora de chamar a função "enviaremail", porém o código consegue chama a função consultarEmail que vem antes de enviaremail e que funciona perfeitamente, porém na hora que chega no terceiro if que é o
if($usuarioDAO-> enviaremail($POST['idMail'])){ CÓDIGO AQUI } 
ele da esse erro: Uncaught Error: Call to undefined method usuarioDAO::enviaremail() in C:\000000000000\1111111111\Chromatic Mods\registration.php:253
Stack trace:
#0 {main}
thrown


Edit 1:

function enviaremail($idMail) {
try {
//Create a new PHPMailer instance
$mail = new PHPMailer;
// Set PHPMailer to use the sendmail transport
$mail->isSendmail();
//Set who the message is to be sent from
$mail->setFrom('chromaticmods@heliohost.org');
//Set who the message is to be sent to
$mail->addAddress($idMail);
//Set the subject line
$mail->Subject = 'PHPMailer sendmail test';
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
if($mail->Send()){
return true;
}
else{
return false;
}
}
catch (PDOException $ex) {
echo "ERRO: {$ex->getMessage()}";
}
}


Fiz essa pequena alteração, o código anterior da função pegava o e-mail direito na entidade, nesse caso ele pega o e-mail do POST do if no registration.php.


4. RESOLVIDO

Rui Guilherme da Cunha
RuiGuilherme

(usa Manjaro Linux)

Enviado em 07/10/2017 - 10:34h

Era só pq minha função estava fora da classe. kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk MANO VOU ME MATAR kkkkkkkkkkkkkkkkkkkkkk Três dias tentanto arrumar essa [*****] pra descobrir que era uma coisa simples dessa. kkkkkkkkkk






Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts