How to save a file name in the MySQL database? - php

I have developed this code below to the user upload a file and save the name of this file in the database, to be able to access it later, the upload is done normally, it goes to the designated folder, but the name is not saved in the database, does anyone know what's wrong with the code? Especially below the move_uploaded_file, because so far it works, then it goes wrong.
<?php
if (isset($_POST['enviar'])) {
$arq = $_FILES['arquivo']['name'];
$arq = str_replace(" ", "_", $arq);
$arq = str_replace("ç", "c", $arq);
if (file_exists("uploads/$arq")) {
$a = 1;
while (file_exists("uploads/[$a]$arq")) {
$a++;
}
$arq = "[".$a."]".$arq;
}
if (move_uploaded_file($_FILES['arquivo']['tmp_name'], 'uploads/'.$arq)) {
$objDb = new db();
$link = $objDb->conecta_mysql();
$sql = "insert into arquivos (email_vol, nomearq) values ('$email', '$arq')";
if (mysqli_query($link, $sql)){
echo 'Plano de aula 1 enviado com sucesso!';
} else {
echo (mysqli_error($link));
echo 'Erro ao enviar o plano de aula!';
}
} else {
echo "Nenhum arquivo selecionado!";
}
}
?>
That is the code used to connect with the database:
class db {
//host
private $host = 'localhost';
//usuario
private $usuario = '111111';
//senha
private $senha = '11111111';
//banco de dados
private $database = 'dsfadsfasd';
public function conecta_mysql(){
//criar a conexão
$con = mysqli_connect($this->host, $this->usuario, $this->senha, $this->database);
//ajustar a charser de cominicação entre a aplicação e o bd
mysqli_set_charset($con, 'utf8');
//verificar se houve erro de conexão
if (mysqli_connect_errno()) {
echo 'Erro ao tentar se conectar com o banco de dados'.mysqli_connect_error();
}
return $con;
}
}
?>

Don't have the privilege to comment right now but shouldn't this be like this plus you don't have a semicolon at the end of your sql script
$sql = "insert into arquivos (email_vol, nomearq) values ('" . $email . "', '"
.$arq . "');";
and also this
if (file_exists("uploads/" . $arq)) {
$a = 1;
while (file_exists("uploads/". $a . ".". $arq)) {
$a++;
}
$arq = $a.".".$arq;
}
with a full stop between your file number and name

Related

Bind more than one domain via ldap and php

