Delete images from two directories - php

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);

Related

How to save a file name in the MySQL database?

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

A PHP DOM program to import Freemind document in database

I put my code after some explanations.
I program this because i need to fill a database used by an application with .mm document (Freemind docs, .mm is the extension for "mind mapping")
The application and database need i keep the structure inside the Freemind doc. I don't program the application and the database, it's the work of an another guy.
This is the reason because i have all this
"if the child of the current node is a node with a child is an icon with an attribute called BUILTIN contains idea, this child is not an other object to put in the database, but the "contenu" value of the object create by the current node"
Just horrible to explain (it's horrible to explain it in French... And i try to make it clear in English. I hope it's clear.)
When i try to use my program, i can select the Freemind docs i want to convert is SQL, but i have this error just after:
Fatal error: Can't use method return value in write context in C:\xampp\htdocs\test2\transfertXmlBdd.php on line 25
Someone know why it's doesn't work and how i can make it works?
I think it's this part
if(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
$chaineXML = $target_file;
I try to keep the uploaded file in the $chaineXML for charge it with DOM after.
$dom->loadXML($chaineXML);
But i probably do it wrong.
uploadForm
<form action="upload.php" method="post" enctype="multipart/form-data">
Selectionner le document Freemind a charger:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Charger le document" name="submit">
</form>
</body>
</html>
upload
// Check if image file is a actual image or fake image
//if(isset($_POST["submit"])) {
// $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
// if($check !== false) {
// echo "File is an image - " . $check["mime"] . ".";
// $uploadOk = 1;
// } else {
// echo "File is not an image.";
// $uploadOk = 0;
// }
//}
// Check if file already exists
if (file_exists($target_file)) {
echo "Le fichier a deja ete charger.";
$uploadOk = 0;
}
// Check file size
//if ($_FILES["fileToUpload"]["size"] > 50000000) {
// echo "Le fichier est trop lourd.";
// $uploadOk = 0;
//}
// Allow certain file formats
if($imageFileType != "mm") {
echo "Vous ne pouvez upload que des fichiers XML au format MM (mind mapping).";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Echec du chargement.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
$chaineXML = $target_file;
echo "Le fichier ". basename( $_FILES["fileToUpload"]["name"]). " a ete charger.";
//on appelle la conversion/transfert
include_once('C:/xampp/htdocs/test2/transfertXmlBdd.php');
echo "Les donnees ont ete enregistre dans la BDD.";
} else {
echo "Une erreur s'est produite.";
}
}
?>
transferXmlBdd
$dom->loadXML($chaineXML);
$element = $listeElements->item(0);
//variables
$id= NULL;
$nom = NULL;
$type = NULL;
$contenu = NULL;
$idParent = NULL;
$idFils = NULL;
//comper le nombres d'elements déjà présent dans la table
$res = $bdd->query('select count(*) as nb from element');
$data = $res->fetch();
$id = $data['nb'];
foreach($xml as $node)
{
//on vérifie la présence ou non de BUILTIN de valeur idea, on passe à l'itération suivante (en forçant) si oui
if($node->hasChild("icon")->hasAttribute("BUILTIN")="idea")
{
continue;
}
//on génere les valeurs id et nom
$nom = getAttributeNode('NAME');
$id = $id + 1;
$idFils = $id;
//
$node.setAttribute(bddid,$id);
//on vérifie la parenté de l'enregistrement
if($node->hasParent("node"))
{
$idParent = getAttributeParent('bddid');
$req = $bdd->prepare('INSERT INTO fils_des_element(id_elem, id_fils) VALUES( idParent, :idFils)');
}
else
{
// affilié à l'élement 0
$req = $bdd->prepare('INSERT INTO fils_des_element(id_elem, id_fils) VALUES( 0, :idFils)');
}
//vérification de contenu
if($node->hasChild("node")->hasChild("icon")->hasAttribute("BUILTIN")=idea)
{
$contenu = getChildAttribute('NAME');
}
//détermination du type
if($node->hasChild("icon")-hasAttribute("BUILTIN")=button_ok)
{
$type = "Avec Solution";
}
elseif($node->hasChild("icon")-hasAttribute("BUILTIN")=button_cancel)
{
$type = "Sans Solution";
}
else
{
$type = NULL;
}
//création de l'entré dans la table
$req = $bdd->prepare('INSERT INTO element(id_element, nom, type, proprietaire, visible, contenu, date_modif) VALUES( :id, :nom, :type, drn, 0, :contenu, CURDATE())');
}
?>

Can't get the image link

