ajax didn't call the server php program - php

I am quite new in the programming and I try to check if a shop has been already assigned to an user. if yes nobody can be assigned to this shop anymore.
so in the index file I make a call via $.ajax of searchunicusershop.php but it didn't seem to call it.
in index.php
unic = {};
data = "siret=" + $('#siret').val() + "&emllog=" + $('#email_login').text();
$.ajax({
type: 'GET',
url: 'searchunicusershop.php',
data: data,
dataType: 'json',
success: function(result, statut) {
unic = {};
unic = result;
if (unic.response == false) {
if (unic.status == 'alreadyassign') {
$('.messmenu').text('shop already assigned');
$('.profile-card-pro').scrollTop(0);
}
}
},
error: function(result, statut, erreur) {
console.log(statut);
console.log(erreur);
},
complete: function(result, statut, erreur) {
}
});
the searchunicusrshop.php
<?php
header("Content-Type: application/json ; charset=utf-8");
header("Cache-Control: no-cache , private");
header("Pragma: no-cache");
$email_login = ' ';
$siret = ' ';
$siren = ' ';
$nic = ' ';
$res1 = ' ';
$res2 = ' ';
$res3 = ' ';
$tunic=[];
$tunic['emllog'] = ' ';
$tunic['siret'] = ' ';
$tunic['status'] = 'false';
$tunic['shopid'] = ' ';
$tunic['admid'] = ' ';
$tunic['emladm'] = ' ';
$tunic['response'] = false;
$shopshop_id = ' ';
$hasshopuser_id = ' ';
$usersuser_email = ' ';
var_dump ($_GET);
require_once('connexionMysqlCheck.php');
if ($connected) {
require_once('connexionMysql.php');
if (isset($_GET['siret']) && isset($_GET['emllog'])) {
$email_login = $_GET['emllog'];
$tunic['emllog'] = $email_login;
$tunic['siret'] = $_GET['$siret'];
$tunic['status'] = 'paramfull';
$siret = $_GET['siret'];
$siren = substr($siret, 0, 9);
$nic = intval(substr($siret, 9, 5));
// Recherche du shop_id avec siret pour accéder ) user_has_shop
$query1="SELECT shop_id FROM shop WHERE siren = ".$siren." and nic = ".$nic."";
var_dump ($query1);
$res1=mysqli_query($connexion,$query1) or die('Erreur SQL !<br />'.$query1.'<br />'.mysqlerror());
if (mysqli_num_rows($res1)>0) { // si le shop est trouvé
while ( $enreg=mysqli_fetch_array($res1) ) { // récupérer le shop_id
$shopshop_id = $enreg['shop_id'];
$tunic['shopid'] = $enreg['shop_id'];
$tunic['status'] = 'shopfound';
mysql_free_result ($res1);
// si shop_id trouvé alors recherche du user_id avec le shop_id dans la table user_has_shop
$query2="SELECT user_id FROM user_has_shop WHERE shop_id = ".$shopshop_id." and shop_admin = 1";
echo $query2;
$res2=mysqli_query($connexion,$query2) or die('Erreur SQL !<br />'.$query2.'<br />'.mysqlerror());
if (mysqli_num_rows($res2)>0) { // s'il y a une association qui existe pour ce shop
while ( $enreg=mysqli_fetch_array($res2) ) { // récupérer le user_id qui est associé dans users has shop
$hasshopuser_id = $enreg['user_id'];
$tunic['admid'] = $hasshopuser_id;
$tunic['status'] = 'assocfound';
mysql_free_result ($res2);
// Recherche si l'utilisateur via son email existe dans users
$query3="SELECT email_login FROM users WHERE user_id = '".$hasshopuser_id"'";
echo $query3;
$res3=mysqli_query($connexion,$query3) or die('Erreur SQL !<br />'.$query3.'<br />'.mysqlerror());
if (mysqli_num_rows($res3)>0) { // si l'utilisateur est trouvé
while ( $enreg=mysqli_fetch_array($res3) ) { // récupérer le user_id de users
$usersuser_email = $enreg['email_login'];
$tunic['emladm'] = $useruser_email;
$tunic['status'] = 'admassocfound';
mysql_free_result ($res3);
if ($email_login == $useruser_email) { // si le shop est déjà associé à lui alors ok
$tunic['status'] = 'assochimself';
$tunic['responses'] = true;
} else { //si il y a déjà une association mais à quelqu'un d'autre alors il ne peut pas
$tunic['status'] = 'alreadyassign';
$tunic['response'] = false;
}
} // fin de while pour récupérer lemail du user associé dans users query3 ***********************
} else {
$tunic['admid'] = $hasshopuser_id;
$tunic['emladm'] = ' ';
$tunic['status'] = 'admnotfoundcritical';
$tunic['response'] = false;
} // si l'utilisateur adm n'est pas trouvé user, c'est pas normal
} // fin de while pour récupérer le user_id de user_has_shop query2 ***********************
} else { // si pas assoc alors c'est bon
$tunic['admid'] = ' ';
$tunic['emladm'] = ' ';
$tunic['status'] = 'noassocfound';
$tunic['response'] = true;
} // si pas d'association alors c'est bon
} // fin while récupérer shop_id query1 uy**************************************
} else { // si le shop_id n'est pas trouvé dans shop ne rien faire c'est false
$tunic['status'] = 'siretnotfound';
$tunic['shopid'] = ' ';
$tunic['admid'] = ' ';
$tunic['emladm'] = ' ';
$tunic['response'] = false;
}// si le shop_id n'est pas trouvé dans shop ne rien faire c'est false
} else { // ne trouve pas not isset. l'un des 2 ou les 2 paramètres email et/ou siret est vide (sont vides)
$tunic['emllog'] = $_GET['emllog'];
$tunic['siret'] = $_GET['siret'];
$tunic['status'] = 'paramempty';
$tunic['shopid'] = ' ';
$tunic['admid'] = ' ';
$tunic['emladm'] = ' ';
$tunic['response'] = false;
} // fin not isset
} // connecté
$result = $tunic;
echo json_encode($result);
?>
I don't know if the index call it or not, if it was successful or in error. I try to debug via chrome but it went through this code but I didn't get any ajax status or result.
Thank you in advance for your help.