Currently I have a project that authenticates via ldap to modify contact attribute, but only in a single domain, I'm trying to add an implementation so I can identify which domain the user wants to authenticate after informing on a form, example:
domain\user.
Here's how my code treats only one domain.
index.php
<?php
set_time_limit(30);
error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
/*
* Function Find user: Procura o usuario no LDAP
*/
$ldap_server = "iphost";
$ldap_binddn = "CN=LDAP Change Info,CN=Users,DC=DOMAIN,DC=com,DC=br";
$ldap_bindpw = "passwordhere";
$ldap_search_dn = "DC=domain,DC=com,DC=br";
function erro($mensagem, $goto_page = "") {
if ($mensagem == "") {
$_SESSION['last_error'] = "";
return;
}else{
$_SESSION['last_error'] = $mensagem;
}
if ($goto_page == "") {
$goto_page = "error.php";
}
include("_include/$goto_page");
die();
}
function modify_user_attribute($userdn, $attributes) {
global $ldap_server;
global $ldap_binddn;
global $ldap_bindpw;
global $ldap_search_dn;
/*
*
* Conexão no servidor LDAP.
*/
#TODO: Fazer conectar em outro servidor caso o primeiro de erro.
$ldap = ldap_connect($ldap_server) or die("LDAP Server connect error.");
ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
$ret = false;
if ($ldap) {
$ldapbind = ldap_bind($ldap, $ldap_binddn, $ldap_bindpw);
if ($ldapbind) {
$ret = ldap_modify($ldap, $userdn, $attributes);
ldap_close($ldap);
}
}
return $ret;
}
function check_value($value, $name) {
if ($value == null) {
erro("Atributo $name não pode ser nulo", "modify.php");
}
if ($value == "") {
erro("Atributo $name não pode ser vazio", "modify.php");
}
if (strlen($value) > 20) {
erro("Atributo $name não pode conter mais do que 20 caracteres.", "modify.php");
}
}
function find_and_auth_user($login, $senha) {
global $ldap_server;
global $ldap_binddn;
global $ldap_bindpw;
global $ldap_search_dn;
$ldap_user_to_find = "";
$ldap_user_pass = "";
$ldap_user_dn = "";
/*
*
* Conexão no servidor LDAP.
*/
#TODO: Fazer conectar em outro servidor caso o primeiro de erro.
$ldap = ldap_connect($ldap_server) or die("LDAP Server connect error.");
ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
if (!$ldap) {
//Redirecionar o usuário para uma tela de erro de sistema.
}
# Find
$ldapbind = ldap_bind($ldap, $ldap_binddn, $ldap_bindpw);
if ($ldapbind) {
$ldap_search_filter = "(sAMAccountName=$login)";
$result = ldap_search($ldap, $ldap_search_dn, $ldap_search_filter) or erro("Erro de sistema");
$data = ldap_get_entries($ldap, $result);
if ($data["count"] == 1) {
$ldap_user_dn = $data[0]["dn"];
# print "Encontrado usuário: " . $ldap_user_dn . "\n";
$ldapbind2 = ldap_bind($ldap, $ldap_user_dn, $senha);
if ($ldapbind2) {
$result = ldap_search($ldap, $ldap_user_dn, $ldap_search_filter) or erro("Erro de sistema");
$data = ldap_get_entries($ldap, $result);
/*
* Salva na sessão os dados encontrados.
*/
$_SESSION['dn'] = $ldap_user_dn;
$_SESSION['telephonenumber'] = $data[0]["telephonenumber"][0];
$_SESSION['ipphone'] = $data[0]["ipphone"][0];
$_SESSION['last_error'] = "";
return true;
}else{
#Redireciona o usuário para página de erro de login e senha.
erro("Usuário ou senha incorreta.", "login.php");
}
}else{
erro("Usuário ou senha incorreta.", "login.php");
}
}
ldap_close($ldap);
}
#
#
# SINGLE PAGE APP
#
#
#
if (session_id() == "") {
session_start();
//GET = Formulario de LOGIN
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$_SESSION['last_error'] = "";
include("_include/login.php");
return;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//POST do formulario de LOGIN
if (isset($_POST['username']) && isset($_POST['password'])) {
if (find_and_auth_user($_POST['username'], $_POST['password'])){
include("_include/modify.php");
}
return;
}
//POST do formulario de CHANGE
if (isset($_GET['change']) && $_GET['change'] == "true") {
$values["telephonenumber"][0] = $_POST['telephonenumber'];
$values["ipphone"][0] = $_POST['ipphone'];
check_value($values["telephonenumber"][0], "Telefone");
check_value($values["ipphone"][0], "Ramal");
if ($_SESSION['dn'] == null) {
erro("Erro de sistema. DN nula.", "login.php");
}
if ($_SESSION['dn'] == "") {
erro("Erro de sistema. DN nula.", "login.php");
}
if (modify_user_attribute($_SESSION['dn'], $values)) {
include("_include/success.php");
return;
}else{
erro("Erro alterando atributos.", "modify.php");
}
}
}
}else{
include("_include/modify.php");
return;
}
?>
Here's how I'm thinking of using it to authenticate to more than one domain:
teste.php
<?php
$username = $_POST['username'];
$arr = explode("\\", $login);
echo "Dominio = " .strtoupper($arr[0]) ."\n";
echo "Login = $arr[1]\n";
$conf = array();
$conf["DOMAIN1"]["LDAP_SERVER"] = "iphost";
$conf["DOMAIN1"]["BIND_DN"] = "CN=LDAP Change Info,CN=Users,DC=domain1,DC=com,DC=br";
$conf["DOMAIN1"]["BIND_PWD"] = "passwordhere";
$conf["DOMAIN1"]["SEARCH_DN"] = "DC=domain1,DC=com,DC=br";
$conf["DOMAIN2"]["LDAP_SERVER"] = "iphost";
$conf["DOMAIN2"]["BIND_DN"] = "CN=LDAP Change Info,CN=Users,DC=domain2,DC=com,DC=br";
$conf["DOMAIN2"]["BIND_PWD"] = "passwordhere";
$conf["DOMAIN2"]["SEARCH_DN"] = "DC=domain2,DC=com,DC=br";
$conf["DOMAIN3"]["LDAP_SERVER"] = "iphost";
$conf["DOMAIN3"]["BIND_DN"] = "CN=LDAP Change Info,CN=Users,DC=domain3,DC=com,DC=br";
$conf["DOMAIN3"]["BIND_PWD"] = "passwordhere";
$conf["DOMAIN3"]["SEARCH_DN"] = "DC=domain3,DC=com,DC=br";
#var_dump($conf);
$dominio = strtoupper($arr[0]);
if ( empty($conf[$dominio]["LDAP_SERVER"])) {
die("Domain $dominio not found\n");
}
//echo "auth domain " .$conf[$dominio]["LDAP_SERVER"] ."\n";
I would like to know how it would be possible to join the raciocio line to be able to log in to other domains.
I want to openly publish this code, it can help a lot of people.

