session_start(); is the first thing I call. There is no whitespace. Why am I still get this warning?
Screenshots:
Error:
[20-Feb-2014 16:52:32 America/New_York] PHP Warning: session_start(): Cannot send session cookie - headers already sent by (output started at /home/feyzprod/public_html/expertlookup.ca/index.php:1) in /home/feyzprod/public_html/expertlookup.ca/index.php on line 4
[20-Feb-2014 16:52:32 America/New_York] PHP Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /home/feyzprod/public_html/expertlookup.ca/index.php:1) in /home/feyzprod/public_html/expertlookup.ca/index.php on line 4
<?php session_start();
require_once('bdservice.php');
$bd = new BDService();
require_once('script.php');
if(!isset($_SESSION['specialiteBD']))
{
$sql = "SELECT * FROM Specialites";
try
{ $resultat = $bd->Select($sql); }
catch(Exception $e)
{ echo $e->getMessage(); }
if(count($resultat) != 0)
{
$newSpec= array();
foreach($resultat as $a)
{
$newSpec[] = utf8_encode($a[1]);
}
$_SESSION['specialiteBD'] = $newSpec;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Annuaire</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<link rel="stylesheet" href="css/style.css" />
<link rel="stylesheet" href="css/ico.css" />
<script src='js/validation.js'></script>
<script>
function initialize()
{
var input = document.getElementById('where');
var componentRestrictions = {country: 'ca'};
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.setComponentRestrictions(componentRestrictions);
}
google.maps.event.addDomListener(window, 'load', initialize);
$(function() {
var availableTags = [];
var ville = [];
var availableTags = <?php echo urldecode(json_encode($_SESSION['specialiteBD'])) ?>;
for(var i = 0; i < availableTags.length; i++)
{
ville.push(decode(availableTags[i]));
}
$( "#what" ).autocomplete({
minLength: 2,
source: function(req, responseFn) {
var re = $.ui.autocomplete.escapeRegex(req.term);
var matcher = new RegExp( "^" + re, "i" );
var a = $.grep( ville, function(item,index){
return matcher.test(item);
});
responseFn( a.slice(0,10));
}
});
});
</script>
</head>
<body>
<?php include_once("analyticstracking.php") ?>
<div class='headerBar'>
<div class='headerContent'>
<div id='logo'><a href='index.php'><img src='images/logo4.png' height='75' width='321' alt="Expert LookUp"/ title="Expert LookUp"/></a></div>
<div id='navLien'>
<table>
<tr>
<td>
<span>
<?php
if(isset($_SESSION['authentification']))
{
echo "<a href='logout.php'>déconnexion</a>
<a href='profil.php' class='blue_Button'>Profil</a>";
}
else
{
echo "<a href='enregistrement.php'>Ajouter votre entreprise</a>
<a href='connexion.php' class='blue_Button'>Connexion</a>";
}
?>
</span>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class='blur'>
<div class='blurContent'>
<div id='left'>
<p>Multiplier votre visibilité sur le web en vous inscrivant gratuitement sur notre moteur de recherche d'entreprise.</p>
<a href='enregistrement.php' class='blue_Button'>S'enregistrer</a>
</div>
<div id='right'>
<form action='search/index.php' method='get'>
<p>Trouvez un entrepreneur pour vos prochains travaux</p>
<div class='iconMan'><input type='text' name='what' id='what' size='40' placeholder="Que recherchez vous ? Ex : Plombier" required title="Veuillez indiquer votre critère de recherche." x-moz-errormessage="Veuillez indiquer votre critère de recherche." /></div><br/>
<?php
if(isset($_SESSION['invalideAdr']))
{
unset($_SESSION['invalideAdr']);
echo "<div class='iconWhere'><input type='text' style=\"border:1px solid red;\" name='where' id='where' size='40' placeholder=\"Impossible de trouver votre adresse !\" required title=\"Veuillez indiquer l\'emplacement de vos travaux.\" x-moz-errormessage=\"Veuillez indiquer l\'emplacement de vos travaux.\" /></div><br/>";
}
else
{
echo "<div class='iconWhere'><input type='text' name='where' id='where' size='40' required title=\"Veuillez indiquer l\'emplacement de vos travaux.\" x-moz-errormessage=\"Veuillez indiquer l\'emplacement de vos travaux.\" /></div><br/>";
}
?>
<div class='radio'>
<input type="radio" id="r1" name="secteur" value='1' />
<label for="r1"><span></span>Résidentiel</label>
<input type="radio" id="r2" name="secteur" value='2' />
<label for="r2"><span></span>Industriel</label>
<input type="radio" id="r3" name="secteur" value='3' checked="checked" />
<label for="r3"><span></span>Les deux</label><br/><br/>
<input type='hidden' name='page' value='1' />
<input type='submit' name='Rechercher' value='Rechercher' class='blue_Button' />
</div>
</form>
</div>
</div>
</div>
<div class='infoContent'>
<div id='info'>
<p>À propos d'Expert Lookup</p>
<span style='font-weight:bold;'>Information</span><br/>
<span>Expert LookUp est un annuaire se concentra principalement sur les entreprises dans le domaine de la construction.</span><br/><br/>
<span style='font-weight:bold;'>La simplicité même !</span><br/>
<span>Vous avez uniquement à choisir quel type d'entreprises/personnes vous recherchez, l'emplacement de votre travaux et le secteur d'activité pour faire votre recherche.
Les résultats de recherches vous seront affichées par ordre de distance et si une entreprise ne se déplace pas jusqu`à chez vous, elle ne sera pas affichée.</span><br/><br/>
<span style='font-weight:bold;'>Validation de la licence RBQ</span><br/>
<span>Nous vérifions directement à partir de la base de données de Gouvernement du Québec pour vérifier la licence RBQ des entreprises enregistrées sur notre annuaires.
Si une entreprise ne dispose pas de licence RBQ valide, cette information vous sera affichée.</span><br/><br/>
</div>
<div id='why'>
<p>Pourquoi s'enregistrer ?</p>
<table>
<tr>
<td><span>Soyez visible partout au Canada, auprès des millions d'internautes !</span></td>
<td><img src='images/blueEarth.png' width='97' height='97' alt='terre' title='terre' /></td>
</tr>
<tr>
<td><span>Expert LookUp est un annuaire entièrement gratuit, aucun frais caché !</span></td>
<td><img src='images/greenMoney.png' width='97' height='97' alt='terre' title='terre' /></td>
</tr>
<tr>
<td><span>Votre inscription prendra moins de 5 minutes, alors qu'attendez-vous ? Vous n'avez rien à perdre !</span></td>
<td><img src='images/clock.png' width='97' height='97' alt='terre' title='terre' /></td>
</tr>
</table>
</div>
</div>
<div class='footerBar'>
<div class='footerContent'>
<a href='contact.php'>Contactez-nous</a><span> | </span>
<a href='enregistrement.php'>Ajouter votre entreprise</a><span> | </span>
<a href='connexion.php'>Connexion</a><span> | </span>
<a href='aide.php'>Aide</a><br/>
<span>© Copyright at ExpertLookUp.ca</span>
</div>
</div>
</body>
</html>
No need to check if your session_start() has already started or not. session_start() will just use the current session if there is one.
PHP Doc:
session_start() creates a session or resumes the current one based on
a session identifier passed via a GET or POST request, or passed via a
cookie.
Link
About the error you're receiving, I'm guessing this is due to the IF-Statement lines above it.
Well, that is probably because you already started session somewhere. I usually made solution by putting # before session_start and error was silent and session also worked.
So, #session_start(); may be solution.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 days ago.
Improve this question
here is my issue.
I made a login page with a variable that counts the number of attempts. This variable increments itself each time the user credentials are wrong.
I use this variable to disable the account if the user tries more than 5 times. Everything works but, if the user goes back to the previous page, he goes back to the last submit and the variable is decremented. With this issue, he can have unlimited attempts if he goes back everytime to the last page.
Can you help me please?
Here is my code.
<?php
// Le nombre de tentatives est placé dans le formulaire en renvoyé en post
if(isset($_POST['failurecount'])) {
$failcount = $_POST['failurecount'];
} else {
$failcount = 1;
}
if(isset($_POST['login_email']) && isset($_POST['mdp'])) {
$login_email = $_POST['login_email'];
$mdp = $_POST['mdp'];
$result = $wpdb->get_results("SELECT login, email, mdp FROM `wp_clients_user` WHERE (`login` = '$login_email' OR `email` = '$login_email') AND actif = 1", ARRAY_A);
if($wpdb->last_error) {
echo 'wpdb error: ' . $wpdb->last_error;
}
if($failcount < 5) {
if(empty($result)) {
$failure = "Erreur, le nom d'utilisateur ou le mot de passe est incorrect, vérifiez les données saisies! Nombre de tentatives : ". $failcount;
$failcount++;
} else {
foreach($result as $row) {
if(password_verify($mdp, $row['mdp'])) {
$_SESSION['login'] = $row['login'];
} else {
$failure = "Erreur, le mot de passe est incorrect, veuillez vérifier le mot de passe saisi! Nombre de tentatives : " . $failcount;
$failcount++;
}
}
}
} else {
// On ne bloque que si le nombre de tentatives est = 5 car sinon, il bloquera tous les comptes qe l'utilisateur entrera après avoir été bloqué
if ($failcount == 5) {
// Si l'utilisateur s'est trompé trop de fois
$failure = "Erreur! Votre compte a été bloqué suite à un trop grand nombre d'échecs!";
$wpdb->query("UPDATE wp_clients_user SET actif = 0 WHERE `login` = '$login_email' OR `email` = '$login_email'", ARRAY_A);
blocked_account($login_email);
$failcount++;
} else { // Si l'utilisateur continue d'essayer de se connecter, on ne fait plus rien (pas de connexion ou de bloquge)
$failure = "Toutes vos prochaines tentatives de connexion ne seront pas prises en compte! Nombre de tentatives : " . $failcount;
$failcount++;
}
?>
<form id="login_form" method="post" onsubmit="return false">
<input type="hidden" name="failurecount" value="<?php if(isset($failcount)){echo $failcount;}else{echo 1;} ?>">
<input id="login_email" name="login_email" type="text" value="<?php echo $login_email; ?>" placeholder="Nom d'utilisateur ou adresse e-mail *">
<input id="mdp" name="mdp" type="password" value="<?php echo $mdp; ?>" placeholder="Mot de passe *">
<p>Mot de passe oublié?</p>
<div>
<input id="showpwd" type="checkbox" onclick="show_password()"><label for="showpwd">Afficher le mot de passe</label>
</div>
<?php
if($failure !== false) {
echo('<p style="color: red;">'.htmlentities($failure)."</p>\n");
}
?>
<div>
<input id="souvenir" type="checkbox"><label for="souvenir">Se souvenir de moi</label>
</div>
<button class="bouton_submit" id="user_send_login" style="background-color:#3498db; color:white; width:100px; height:35px;" onclick="verif_login_form()">Se connecter</button>
</form>
I have a problem with my form, when I get in my website with Xampp, the webpage is not completed, doesn't appear the "region" combo box, the "fono" text field and the buttons, I don't know why it happens :( I wonder if someone could help me with this issue, please, as I fixed the bracket problems, now this problem is really freaking me out indeed.
<!DOCTYPE html>
<html>
<head>
<title>Formulario de datos</title>
<meta charset="UTF-8">
<script src="js/jquery.js"></script>
<script src="js/NumeroLetra.js"></script>
<script src="js/Hora.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/jquery.Rut.js"></script>
<script src="js/jquery.validate.js"></script>
</head>
<body onLoad="IniciarReloj24()">
<?php
ini_set('error_reporting',0);
include ('funciones.php');
?>
<form action = " " method="post">
<?php
//comprobamos el evento del boton
if ($_POST['btnRutBuscar'] == "Buscar"){
$cnn = Conectar();
//concatenamos los inputs para realizar el formato del rut
$rutt = $_POST['txtRut']."-".$_POST['txtDigito'];
//sentencia sql anidada entre registro y regiones
$sql = "select re.rut, re.nombres, re.apellidos, re.fnac, re.sexo, r.id, r.region, re.fono from registro re, regiones r where (re.region = r.id) and (re.rut = '$rutt')";
$rs = mysqli_query($cnn, $sql);
while ($row = mysqli_fetch_array($rs)){
$rut = $row['rut'];
$nom = $row['nombres'];
$ape = $row['apellidos'];
$fna = $row['fnac'];
$sex = $row['sexo'];
//recogemos el id de la tabla regiones que sera utilizada en el combo box de regiones
$id = $row['id'];
$reg = $row['region'];
$fon = $row['fono'];
//se les añade los value a los inputs para poder recibir los valores de la base de datos
}
}
?>
<center><h1>Formulario de datos: todo en uno</h1></center>
<center><h2>Creado por Matías Cáceres y Francisco Tello</h2></center>
<br>
<br>
<div align="center"><label>Rut:</label>
<input type="text" name="txtRut" id="txtRut" onkeypress="ValidaSoloNumeros()" value="<?php echo $rut?>" /> -
<input type="text" name="txtDigito" id="Verificador" size="2" onkeypress="ValidaSoloNumeros()" />
<input type="submit" name="btnRutBuscar" id="btnBuscar" value="Buscar" /></div>
<br>
<br>
<div align="center"><label>Nombres:</label>
<input type="text" name="txtNombres" id="txtNombres" onkeypress="txNombres()" value="<?php echo $nom ?>" />
<br>
<br>
<div align="center"> <label>Apellidos:</label>
<input type="text" name="txtApellidos" id="txtApellidos" onkeypress="txNombres()" value="<?php echo $ape ?>"/>
<br>
<br>
<div align="center"><label>Fecha de Naciemiento:</label>
<input type="date" name="txtFecha" value="<?php echo $fnac ?>" />
<br>
<br>
<div align="center"><label>Sexo:</label>
<select name="txtSexo">
<option value=""><?php $sex ?></option>
<option value = "Masculino">Masculino</option>
<option value = "Femenino">Femenino</option>
</select></div>
<br>
<br>
<div align="center"><label>Región:</label>
<?php
$cnn=Conectar();
$sql="select region from regiones";
$rs = mysqli_query($cnn,$sql); ?>
<select name="txtRegion">
<option value=""><?php echo $reg ?></option>
<?php while ($row=mysqli_fetch_array($rs))
{echo '<option>'.$row["region"];}
?>
</select>
</div>
<br>
<br>
<div align="center"><label>Fono:</label>
<input type="text" name="txtFono" id="txtFono" onkeypress="ValidaSoloNumeros()" value="<?php echo $fon ?>" />
</div>
<br>
<br>
<table>
<td><input type="submit" name="btnAgregar" id="btnAgregar" value="Agregar"/></div></td>
<td><input type="submit" name="btnModificar" id="btnModificar" value="Modificar"/></div></td>
<td><input type="submit" name="btnEliminar" id="btnEliminar" value="Eliminar"/></div></td>
<td><input type="submit" name="btnVerTodos" id="btnVerTodos" value="Ver Todos"/></div></td>
</table>
<?php
if($_POST['btnAgregar']=="Agregar")
{
$cnn = Conectar();
$rutt = $_POST['txtRut']."-".$_POST['txtDigito'];
$nom = $_POST['txtNombres'];
$ape = $_POST['txtApellidos'];
$fna = $_POST['txtFecha'];
$sexo = $_POST['txtSexo'];
$reg = $_POST['txtRegion'];
$fon = $_POST['txtFono'];
$sql = "insert into registro values('$rutt','$nom','$ape','$fna','$sexo','$reg','$fon')";
//este if lo acabo de colocar, es mas que nada para saber si ocurrio algo malo al momento de ejecutar la funcion (***** El if es necesario en todos los botones*****)
#Comprobar el nombre de las variables
if (empty($rut) || empty($nom) || empty($ape) || empty($fnac) || empty($sex) || empty($reg) || empty($fon)) {
echo "<script>alert('Todos los campos son obligatorios');</script>";
if( mysqli_query($cnn,$sql)){
echo "<script>alert('Se han grabado los datos')</script>";
echo "<script>window.location='index.php'</script>";
}else{
echo "<script>alert('ocurrio un problema');</script>";
}
}
}
if($_POST['btnEliminar']=="Eliminar")
{
$cnn = Conectar();
$rut = $_POST['txtRut']."-".$_POST['txtDigito'];//es necesario concadenar los dos inputs para que funcione la consulta
$sql = "delete from registro where (rut = '$rut')";
mysqli_query($cnn,$sql);
echo "<script>alert('Se eliminó el registro')</script>";
}
if($_POST['btnModificar']=="Modificar")
{
$cnn = Conectar();
$rutt = $_POST['txtRut']."-".$_POST['txtDigito']; //es necesario concadenar los dos inputs para que funcione la consulta
$nom = $_POST['txtNombres'];
$ape = $_POST['txtApellidos'];
$fna = $_POST['txtFecha'];
$sex = $_POST['txtSexo'];
$reg = $_POST['txtRegion'];
$fon = $_POST['txtFecha'];
$sql = "update registro set nombres='$nom', apellidos='$ape', fnac='$fna', sexo='$sex', region='$reg', fono='$fon' where rut='$rutt'";
mysqli_query($cnn,$sql);
echo "<script>alert('Se han editado los datos')</script>";
}
?>
</form>
<table border = '1'>
<tr>
<?php date_default_timezone_set('America/Santiago');
$vaFecha = date('d-m-y');
?>
<td>Fecha</td>
<td><input type = "text" name="caja_fecha" value = "<?php echo $vaFecha; ?>" disabled="disabled"></td>
</tr>
</table>
<form name="reloj24">
<input type="text" size="8" name="digitos" value=" " disabled="disabled">
</form>
<script>
$('#txtRut').Rut( {
digito_verificador: '#Verificador',
on_error: function(){ alert('Rut incorrecto');
$("#txtRut").val("");
$("#Verificador").val("");
}
} );
</script>
</body>
</html>
enter image description here
I'm trying to populate some inputs depending by other inputs, but when i fill the first input thishow me an error of problems to connect with the data base
this is my HTML
<!doctype html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>POC Ajax Cliente</title>
</head>
<body>
<div id="cliente">
<form action="" method="POST">
<label for="nombre">Nombre</label>
<input type="text" id="nombre" name="nombre" value="" placeholder="Nombre.." />
<br />
<label for="direccion">Dirección</label>
<input type="text" id="direccion" name="direccion" value="" placeholder="Dirección.." />
<br />
<label for="telefono">Teléfono</label>
<input type="text" id="telefono" name="telefono" value="" placeholder="Teléfono..." />
</form>
</div>
<div id="estado">Esperando input.</div>
<!-- Scripts -->
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script type="text/javascript" src="cliente.js"></script>
</body>
</html>
this is my client.js
$(function(){
/* Ponemos evento blur a la escucha sobre id nombre en id cliente. */
$('#cliente').on('blur','#nombre',function(){
/* Obtenemos el valor del campo */
var valor = this.value;
/* Si la longitud del valor es mayor a 2 caracteres.. */
if(valor.length>=3){
/* Cambiamos el estado.. */
$('#estado').html('Cargando datos de servidor...');
/* Hacemos la consulta ajax */
var consulta = $.ajax({
type:'POST',
url:'cliente.php',
data:{nombre:valor},
dataType:'JSON'
});
/* En caso de que se haya retornado bien.. */
consulta.done(function(data){
if(data.error!==undefined){
$('#estado').html('Ha ocurrido un error: '+data.error);
return false;
} else {
if(data.telefono!==undefined){$('#cliente #telefono').val(data.telefono);}
if(data.direccion!==undefined){$('#cliente #direccion').val(data.direccion);}
$('#estado').html('Datos cargados..');
return true;
}
});
/* Si la consulta ha fallado.. */
consulta.fail(function(){
$('#estado').html('Ha habido un error contactando el servidor.');
return false;
});
} else {
/* Mostrar error */
$('#estado').html('El nombre tener una longitud mayor a 2 caracteres...');
return false;
}
});
});
and this is my client.php where i make the consult from the DB
<?php
require 'config/Conexion.php';
if(!empty($_POST['nombre'])){
$nombre = $_POST['nombre'];
$sql = "SELECT * FROM usuarios WHERE nombre = '.$nombre.'";
$stmt = $pdo->prepare($sql);
$stmt ->execute();
$arrDatos = $stmt->fetchAll(PDO::FETCH_ASSOC);
if($arrDatos){
foreach ($arrDatos as $row) {
$return = array ('telefono' => $row['telefono'], 'direccion' => $row['direccion']);
}
} else {
$return = array('error'=>'El nombre no esta guardado en la base de datos');
}
die(json_encode($return));
}
when i put something in the first input the message that apears is that there was a problem with the connection to the Data Base
bringing trouble again, I have a PHP form with which I receive information (name and email) and send the information by email and in turn allows downloading a file with JS validation, if I remove sending email, save the information in MySQL but if I put sending mail, do not save the info ...
Here´s the code from index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Muestra Gratuita</title>
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="shortcut icon" href="img/favicon.ico">
<div id="fb-root"></div>
<script type="text/javascript">
function validar(){
var copia = document.getElementById("txtcopia").value;
var captcha = document.getElementById("captcha").value;
if (copia == captcha) {
window.open("muestra/Corazon_prodigo.pdf", "_blank");
}else{
alert("El codigo ingresado no coincide");
}
}
</script>
<script type="text/javascript">
document.oncontextmenu = function(){return false;}
</script>
</head>
<body>
<div class="container" style="padding-top : 50px;">
<div class="row">
<div class="col-md-6">
<div class="display-block">
<img class="img-responsive center-block" src="img/muestra.jpg">
</div>
</div>
<div class="col-md-6">
<p class="lead">
Por favor completa el formulario para que puedas descargar
<strong>GRATIS</strong>
una muestra (Primeras páginas) del libro Corazón Pródigo:
<br>
</p>
<div class="alert" style="display: none" role="alert"></div>
<form class="email-form" method="POST" action="send.php">
<div class="form-group">
<label for="name">Nombre Completo</label>
<input class="form-control" name="name" type="text" required>
</div>
<div class="form-group">
<label for="email">Email</label>
<input class="form-control" name="email" type="email" required>
</div>
<br>
<label class="lead" for="txtcopia">Introduce el texto del campo de abajo</label>
<input class="form-control" type="text" name="txtcopia" id="txtcopia" size="10">
<br>
<br>
<input class="captcha" type="text" name="captcha" id="captcha" value=<?php echo captcha(); ?> size="8" readonly>
<br>
<br>
<br>
<button id="buscarbtn" class="btn btn-success" type="submit" value="registrar" name ="buscarbtn" onclick="validar();">Suscribirse</button>
<br>
<br>
<a class="download_button btn btn-lg btn-success center-block" style="display:none" download="" href="muestra/Corazon_prodigo.pdf">Descarga Ahora</a>
</form>
</div>
</div>
</div>
</body>
</html>
<?php
#error_reporting(0);
$sqlhost = 'localhost';
$sqluser = 'root';
$sqlpass = '';
$sqldb = 'registro';
$sqltable= 'registro';
function captcha() {
$k="";
$param="1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$max=strlen($param)-1;
for ($i=0; $i<6; $i++) {
$k.=$param{mt_rand(0,$max)};
}
return $k;
}
$db = mysqli_connect($sqlhost, $sqluser, $sqlpass, $sqldb); //Nuestra variable para establecer la conexión a la base de datos
if(!$db){die("Error al conectar con la db" . mysql_error());}
$name = isset($_POST['name']) ? $_POST['name'] : NULL; // Tomamos el texto del input "nombre"
$email = isset($_POST['email']) ? $_POST['email'] : NULL; // Tomamos el texto del input "apellido"
$date = date('Y-m-d');
// Insertaremos la información a la tabla Nombre y Apellido, donde VALUES declara el texto que ingresaremos
$query = "INSERT INTO ".$sqltable."(name, email, date) VALUES('".$name."', '".$email."', '".$date."');";
mysqli_select_db($db,$sqldb); //verificaremos la conexión a nuestra base de datos
$insert_value = mysqli_query($db, $query); // Declaramos la variable $insert_value para usarla cómo un bool, en caso de que esta consulta falle
if(!$insert_value) //Crearemos la consulta
die('Error: ' . mysqli_error($db)); // Si falla, nos mostrará este texto, seguido del error.
mysqli_close($db); // Detenemos la conexión de la base de datos
?>
Here´s the code from send.php:
<?php
$para = "example#example.com";
require 'PHPMailerAutoload.php';
$mail=new phpmailer();
$mail->PluginDir = "includes/";
$mail->Mailer = "smtp";
$mail->Host = "mail.example.com";
$mail->SMTPAuth = true;
$mail->Username = "contact#example.com";
$mail->Password = "H1hs4h45";
$mail->From = "contact#example.com";
$mail->FromName = "contacto WEB";
$mail->Timeout=30;
$mail->AddAddress($para);
$mail->Subject = "NUEVO USUARIO REGISTRADO";
$mail->Body = $_POST['name'].chr(13).chr(10).$_POST['email'];
$mail->IsHTML(true);
if($mail->Send())
{
echo'<script type="text/javascript">
alert("Enviado Correctamente");
window.location="http://example.com/index.php"
</script>';
}
else{
echo'<script type="text/javascript">
alert("NO ENVIADO, intentar de nuevo");
window.location="http://example.com/index.php"
</script>';
}
?>
So the question is, how can I run the email sending and turn to save the information in MySQL at the same time?
Because, if I put send.php content in the same file index.php or vice versa, when the page loads it generates a loop and sends email every 30 seconds, and I forgot to say, when the email are sent, it generates a MySQL row but it is empty...
I've got two websites with the same content. One is with ".com" and the other one is ".nc".
I've got this php page:
<?php
// si le mot de passe est posté
if(isset($_POST["motpasse"])){
// si la valeur du mot de passe est bien celle qu'il faut
if($_POST["motpasse"] == "pass") {
header ("Location: dernier.php");
exit();
}else {echo "Mauvais mot de passe";}
}
echo ('<p align="center"><font size=6pt>Veuillez saisir
votre mot de passe: <br></p></font>');
echo '<form name="motdepasse" method="post"
action="' . htmlspecialchars($_SERVER['REQUEST_URI']) . '">';
echo ('<p align="center"><input type=password name="motpasse"
size="5" style="height:60px; width:160px" value="" /></p>');
echo ('<p align="center"><input type="submit"
name="action onClick=(this.form)"
style="height:60px; width:160px"value="OK"></p>');
echo '</form>';
?>
Weirdly, the header function is working on the website ".com" but not on the website ".nc"
When I type the password, the header doesn't redirect me on the php page that I've put ("dernier"). Any idea why?
Is correct what JackBauer told you about the headers sent. another solution some nasty is this:
<?php
// si le mot de passe est posté
if(isset($_POST["motpasse"])){
// si la valeur du mot de passe est bien celle qu'il faut
if($_POST["motpasse"] == "pass") {
echo "<meta http-equiv="refresh" content="0;url=dernier.php">";
/*header ("Location: dernier.php"); */
exit();
}else {echo "Mauvais mot de passe";}
}
echo ('<p align="center"><font size=6pt>Veuillez saisir votre mot de passe: <br></p></font>');
echo '<form name="motdepasse" method="post" action="' . htmlspecialchars($_SERVER['REQUEST_URI']) . '">';
echo ('<p align="center"><input type=password name="motpasse" size="5" style="height:60px; width:160px" value="" /></p>');
echo ('<p align="center"><input type="submit" name="action onClick=(this.form)" style="height:60px; width:160px"value="OK"></p>');
echo '</form>';
?>
But maybe the principal thing that is failing in your script is the action in your form.
with firebug review your scaped html code in your client side. (what u r seeing in your browser {font code})
see ya!