So I can't insert images. I keep getting the following error.
"Notice: Undefined index: uploaded"
I can't get the image link!
Uploaded is the name of the button type=file (Upload images)
<?php
$host="localhost"; // Nome do host onde esta o banco de dados. Padrão ‘localhost’
$usuario="root"; // Usuário do Mysql. Padrão ‘root’
$senha=""; // Senha do Mysql
$db ="centro"; // Nome da Database
$tabela="usuarios"; // Nome da tabela
//connecta ao servidor
$mysqli = mysqli_connect("$host", "$usuario", "$senha")or die("cannot connect");
mysqli_select_db($mysqli,$db)or die("cannot select DB");
if(isset($_POST["upload"]))
{
//HERE!!!!!!!
$d="imagens/" . $_FILES["uploaded"]["name"];
if($_FILES["uploaded"]["type"]=="image/jpeg")
{
if(move_uploaded_file($_FILES["uploaded"]["tmp_name"],$d))
{
echo '<img style="width:50px;height:50px;" src="'. $d . '" >';
}
}
$titulo=$_POST['titulo'];
$mensagem=$_POST['mensagem'];
$ano=$_POST['ano'];
$mes=$_POST['mes'];
$dia=$_POST['dia'];
$link=$d;
}
else
{
echo "So imagens JPG.";
$titulo=" ";
$mensagem=" ";
$ano=0;
$mes=0;
$dia=0;
$link=" ";
}
$query = "INSERT INTO imagens(titulo,mensagem,dia,mes,ano,link) VALUES(?,?,?,?,?,?)";
$stat = $mysqli->prepare($query);
$stat->bind_param('ssiiis',$titulo,$mensagem,$dia,$mes,$ano,$link);
if ($stat->execute() && $stat->affected_rows>0)
{
echo "<div>Foi inserida uma imagem!</div>";
}
$stat->close();
$mysqli->close();
?>
You are getting:
Notice: Undefined index: uploaded
For this notice check your HTML Form and
enctype="multipart/form-data"
Example:
<form action="youraction" method="yourMethod" enctype="multipart/form-data">
HTML enctype Attribute

Loop though database with foreach

I want to browse data from my postgre database with a "foreach". So I made my request like that :
$conn_string = "host=localhost port=5432 dbname=test_postgre user=postgres password='1234'";
$dbconn = pg_connect($conn_string);
$sql = "SELECT id_traitement FROM public.traitement WHERE id_essai='.$id_essai.';";
$res = pg_query($sql) or die("Pb avec la requete: $sql");
$data = pg_fetch_all($res);
And I get my values with "pg_fetch_all".
After that, I'm looking for compare the data in my database (get with the request) and the data in my web page. So I created this loop :
foreach($array as $ligne_web)
{
foreach($data['id_traitement'] as $ligne_base)
{
if(($ligne_web[0] == $ligne_base) and ($flag))
{
//update de la ligne
update_traitement($id_traitement,$traitement,$code_traitement,$id_essai);
$flag2 = false;
break 1;
}
}
if(($flag) and ($flag2))
{
insert_traitement($id_traitement,$traitement,$code_traitement,$id_essai);
}
}
When I try to run it, firebug tells me : Invalid argument supplied for foreach(). So I don't know how to browse the rows in the database. Certainly my problem is in my foreach, but I don't find what's wrong.
Help please !
It seems your second foreach needs to be '$data' instead of $data['id_traitement']
So your code need to changed to ,
foreach($arr as $ligne_web)
{
foreach($data as $ligne_base) // <-- Here is the correction
{
if(($ligne_web[0] == $ligne_base) and ($flag))
{
------ REST of your Codes ------
Ok, I found an answer. Instead of an array $data from my database, and directly after the request, I created a new array.
Here is my code :
$conn_string = "host=localhost port=5432 dbname=test_postgre user=postgres password='1234'";
$dbconn = pg_connect($conn_string);
$sql = "SELECT id_traitement FROM public.traitement WHERE id_essai='.$id_essai.';";
$res = pg_query($sql) or die("Pb avec la requete: $sql");
$tableau_database_final = array();
while ($data = pg_fetch_all($res)) //Here is my array
{
$tableau_database = array('id_traitement'=>$data['id_traitement']);
array_push($tableau_database_final,$tableau_database);
}
$flag2 = true;
foreach($array as $ligne_web)
{
foreach($tableau_database_final as $ligne_base)
{
echo ($ligne_web[0]);
echo ($ligne_base);
if(($ligne_web[0] == $ligne_base)) //Si il existe une ligne ayant déjà le même id traitement
{
//update de la ligne
update_traitement($id_traitement,$traitement,$code_traitement,$id_essai);
$flag2 = false;
break 1;
}
}
if(($flag) && ($flag2))
{
//insert_traitement($id_traitement,$traitement,$code_traitement,$id_essai);
}
}

$user_id = $GET['user_id'] returns null when upload file

When i upload a file to my databae i want it to get the user_id, but it is returning null.
I already have made some tests to check if its really returning null and it is once i upload.
It knows which user_id is logged on that upload page.
See my code:
<?php
if(isset($_POST['title']))
{
//Check file type
$ext = substr(strrchr(basename($_FILES['file']['name']), '.'), 1);
if (!in_array($ext, $okExts))
{
echo "<p class=\"bad\">Formato Inválido.</p>";
}
else
{
$movePath = "../".$uploadPath . basename($_FILES['file']['name']);
$url = basename($_FILES['file']['name']);
$title = mysql_escape_string($_POST['title']);
$description = mysql_escape_string($_POST['description']);
$user_id = $_GET['user_id'];
if(move_uploaded_file($_FILES['file']['tmp_name'], $movePath))
{
//Update Fields
$fileSQL = "INSERT INTO files (title, description, user_id, url)
VALUES ('$title', '$description', '$user_id','$url')";
mysql_query($fileSQL,$conn) or die('Error: ' . mysql_error());
echo "<p class=\"good\">O Arquivo ".basename( $_FILES['file']['name'])." foi enviado.</p>";
}
else
{
echo "Ocorreu um erro ao enviar o arquivo, por favor tente novamente!";
}
}
}
?>
Why should not you use $_POST['user_id']; whether you $_POST['title']. To get $_GET['user_id']; you should pass page.php?user_id=36525 with URL.

Categories