Json return null

I have the next problem doing a json to read in Andorid
(the credentials are hidden but connection going good in others files)
class reportes
{
var $parametro;
var $conexion;
function __construct(){
$host = "IP"; $DBName = "DbName";
$usuario="user"; $contrasena="pass";
$driver = "DRIVER={iSeries Access ODBC Driver};
SYSTEM=$host;Uid=$usuario;
Pwd=$contrasena;Client_CSet=UTF-8;";
$this->conexion = odbc_connect($driver, $usuario, $contrasena);
}
function consulta($parametro){
$query=
"SELECT OHSNME,OHTOT$,OHREPÑ
FROM MYDB.SANFPRD.FOMHDR
WHERE OHORDÑ= $parametro ";
echo $query."<br><br>";
if ($this->conexion == 0) {echo "Ha fallado la conexion a la BBDD </br>";}
else{
$datos = array();
$result=odbc_exec($this->conexion,$query);
while($row = odbc_fetch_object($result)){
$datos[]= $row;
}
echo json_encode($datos);
}
}//Fin funcion consulta()
}//Fin de la clase
$consultar = new reportes();
$nota_venta = $_REQUEST['parametro'];
$consultar->consulta($nota_venta);
the response JSON that i get is:
SELECT OHSNME,OHTOT$,OHREPÑ FROM DELLORTO.SANFPRD.FOMHDR WHERE OHORDÑ= 366
[{"OHSNME":"E.C. GM. ","OHTOT$":"1861.00",null:" A07"}]
you can see that OHORDÑ is probably the problem with the 'Ñ'
but this table are part a productive database and i can't update
Solution #1, alias the column name to a name without non-ascii characters:
$query=
"SELECT OHSNME,OHTOT$,OHREPÑ AS OHREPN
FROM MYDB.SANFPRD.FOMHDR
WHERE OHORDÑ= $parametro ";
Solution #2, manually serialize using utf8_encode():
$result=odbc_exec($this->conexion,$query);
while($row = odbc_fetch_object($result)){
$_row_fix = array();
foreach ($row as $field => $val) {
$_row_fix[utf8_encode($field)] = utf8_encode($val);
}
$datos[]= $_row_fix;
}

can't create automatic sql tables after first use