I found where the issue is :
$query3="SELECT email_login FROM users WHERE user_id = '".$hasshopuser_id"'";
it should be this instead :
$query3="SELECT email_login FROM users WHERE user_id = ".$hasshopuser_id;

Related

My php code loops and doesn't explore my database [duplicate]

This question already has answers here:
The 3 different equals
(5 answers)
Closed 1 year ago.
Hello I'm currently trying to create a page based on a database under mysql that would update itself for a client. However what I'm trying to do loops and returns the first value of the database each time and indefinetely when I want it to go on to another object in the database. Here is the code, I'm a beginner so the error might be flagrant, thanks for the help.
<?php
try
{
$db = new PDO('mysql:host=localhost;dbname=labase', 'root' ,'');
$db->exec(" SET CHARACTER SET utf8 ");
$db->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e){
echo'une erreur est survenue';
die();
}
for ($i = 1; $i < 10; $i++) {
if ($i=1){
$select = $db->prepare("Select profession from contact where affiliation='nord' group by profession"); // je récupère les professions de la bdd
$select->execute();
}
$data = $select->fetch(PDO::FETCH_OBJ);
$profess=$data->profession; // je prends la prochaine profession
$selectionner = $db->prepare("Select nomcontact, count(*) as nbrcontact from contact where affiliation='nord' and profession='$profess'"); // je prends les contacts qui ont cette profession ainsi que leur nombre
$selectionner->execute();
$prendre = $selectionner->fetch(PDO::FETCH_OBJ);
$nbrcontact=$prendre->nbrcontact;// je récupère leur nombre
echo $profess;
echo $nbrcontact;
}
?>
I am not a PHP expert and never use PDO, but in Msqli, there is a fetch_array() to get multiple result (instead of fetch for single result), maybe in PDO you have a fetch_array too. Then, you can loop on the result array
Something like that (using msqli)
$sql = "SELECT... FROM ..";
$result = $link->query($sql);
while($row =mysqli_fetch_array($result))
{
}
if ($i=1) { // here is should be == or ===
You're causing an infinite loop by declaring $i=1
<?php
try
{
$db = new PDO('mysql:host=localhost;dbname=labase', 'root' ,'');
$db->exec(" SET CHARACTER SET utf8 ");
$db->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e){
echo'une erreur est survenue';
die();
}
for ($i = 1; $i < 10; $i++) {
if ($i == 1){ // added code
$select = $db->prepare("Select profession from contact where affiliation='nord' group by profession"); // je récupère les professions de la bdd
$select->execute();
}
$data = $select->fetch(PDO::FETCH_OBJ);
$profess=$data->profession; // je prends la prochaine profession
$selectionner = $db->prepare("Select nomcontact, count(*) as nbrcontact from contact where affiliation='nord' and profession='$profess'"); // je prends les contacts qui ont cette profession ainsi que leur nombre
$selectionner->execute();
$prendre = $selectionner->fetch(PDO::FETCH_OBJ);
$nbrcontact=$prendre->nbrcontact;// je récupère leur nombre
echo $profess;
echo $nbrcontact;
}
?>
Use == for comparison

Mobilpay return error http 404

i have an error in my mobilpay account and i it returns me that i can't pay with my card, any suggestions,help?
I use: prestashop 1.6.1.4
And mobilpay module installed.
This is the error:
IDS_Model_Purchase_INVALID_RESPONSE_STATUS , they told me that is problems with hosting account that returns me error 404
Here is a picture with the issue:
Validation Php file:
<?php
include(dirname(__FILE__).'/../../config/config.inc.php');
include(dirname(__FILE__).'/mobilpay_cc.php');
require_once dirname(__FILE__).'/Mobilpay/Payment/Request/Abstract.php';
require_once dirname(__FILE__).'/Mobilpay/Payment/Request/Card.php';
require_once dirname(__FILE__).'/Mobilpay/Payment/Request/Notify.php';
require_once dirname(__FILE__).'/Mobilpay/Payment/Invoice.php';
require_once dirname(__FILE__).'/Mobilpay/Payment/Address.php';
$errorCode = 0;
$errorType = Mobilpay_Payment_Request_Abstract::CONFIRM_ERROR_TYPE_NONE;
$errorMessage = '';
if (strcasecmp($_SERVER['REQUEST_METHOD'], 'post') == 0)
{
if(isset($_POST['env_key']) && isset($_POST['data']))
{
#calea catre cheia privata
#cheia privata este generata de mobilpay, accesibil in Admin -> Conturi de comerciant -> Detalii -> Setari securitate
$privateKeyFilePath = dirname(__FILE__).'/Mobilpay/certificates/private.key';
try
{
$objPmReq = Mobilpay_Payment_Request_Abstract::factoryFromEncrypted($_POST['env_key'], $_POST['data'], $privateKeyFilePath);
switch($objPmReq->objPmNotify->action)
{
#orice action este insotit de un cod de eroare si de un mesaj de eroare. Acestea pot fi citite folosind $cod_eroare = $objPmReq->objPmNotify->errorCode; respectiv $mesaj_eroare = $objPmReq->objPmNotify->errorMessage;
#pentru a identifica ID-ul comenzii pentru care primim rezultatul platii folosim $id_comanda = $objPmReq->orderId;
case 'confirmed':
#cand action este confirmed avem certitudinea ca banii au plecat din contul posesorului de card si facem update al starii comenzii si livrarea produsului
$errorCode = $objPmReq->objPmNotify->errorCode;
$errorMessage = $objPmReq->objPmNotify->getCrc();
break;
case 'confirmed_pending':
#cand action este confirmed_pending inseamna ca tranzactia este in curs de verificare antifrauda. Nu facem livrare/expediere. In urma trecerii de aceasta verificare se va primi o noua notificare pentru o actiune de confirmare sau anulare.
$errorCode = $objPmReq->objPmNotify->errorCode;
$errorMessage = $objPmReq->objPmNotify->getCrc();
break;
case 'paid_pending':
#cand action este paid_pending inseamna ca tranzactia este in curs de verificare. Nu facem livrare/expediere. In urma trecerii de aceasta verificare se va primi o noua notificare pentru o actiune de confirmare sau anulare.
$errorCode = $objPmReq->objPmNotify->errorCode;
$errorMessage = $objPmReq->objPmNotify->getCrc();
break;
case 'paid':
#cand action este paid inseamna ca tranzactia este in curs de procesare. Nu facem livrare/expediere. In urma trecerii de aceasta procesare se va primi o noua notificare pentru o actiune de confirmare sau anulare.
$errorCode = $objPmReq->objPmNotify->errorCode;
$errorMessage = $objPmReq->objPmNotify->getCrc();
break;
case 'canceled':
#cand action este canceled inseamna ca tranzactia este anulata. Nu facem livrare/expediere.
$errorCode = $objPmReq->objPmNotify->errorCode;
$errorMessage = $objPmReq->objPmNotify->getCrc();
break;
case 'credit':
#cand action este credit inseamna ca banii sunt returnati posesorului de card. Daca s-a facut deja livrare, aceasta trebuie oprita sau facut un reverse.
$errorCode = $objPmReq->objPmNotify->errorCode;
$errorMessage = $objPmReq->objPmNotify->getCrc();
break;
default:
$errorType = Mobilpay_Payment_Request_Abstract::CONFIRM_ERROR_TYPE_PERMANENT;
$errorCode = Mobilpay_Payment_Request_Abstract::ERROR_CONFIRM_INVALID_ACTION;
$errorMessage = 'mobilpay_refference_action paramaters is invalid';
break;
}
}
catch(Exception $e)
{
$errorType = Mobilpay_Payment_Request_Abstract::CONFIRM_ERROR_TYPE_TEMPORARY;
$errorCode = $e->getCode();
$errorMessage = $e->getMessage();
}
}
else
{
$errorType = Mobilpay_Payment_Request_Abstract::CONFIRM_ERROR_TYPE_PERMANENT;
$errorCode = Mobilpay_Payment_Request_Abstract::ERROR_CONFIRM_INVALID_POST_PARAMETERS;
$errorMessage = 'mobilpay.ro posted invalid parameters';
}
}
else
{
$errorType = Mobilpay_Payment_Request_Abstract::CONFIRM_ERROR_TYPE_PERMANENT;
$errorCode = Mobilpay_Payment_Request_Abstract::ERROR_CONFIRM_INVALID_POST_METHOD;
$errorMessage = 'invalid request metod for payment confirmation';
}
$Mobilpay_cc = new Mobilpay_cc();
if(!empty($objPmReq->orderId) && $errorCode==0) {
$cart = new Cart(intval($objPmReq->orderId));
//real order id
$order_id = Order::getOrderByCartId($objPmReq->orderId);
if(intval($order_id)>0) {
$order = new Order(intval($order_id));
$history = new OrderHistory();
$history->id_order = $order_id;
$history->changeIdOrderState(intval(Configuration::get('MPCC_OS_'.strtoupper($objPmReq->objPmNotify->action))), intval($order_id));
$history->id_employee = 1;
$carrier = new Carrier(intval($order->id_carrier), intval($order->id_lang));
$templateVars = array('{followup}' => ($history->id_order_state == _PS_OS_SHIPPING_ AND $order->shipping_number) ? str_replace('#', $order->shipping_number, $carrier->url) : '');
$history->addWithemail(true, $templateVars);
}
else {
//create the order
$Mobilpay_cc->validateOrder($objPmReq->orderId, intval(Configuration::get('MPCC_OS_'.strtoupper($objPmReq->objPmNotify->action))), floatval($objPmReq->invoice->amount), $Mobilpay_cc->displayName);
}
}
header('Content-type: application/xml');
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
if($errorCode == 0)
{
echo "<crc>{$errorMessage}</crc>";
}
else
{
echo "<crc error_type=\"{$errorType}\" error_code=\"{$errorCode}\">{$errorMessage}</crc>";
}

PHP How to avoid multi-session

There are some things that I want to do, but don't know if they are possible with PHP SESSIONS.
1. Avoid multi-session. (I did it using a flag in my database, but the problem comes when the user doesn't log out, and they just close the browser.
2. Log out a user remotely.
I will put my code right here. I tried to do it using the database and checking time differences, so I rewrite the value in my database and the user can log in.
Sessions.php
<?php
//Evitamos que nos salgan los NOTICES de PHP
error_reporting(E_ALL ^ E_NOTICE);
//Obtenemos el timestamp del servidor de cuanto se hizo la petición
$hora = $_SERVER["REQUEST_TIME"];
require('conexion.php');
//Duración de la sesión en segundos
$duracion = 9000;
//Si el tiempo de la petición* es mayor al tiempo permitido de la duración,
//destruye la sesión y crea una nueva
if (isset($_SESSION['ultima_actividad']) && ($hora - $_SESSION['ultima_actividad']) > $duracion) {
session_unset();
session_destroy();
// session_start();
};
// * Por esto este archivo debe ser incluido en cada página que necesite comprobar las sesiones
//Definimos el valor de la sesión "ultima_actividad" como el timestamp del servidor
$_SESSION['ultima_actividad'] = $hora;
?>
access.php
//Conectamos a la base de datos
require('../../config/conexion.php');
//Obtenemos los datos del formulario de acceso
$userPOST = $_POST["idUsuario"];
$passPOST = $_POST["idPass"];
//Filtro anti-XSS Seguridad
$userPOST = htmlspecialchars(mysqli_real_escape_string($conexion, $userPOST));
$passPOST = htmlspecialchars(mysqli_real_escape_string($conexion, $passPOST));
//Definimos la cantidad máxima de caracteres
//Esta comprobación se tiene en cuenta por si se llegase a modificar el "maxlength" del formulario
//Los valores deben coincidir con el tamaño máximo de la fila de la base de datos
$maxCaracteresUsername = "20";
$maxCaracteresPassword = "60";
//Si los input son de mayor tamaño, se "muere" el resto del código y muestra la respuesta correspondiente
if(strlen($userPOST) > $maxCaracteresUsername) {
die('El nombre de usuario no puede superar los '.$maxCaracteresUsername.' caracteres');
};
if(strlen($passPOST) > $maxCaracteresPassword) {
die('La contraseña no puede superar los '.$maxCaracteresPassword.' caracteres');
};
//Pasamos el input del usuario a minúsculas para compararlo después con
//el campo "usernamelowercase" de la base de datos
// $userPOSTMinusculas = strtolower($userPOST);
//Escribimos la consulta necesaria
// $consulta = "SELECT * FROM `users` WHERE usernamelowercase='".$userPOSTMinusculas."'";
//Consulta normal sin pedir comprobaciones de minusculas o mayusculas.
$consulta = "SELECT * FROM `users` WHERE username='".$userPOST."'";
//Obtenemos los resultados
$resultado = mysqli_query($conexion, $consulta) or die ("Query problem");
$datos = mysqli_fetch_array($resultado);
//Guardamos los resultados del nombre de usuario normal, no en minúsculas
//y de la contraseña de la base de datos
$userBD = $datos['username'];
$passwordBD = $datos['password'];
//Comprobamos si los datos son correctos
// if($userBD == $userPOSTMinusculas and password_verify($passPOST, $passwordBD)){
if($userBD == $userPOST and $passPOST == $passwordBD){
date_default_timezone_set('America/Chihuahua');
// die($parsedDate); //2016-08-18 22:54:33
//CrearFuncion para la diferencia en las fechas y el accesso en si para no repetir procedimientos...
//Funciones o declaraciones repetidas deberan ser incluidas en esta clase*****************************************
$time = date('Y-m-d H:i:s');
$time_dt = new DateTime($time);
$databasetime_dt = new DateTime($datos['lastActivity']);
//*******************************OBTENER DIFERENCIAS EN LAS FECHAS. ENTRE EL TIEMPO ACTUAL Y LA HORA QUE SE REGISTRA EN LA BASE DE DATOS.
$interval = $databasetime_dt->diff($time_dt);
// die($interval->format('%Y'));
if($datos['logged'] == 0){
session_id($datos['id']);
session_start();
$_SESSION['id'] = $datos['id'];
$_SESSION['usuario'] = $datos['username'];
$_SESSION['estado'] = 'Autenticado';
// ***********************************************************************************//
//SE GENERA UN UPDATE PARA CONFIRMAR QUE EL USUARIO ESTE LOGUEADO, SI LO ESTA, NO PODRA TENER MAS DE UNA SESION ACTIVA CON UN UPDATE EN LA HORA DE ACCESO//
$consultaActivo = "UPDATE users SET logged = 1, lastActivity ='".$time."' WHERE id=".$datos['id'];
$resultadoActivo = mysqli_query($conexion, $consultaActivo);
echo 'Hecho';
}else{
if($interval->format('%Y') >= 1){
session_id($datos['id']);
session_start();
$_SESSION['id'] = $datos['id'];
$_SESSION['usuario'] = $datos['username'];
$_SESSION['estado'] = 'Autenticado';
echo 'Hecho';
// die("Uno o mas años de diferencia");
}else{
if($interval->format('%m') >= 1){
session_id($datos['id']);
session_start();
$_SESSION['id'] = $datos['id'];
$_SESSION['usuario'] = $datos['username'];
$_SESSION['estado'] = 'Autenticado';
echo 'Hecho';
// die("Uno o mas meses de diferencia");
}else{
if($interval->format('%d') >= 1){
session_id($datos['id']);
session_start();
$_SESSION['id'] = $datos['id'];
$_SESSION['usuario'] = $datos['username'];
$_SESSION['estado'] = 'Autenticado';
echo 'Hecho';
// die("Uno o mas dias de diferencia");
}else{
if($interval->format('%H') >=1){
session_id($datos['id']);
session_start();
$_SESSION['id'] = $datos['id'];
$_SESSION['usuario'] = $datos['username'];
$_SESSION['estado'] = 'Autenticado';
echo 'Hecho';
// die("Una o mas hora de diferencia");
}else{
if($interval->format('%i') > 10){
session_id($datos['id']);
session_start();
$_SESSION['id'] = $datos['id'];
$_SESSION['usuario'] = $datos['username'];
$_SESSION['estado'] = 'Autenticado';
echo 'Hecho';
}
else{
echo 'SesionActiva';
}
}
}
}
}
}
/* Sesión iniciada, si se desea, se puede redireccionar desde el servidor */
//Si los datos no son correctos, o están vacíos, muestra un error
//Además, hay un script que vacía los campos con la clase "acceso" (formulario)
// } else if ( $userBD != $userPOSTMinusculas || $userPOST == "" || $passPOST == "" || !password_verify($passPOST, $passwordBD) ) {
} else if ( $userBD != $userPOST || $userPOST == "" || $passPOST == "" || !password_verify($passPOST, $passwordBD) ) {
// die ('<script>$(".input-group-addon").val("");</script>');
echo "Datos erroneos";
} else {
die('Error');
};
?>
logout.php
<?php
//Reanudamos la sesión
session_start();
//Requerimos los datos de la conexión a la BBDD
require('../../config/conexion.php');
$consultaActivo = "UPDATE `users` SET logged=0 WHERE id=".$_SESSION['id'];
$resultadoActivo = mysqli_query($conexion, $consultaActivo);
//Des-establecemos todas las sesiones
unset($_SESSION);
//Destruimos las sesiones
session_destroy();
//Cerramos la conexión con la base de datos
mysqli_close($conexion);
//Redireccionamos a el index
header("Location: ../../");
return true;
die();
?>

cant show up my image php from a DB

the problem is when it does return the binary file, pls help me
<!DOCTYPE html>
<html>
<head>
<title>Tienda Online</title>
<FORM action="upload_imagen.php" enctype="multipart/form-data" method="POST">
<input type="file" name="imagen"> Buscar imagen
<input type="submit" value="Buscar">
</FORM>
<div id="visualizar">
</div>
<form action="mostrar_imagen.php" method="POST">
<input type="text" name="valor" >
<input type="submit" value="mostrar">
</form>
</html>
upload_imagen.php this file upload an image and does storage in a DB
<?php
// Conexion a la base de datos
require "db_model.php";
class upload extends db_model {
function whatever() {
// Comprobamos si ha ocurrido un error.
if (!isset($_FILES["imagen"]) || $_FILES["imagen"]["error"] > 0) {
echo "Ha ocurrido un error.";
} else {
var_dump($_FILES["imagen"]);
// Verificamos si el tipo de archivo es un tipo de imagen permitido.
// y que el tamaño del archivo no exceda los 16MB
$permitidos = array("image/jpg", "image/jpeg", "image/gif", "image/png");
$limite_kb = 16384;
if (in_array($_FILES['imagen']['type'], $permitidos) && $_FILES['imagen']['size'] <= $limite_kb * 1024) {
// Archivo temporal
$imagen_temporal = $_FILES['imagen']['tmp_name'];
// Tipo de archivo
$tipo = $_FILES['imagen']['type'];
// Leemos el contenido del archivo temporal en binario.
$fp = fopen($imagen_temporal, 'r+b');
$data = fread($fp, filesize($imagen_temporal));
fclose($fp);
//Podríamos utilizar también la siguiente instrucción en lugar de las 3 anteriores.
// $data=file_get_contents($imagen_temporal);
// Escapamos los caracteres para que se puedan almacenar en la base de datos correctamente.
$data = mysql_real_escape_string($data);
// Insertamos en la base de datos.
$this->query ="INSERT INTO imagenes (imagen, tipo_imagen) VALUES ('$data', '$tipo')";
$resultado = $this->execute_query();
if ($resultado) {
echo "El archivo ha sido copiado exitosamente.";
} else {
echo "Ocurrió algun error al copiar el archivo.";
}
} else {
echo "Formato de archivo no permitido o excede el tamaño límite de $limite_kb Kbytes.";
}
}
}
}
$obj = new upload();
$obj->whatever();
?>
mostrar_imagen.php this section retrives the image in binary format, then i want to show it, so i read that i need a header and send it the type of image it is for example .jpg, .gif but i dont know if a i have an error
<?php
require 'db_model.php';
class mostrar extends db_model {
function __construct()
{
$id = $_POST['valor'];
$this->query = "SELECT imagen, tipo_imagen
FROM imagenes
WHERE imagen_id=$id";
$datos = $this->execute_query_as();
$imagen = $datos['imagen']; // Datos binarios de la imagen.
$tipo = $datos['tipo_imagen']; // Mime Type de la imagen.
// Mandamos las cabeceras al navegador indicando el tipo de datos que vamos a enviar.
---- > my problem is here, i guess
header("Content-type: image/jpg");
echo $imagen;
// A continuación enviamos el contenido binario de la imagen.
}
}
$obj = new mostrar();
?>
db_model.php
<?php
/**
* clase de la base de datos
*/
include_once('config.php');
class db_model
{
private $db_host = "localhost";
private $db_user = "root";
private $db_pass = "";
protected $db_name = "tienda_cartas";
protected $query;
protected $rows = array();
private $conection;
private function open_conection()
{
$this->conection = new mysqli($this->db_host,$this->db_user,$this->db_pass,$this->db_name);
if ($this->conection->connect_errno) {
echo "error al conectar";
die();
} else {
echo "conectado";
}
}
private function close_conection() {
$this->conection->close();
}
protected function execute_query() {
$this->open_conection();
$result = $this->conection->query($this->query);
if(!$result){
echo "no se pudo ejecutar el sql";
}
$this->close_conection();
return $result;
header("location:index.php");
}
protected function execute_query_as() {
$this->open_conection();
$result = $this->conection->query($this->query);
if(!$result){
echo "no se pudo ejecutar el sql";
}
$array_as = $result->fetch_assoc();
if(!$array_as){
echo "no hay incidencias";
die();
}
$this->close_conection();
return $array_as;
}
}
?>
This could be your problem:
$data = mysql_real_escape_string($data);
In your classes you use mysqli_* functions, but this one belongs to the deprecated mysql_* functions. When you call it it will automatically try to open a new database connection with mysql_connect(), which will fail because it doesn't have any information about your host. mysql_real_escape_string() will then return false:
Warning: mysql_real_escape_string(): A link to the server could not be established in test.php on line 2
bool(false)
Just remove the line, escaping binary data will most probably ruin it anyway. Instead you should use prepared statements to prevent SQL injections.

Unable to edit ints

I'm building an admin panel in PHP. I'm new to PHP and I can't get my edit page to work as I need it to. I can edit the name, but 2 values which represent "Active User" and "Access Level" are set to 0 and I can't change it from 0 on my edit page, only from PhpmyAdmin..
<?php
// Inserir o registo na BD
include_once ('config1.php');
// Estabelecer a ligação à BD
$connection = new mysqli('localhost', 'root', '123456', 'admin1');
//Verificar se a ligação foi estabelecida com sucesso
if (mysqli_connect_errno() ) {
echo "</h2>Erro no acesso a BD</h2>" . mysqli_connect_error();
exit();
}
// Validar se os campos do formulário foram preenchidos pelo utilizador
// Verificar se "username" foi enviado
if (isset($_POST['iusername']) == FALSE) {
echo ("Erro de submissão");
exit();
} else {
$username = trim($_POST['iusername']);
}
if (isset($_POST['inome']) == FALSE) {
echo ("Erro de submissão");
exit();
} else {
$nome = trim($_POST['inome']);
}
if (isset($_POST['inivel']) == FALSE) {
echo ("Erro de submissão");
exit();
} else {
$apelido = trim($_POST['inivel']);
}
if (isset($_POST['iativo']) == FALSE) {
echo ("Erro de submissão");
exit();
} else {
$telefone = trim($_POST['iativo']);
}
if (isset($_POST['iemail']) == FALSE) {
echo ("Erro de submissão");
exit();
} else {
$email = trim($_POST['iemail']);
}
if (isset($_POST['ipass']) == FALSE) {
echo ("Erro de submissão");
exit();
} else {
$pass = trim($_POST['ipass']);
}
if (isset($_POST['irpass']) == FALSE) {
echo ("Erro de submissão");
exit();
} else {
$repass = trim($_POST['irpass']);
}
// Função de validação do email (chamada mais abaixo no código)
function isValidEmail($email){
return #eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z] {2,3})", $email);
// Validar se o nº de caracteres do "username" está entre 4 e 12
if (strlen($username) < 4 || strlen($username) > 12) {
$erro = true;
$msgerro .= "<p>erro: \"username\" deve conter entre 4 e 12 caracteres</p>";
}
// Validar se o nome tem entre 3 e 40 caracteres
if (strlen($nome) < 3 || strlen($nome) > 40) {
//echo (strlen($nome));
$erro = true;
$msgerro .= "<p>erro: \"nome\" deve conter entre 3 a 40 caracteres</p>";
}
// Validação das passwords
$mudapass = false;
if (strlen($password) == 0 && strlen($rpassword) == 0) {
$mudapass = false;
} else {
$mudapass = true;
}
// 2.2. Validar o tamanho da password
if (strlen($password) < 4 || strlen($password)> 16) {
$erro = true;
$msgerro .= "<p>erro: \"password\" deve conter entre 4 a 16 caracteres</p>";
}
}
// 3. Validar se as duas passwords correspondem
if ($password != $rpassword) {
$erro = true;
$msgerro .= "<p>\"passwords\" não correspondem</p>";
}
// validação de email
// Chama a nova função "isValidEmail"
if (isValidEmail($email) == false) {
$erro = true;
$msgerro .= "<p>email inválido</p>";
}
// Final das validações (avisa caso algum erro seja detectado)
if ($erro) {
echo "<p>Formulário submetido com erros</p>";
echo $msgerro;
echo "<br>";
// Desenha 2 botões "Corrigir" e "Listar"
echo "<a class='ains' href='javascript:history.go(-1)' title='Volta à página anterior'>Corrigir </a>";
echo "<br/>";
echo "<a class='ains' href='lista.php'>Listar</a>";
exit();
}
if($password != $rpassword){
echo "ERRO: PASSWORDS SAO DIFERENTES";
}
$sql= "UPDATE usuarios SET
nome = '$nome';
email = '$email';
nivel = '$nivel';
ativo = '$ativo';
WHERE
usuario = '$username'";
if ($mudapass == TRUE) {
$sql = "UPDATE usuarios SET nome = '$nome',
password = '$password',
email = '$email',
nivel = '$nivel',
ativo = '$ativo', WHERE usuario = '$username'";
}
if ($mudapass == FALSE) {
$sql = "UPDATE usuarios SET
nome = '$nome',
email = '$email',
nivel = '$nivel',
ativo = '$ativo'
WHERE
usuario = '$username'";
}
$connection->query($sql);
// Lista users depois de actualizar
header("location:lista.php");
?>
It looks like a naming problem. Two of your variables don't seem to follow the same convention as the rest of them, and unless I'm missing some extra processing before the query, then you should change these two lines:
$apelido = trim($_POST['inivel']);
// ...several lines later
$telefone = trim($_POST['iativo']);
to this:
$nivel = trim($_POST['inivel']);
// ...several lines later
$ativo = trim($_POST['iativo']);

Categories