I'm new with PHP and SQL...
I'm trying to create new tables based on the url, but it's only working the first time I use it. After that, it's not possible.
Here is my PHP code:
if(isset($_GET['id'])){
$tabela = $_GET['tabela'];
$_GET['id'];
$criar = $tabela . $nivel . $page_id;
// Se clicar no botão 'confirmar', então ele faz o seguinte:
if(isset($_POST['submit'])){
$titulo = $_POST['titulo'];
$_FILES['imagem']['tmp_name'];
$texto = $_POST['texto'];
// Se um destes campos estiver vazio:
if($titulo=='' or $imagem=='' or $texto==''){
echo "Preencha todos os campos para o menu!";
exit(); }
// Se não houver campos vazios, ele faz: else {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "site";
// Ligação à base de dados:
$conn = new mysqli($servername, $username, $password, $dbname);
// Verifica a ligação:
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Cria a nova tabela:
$sql = "CREATE TABLE IF NOT EXISTS $criar (
id INT(9) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
titulo VARCHAR(255),
imagem LONGBLOB,
texto TEXT,
grupo INT(9),
FOREIGN KEY (grupo) REFERENCES $tabela(id)
)";
// Se conseguir ligar-se à base de dados e criar uma nova tabela, ele insere os dados na nova tabela:
if ($conn->query($sql) === TRUE) {
include("includes/connect.php");
mysql_query("SET NAMES 'utf8'");
move_uploaded_file($image_tmp,"../imagens/$imagem");
$insert_query = "INSERT INTO $criar (titulo, imagem, texto, grupo) VALUES ('$titulo','$imagem','$texto','$page_id')";
// Se inserir os dados na nova tabela, ele dá uma mensagem de sucesso:
if(mysql_query($insert_query)){
echo "<script>alert('Menu inserido com sucesso!')</script>";
echo "<script>window.open('index.php','_self')</script>";
}
else{
echo "Erro: " . $insert_query . "<br>" . $conn->error;
}
}
// Caso ele não consiga criar uma nova tabela (porque já existe), ele insere os dados na tabela já existente:
else {
include("includes/connect.php");
mysql_query("SET NAMES 'utf8'");
// Cria a nova tabela:
$sql = "CREATE TABLE IF NOT EXISTS $criar (
id INT(9) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
titulo VARCHAR(255),
imagem LONGBLOB,
texto TEXT,
grupo INT(9),
FOREIGN KEY (grupo) REFERENCES $tabela(id)
)";
if(mysql_query($sql)){
echo "sim!";
}
else {
echo "não!";
}
move_uploaded_file($image_tmp,"../imagens/$imagem");
$insert_query = "INSERT INTO $criar (titulo, imagem, texto, grupo) VALUES ('$titulo','$imagem','$texto','$page_id')";
// Caso consiga inserir os dados na tabela já existente, dá uma mensagem de sucesso:
if(mysql_query($insert_query&&$sql)){
echo "<script>alert('Menu inserido com sucesso!')</script>";
echo "<script>window.open('index.php','_self')</script>";
}
else{
echo "isto não está a correr bem!";
}
// Fecha a ligação à base de dados:
$conn->close();
} } }$nivel = $_GET['grupo']; $page_id =$imagem = $_FILES['imagem']['name']; $image_tmp =
What do you mean 1st time, 2nd time? Do you try to create another table with the same name you just have created? You'll get a table already exists error.
CREATE TABLE IF NOT EXISTS $criar
This explicitly tells MySql not to create the table if it exists, so if you pass the same query parameters to your php then it'll not be able to create the same table again.
Probably you could change it to:
$page_id = $_GET['id'];
$criar = $tabela . $nivel . $page_id;
And then pass a different id and/or different tabela every time.
this code looks behind the issue to me :
$tabela = $_GET['tabela'];
$_GET['id']; //this line looks odd
$criar = $tabela . $nivel . $page_id;
and maybe it's not creating new tables because you give the same $criar every time.
After hours of trying to solve this issue, i finally got good news! :) i was working in my local server (via xampp) and decided to put it online to check if something changes... and dont know why, but it works perfectly online and dont work with xampp! What a mess!! but its working!! thanks all for your help!! ;)

Extract forex data from xlm with php and simplexml_load_file

<?php
$url = "http://rates.fxcm.com/RatesXML";
$xml = simplexml_load_file($url);
print_r($xml);
?>
This script really works and the output is here:
http://sitoxte.com/test%20mercato/array.php
But what I want to do is put this data to MySQL tabs, I need some help because I want to store the data each minute.
So i Try:
json-to-mysql
but I think that array in xml variable is not adeguate.
I want create a for cicle
and create 69 table like this:
table 1 eur/usd
id - Bid - Ask - High - Low - Direction - Last - timestamp
1
2
3
4...
and so on
refresh mode is simple and I do in this way whit javascript:
<script>
setInterval(function () {}, 3000);
var myVar=setInterval(function(){myTimer()},10000);
function myTimer()
{
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
location.reload();
}
</script>
connetion is simple too and is like this:
//Host:
$localhost="******";
//database
$mioblog=*******;
//Nome utente:
$username=********;
//Password:
$password=*******;
// connessione a MySQL con l'estensione MySQLi
$mysqli = new mysqli("$localhost", "$username", "$password", $mioblog);
// verifica dell'avvenuta connessione
if (mysqli_connect_errno()) {
// notifica in caso di errore
echo "Errore in connessione al DBMS: ".mysqli_connect_error();
// interruzione delle esecuzioni i caso di errore
exit();
}
else
{
// notifica in caso di connessione attiva
echo "Connessione avvenuta con successo";
}
This depends on what you're using for your database, but assuming PDO, something like the below. If you need more details then look up a MySQL tutorial, but hopefully this gets you started and shows you how to traverse the XML.
foreach($xml->Rate as $rate) {
$query = "INSERT INTO tblrate (time, symbol, bid) VALUES (NOW(), :symbol, :bid)";
$query = $pdo->prepare($query);
$query->execute(array(
':symbol' => $rate->#attributes['Symbol'],
':bid' => $rate->Bid;
));
}
edit: If you only need one currency, something like this should work
foreach($xml->Rate as $rate) {
if($rate->#attributes['Symbol'] == 'EURUSD') {
$query = "INSERT INTO tblrate (time, bid) VALUES (NOW(), :bid)";
$query = $pdo->prepare($query);
$query->execute(array(
':bid' => $rate->Bid;
));
}
}
My friend Biagio help me to write code:
foreach($xml->children() as $xml_child){
$Symbol = $xml_child['Symbol'];
$Bid = $xml_child->Bid;
$Ask = $xml_child->Ask;
$High = $xml_child->High;
$Low = $xml_child->Low;
$Direction = $xml_child->Direction;
$Last = $xml_child->Last;
echo('$Symbol = '.$Symbol.'<br>');
echo('$Bid = '.$Bid.'<br>');
}
final code of php scrip that write in mysql tables every second forex data:
...
<body id="top">
<!-- <button onclick="myFunction()">Reload page</button> -->
<a id=demo> <a>
...
<?php
echo date("F j, Y, g:i a", time()).'<br>';
$html="";
$url = "http://rates.fxcm.com/RatesXML";
$xml = simplexml_load_file($url);
//Host:
//echo('var_dump( $xml)<br>');
//var_dump( $xml);
//SimpleXMLElement
//Host:
$localhost="----";
//database
$mioblog=----;
//Nome utente:
$username=-----;
//Password:
$password=-----;
// connessione a MySQL con l'estensione MySQLi
$mysqli = new mysqli("$localhost", "$username", "$password", $mioblog);
// verifica dell'avvenuta connessione
if (mysqli_connect_errno()) {
// notifica in caso di errore
echo "Errore in connessione al DBMS: ".mysqli_connect_error();
// interruzione delle esecuzioni i caso di errore
exit();
}
else {
// notifica in caso di connessione attiva
// echo "Connessione avvenuta con successo";
}
// sql to create table
// sql to create table
foreach($xml->children() as $xml_child){
$Symbol = $xml_child['Symbol'];
$Bid = $xml_child->Bid;
$Ask = $xml_child->Ask;
$High = $xml_child->High;
$Low = $xml_child->Low;
$Direction = $xml_child->Direction;
$Last = $xml_child->Last;
// sql to create table
/*
$sql = "CREATE TABLE $Symbol (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
Bid VARCHAR(30) NOT NULL,
Ask VARCHAR(30) NOT NULL,
High VARCHAR(30) NOT NULL,
Low VARCHAR(30) NOT NULL,
Direction VARCHAR(30),
Last VARCHAR(30) NOT NULL,
reg_date TIMESTAMP
)";*/
$sql = "INSERT INTO $Symbol (Bid,Ask,High,Low,Direction,Last)
VALUES ('$Bid','$Ask',$High,$Low,$Direction,'$Last')";
if ($mysqli->query($sql) === TRUE) {
// echo "Inserito in table ".$Symbol." / bid=".$Bid." / ask=".$Ask."/ High=".$High."/ Low=".$Low."/ Direction=".$Direction."/ Last=".$Last."<br>";
} else {
echo "Error creating table: " . $mysqli->error;
}
// echo('$Symbol = '.$Symbol.'<br>');
//echo('$Bid = '.$Bid.'<br>');
//echo('$Ask = '.$Ask.'<br>');
//echo('$High = '.$High.'<br>');
//echo('$Low = '.$Low.'<br>');
// echo('$Direction = '.$Direction.'<br>');
// echo('$Last = '.$Last.'<br>');
}
$mysqli-->close();
?>
....

Delete images from two directories

I have a script that loads images in the database and in two directories: uploads / original and a directory for the preview: uploads / thumbs
I need to create a small panel to delete inserted images, I have already created the code to delete from the database, but I can not delete them from the two directories.
I know I need to use unlink, but I'm no expert, I do not know where to place the code etc. I ask for help to you.
This is the file that I delete.php structured so far:
<?php
$con = mysql_connect("localhost","*******","******");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("**********************", $con);
if($_POST)
{
$ids = isset($_POST['id']) ? $_POST['id'] : array();
elimina_record($ids);
}
elseif(isset($_GET['id']))
{
elimina_record(array($_GET['id']));
}
else
mostra_lista();
function mostra_lista()
{
// mostro un eventuale messaggio
if(isset($_GET['msg']))
echo '<b>'.htmlentities($_GET['msg']).'</b><br /><br />';
// preparo la query
$query = "SELECT id,name,filename FROM image";
// invio la query
$result = mysql_query($query);
// controllo l'esito
if (!$result) {
die("Errore nella query $query: " . mysql_error());
}
echo '
<form name="form1" method="post" action="">
<table border="1">
<tr>
<th> </th>
<th>ID</th>
<th> </th>
</tr>';
while ($row = mysql_fetch_assoc($result))
{
$name = htmlentities($row['name']);
$id = htmlentities($row['id']);
$filename = htmlentities($row['filename']);
// preparo il link per la modifica dei dati del record
$link = $_SERVER['PHP_SELF'].'?id=' . $row['id'];
echo "<tr>
<td><input name=\"id[]\" type=\"checkbox\" value=\"$row[id]\" /></td>
<td>$id</td>
<td>delete</td>
</tr>";
}
echo '</table>
<br />
<input type="submit" name="Submit" value="Elimina record selezionati" />
</form>';
// libero la memoria di PHP occupata dai record estratti con la SELECT
mysql_free_result($result);
// chiudo la connessione a MySQL
mysql_close();
}
function elimina_record($ids)
{
// verifico che almeno un id sia stato selezionato
if(count($ids) < 1)
{
$messaggio = urlencode("Nessun record selezionato!");
header('location: '.$_SERVER['PHP_SELF'].'?msg='.$messaggio);
exit;
}
// per precauzione converto gli ID in interi
$ids = array_map('intval',$ids);
// creo una lista di ID per la query
$ids = implode(',',$ids);
// preparo la query
$query = "DELETE FROM image WHERE id IN ($ids)";
// invio la query
$result = mysql_query($query);
// controllo l'esito
if (!$result) {
die("Errore nella query $query: " . mysql_error());
}
// conto il numero di record cancellati
$num_record = mysql_affected_rows();
// chiudo la connessione a MySQL
mysql_close();
$messaggio = urlencode("Numero record cancellati: $num_record");
header('location: '.$_SERVER['PHP_SELF'].'?msg='.$messaggio);
}
?>
While, it may be useful, even paste the file to upload.php files:
session_start();
$_SESSION['id']="1";
$id=$_SESSION['id'];
include 'config.php'; //assume you have connected to database already.
$folder = 'uploads/';
$name = date('YmdHis');
$filename = md5($_SERVER['REMOTE_ADDR'].rand()).'.jpg';
$original = $folder.$filename;
// The JPEG snapshot is sent as raw input:
$input = file_get_contents('php://input');
if(md5($input) == '7d4df9cc423720b7f1f3d672b89362be'){
// Blank image. We don't need this one.
exit;
}
$result = file_put_contents($original, $input);
if (!$result) {
echo '{
"error" : 1,
"message" : "Failed save the image. Make sure you chmod the uploads folder and its subfolders to 777."
}';
exit;
}
$info = getimagesize($original);
if($info['mime'] != 'image/jpeg'){
unlink($original);
exit;
}
// Moving the temporary file to the originals folder:
rename($original,'uploads/original/'.$filename);
$original = 'uploads/original/'.$filename;
// Using the GD library to resize
// the image into a thumbnail:
$origImage = imagecreatefromjpeg($original);
$newImage = imagecreatetruecolor(154,110);
imagecopyresampled($newImage,$origImage,0,0,0,0,154,110,520,370);
imagejpeg($newImage,'uploads/thumbs/'.$filename);
echo '{"status":1,"message":"Success!","filename":"'.$filename.'"}';
$sql="INSERT INTO image VALUES ('','$name','$filename')";
$result=mysqli_query($con,$sql);
$value=mysqli_insert_id($con);
$_SESSION["myvalue"]=$value;
$cart_1="/uploads/original/";
$cart_2="/uploads/thumbs/";
foreach($files as $file){
$f_1=$cart_1.$file;
$f_2=$cart_2.$file;
unlink($f_1);
unlink($f_2);
}
Check this out:
$dir1 = '/upload/original/';
$dir2 = '/upload/thumbs/';
$image = 'abc.jpg';
if(file_exists($dir1.$image))
unlink($dir1.$image);
if(file_exists($dir2.$image))
unlink($dir2.$image);

Categories