This is my code. I tried to upload an image using this PHP code. $mainCName, $mainCImage save in the database. But, the image does not upload to the uploadedimage folder. Can you help me please?.
public function add_main_category($mainCName, $mainCImage){
$query = "SELECT * FROM mainCategory WHERE mainCName='$mainCName'";
$result = $this->db->query($query) or die($this->db->error);
$count_row = $result->num_rows;
if($count_row == 0){
$imgfile=$_FILES["$mainCImage"];
$extension = substr($imgfile,strlen($imgfile)-4,strlen($imgfile));
$allowed_extensions = array(".jpg",".jpeg",".png",".gif");
if(!in_array($extension,$allowed_extensions))
{
echo "<script>alert('Invalid format. Only jpg / jpeg/ png /gif format allowed');</script>";
}
else{
$imgnewfile=md5($imgfile).$extension;
move_uploaded_file($_FILES["mainCImage"]["tmp_name"],"uploadedimage/".$imgnewfile);
}
$query = "INSERT INTO maincategory(mainCName,mainCImage) VALUES('$mainCName','$mainCImage')";
$result = $this->db->query($query) or die($this->db->error);
return true;
}
else{return false;}
}
Related
So problem is that I created 2 methods to set files and check the image if there is an image in tmp, it should delete the old image before moving a new one. But when I upload an image, unlink gives an error like this unlink(\Users\Murat\Desktop\xampp\htdocs\new\usersimages\42\1593769114256123131.jpg): No such file or directory in this number belongs to what I uploaded not the old image.
It moves a new image to the folder and try to delete new image but not delete old. this is the main problem. Probably I do a mistake but can't find where. The codes are below.
public function set_file($file){
$this->image = basename($file['name']);
$this->tmp_path = $file['tmp_name'];
$this->type = $file['type'];
$this->size = $file['size'];
$this->image = preg_replace('#[^a-z.0-9]#i', '', $this->image);
$kaboom = explode(".", $this->image); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
$this->image = time().rand().".".$fileExt;
}
public function checkPhoto($user_id){
global $database;
if(!empty($this->tmp_path)) {
$path = $this->upload_directory.$user_id.DS.$this->image;
unlink($path);
move_uploaded_file($this->tmp_path,
$path);
// unlink("album_uploads/$this->image");
} elseif (empty($this->tmp_path)) {
$sql = "SELECT * FROM users WHERE user_id = :user_id ";
$query =$database->query($sql, [':user_id'=>$user_id]);
$row = $query->fetch();
$this->image = $row['image'];
$this->type = $row['type'];
$this->size = $row['size'];
} else {
$this->errors[] = "Unexpected error please try again after refresh the page!";
}
}
So I added this part in the checkphoto method and it works now. if I did a mistake please let me know who can have more knowledge.
public function checkPhoto($user_id){
global $database;
$sql = "SELECT * FROM users WHERE user_id = :user_id ";
$query =$database->query($sql, [':user_id'=>$user_id]);
$row = $query->fetch();
$path = $this->upload_directory.$user_id.DS;
if(!empty($this->tmp_path)) {
$this->image = $row['image'];
if (file_exists($this->image)) {
unlink($path.$this->image);
}
// unlink("album_uploads/$this->image");
} elseif (empty($this->tmp_path)) {
$this->image = $row['image'];
$this->type = $row['type'];
$this->size = $row['size'];
} else {
$this->errors[] = "Unexpected error please try again after refresh the page!";
}
}
Upload file not working on server but it is working on localhost. File upload permission is ON, but even getting error. I tried all the solution over internet.
Here is my code.
if($submit == "UPLOAD PROFILE PICTURE") {
$user = $_COOKIE['userId'];
$file_name = $_FILES['userPic']['name'];
$file_size =$_FILES['userPic']['size'];
$file_tmp =$_FILES['userPic']['tmp_name'];
$file_type=$_FILES['userPic']['type'];
$tmp = explode('.', $file_name);
$file_ext = end($tmp);
$expensions= array("jpeg","jpg","png");
$nameToStore = $user.".".$file_ext;
chmod("images/users-dp/$nameToStore",0777);
if(in_array($file_ext,$expensions)=== true){
if($file_size < 2097152){
if(move_uploaded_file($file_tmp,"images/users-dp/".$nameToStore)) {
$queryFoCheck = "SELECT * FROM profilepic WHERE user = '$user'";
$resultFoCheck = $connection -> query($queryFoCheck);
$countFoCheck = mysqli_num_rows($resultFoCheck);
if($countFoCheck>=1) {
$query = "UPDATE profilepic SET piclink = '$nameToStore' WHERE user = '$user'";
$result = $connection -> query($query);
} else {
$query = "INSERT INTO profilepic VALUES ('$user', '$nameToStore') ";
$result = $connection -> query($query);
}
header('Location: profile.php?s'); //successsfully updated
} else {
header('Location: profile.php?e=1'); //Cant update
}
} else {
header('Location: profile.php?e=2'); //Cant update
}
} else {
header('Location: profile.php?e=3'); //Cant update
}
}
I'm trying to make a loop which checks if an image with filename from database exists, if not to unlink all images because I have many duplicates in folder but folder is 50gb. I can't check each one.
So here's what I've tried
$id = $_GET['id'];
$sql = "SELECT thumbnail FROM files WHERE id='$id'";
$query = $mysqli->query($sql);
$row = $query->fetch_assoc();
$thumb = $row['thumbnail'];
$records = "../upload/images/";
foreach ($records as $record) {
if (file_exists('../upload/images/'.$thumb)) {}
else {
#unlink('../upload/images/'.$thumb);
}
}
Update
$sql = "SELECT thumbnail FROM filesWHERE id='$id'";
$query = $mysqli->query($sql);
$row = $query->fetchAll();
foreach($sql as $search_result) {
if(file_exists($search_result['thumbnail'])) {
$img_source = ('../upload/images/'.$search_result['thumbnail']);
} else {
#unlink('../upload/images/'.$search_result);
}
}
That's the logic I've understood. Checking if there are files in the folder that aren't present in database, and if so, delete it.
$directory = "../upload/images/";
$images = glob($directory . "*.jpg");
foreach($images as $image)
{
$sql = "SELECT thumbnail FROM files WHERE thumbnail =?";
$stmt = $mysqli->prepare($sql);
if($stmt) {
$stmt->bind_param('s', $image);
$stmt->bind_result($result);
$stmt->execute();
$stmt->fetch();
if(!$result) {
if(unlink($image)) {
echo "Image deleted $image <br>\n";
}
}
} else {
echo "Unable to prepare SQL";
}
}
Hi i'm trying to receive my images from the database. I already can insert the images, but I don't know if it goes wrong overthere or that I do something wrong with getting the image.
The code for inserting the image:
public function Save(){
/*** check if a file was uploaded ***/
if(is_uploaded_file($_FILES['userfile']['tmp_name']) && getimagesize($_FILES['userfile']['tmp_name']) != false)
{
/*** get the image info. ***/
$size = getimagesize($_FILES['userfile']['tmp_name']);
/*** assign our variables ***/
$type = $size['mime'];
$imgfp = fopen($_FILES['userfile']['tmp_name'], 'rb');
$size = $size[3];
$name = $_FILES['userfile']['name'];
$maxsize = 99999999;
/*** check the file is less than the maximum file size ***/
if($_FILES['userfile']['size'] < $maxsize )
{
/*** connect to db ***/
$db = new Db();
/*** our sql query ***/
$sql = "INSERT INTO Foto (image_type ,image, image_size, image_name)
VALUES ('". $type ."',
'". $imgfp ."',
'". $size ."',
'". $name ."');";
$db->conn->query($sql);
$sql = "SELECT * FROM Foto ORDER BY id DESC LIMIT 1;";
$select = $db->conn->query($sql);
$numberofRows = $select->num_rows;
if($numberofRows == 1)
{
while ($oneSelect = $select->fetch_assoc())
{
return $oneSelect;
}
} else {
throw new Exception("Fout");
}
}
else
{
throw new Exception("Bestand is te groot");
}
}
else
{
throw new Exception("Dit extensie is niet ondersteund");
}
}
The code for loading the images:
<?php
include_once("classes/Db.class.php");
//$id = $_GET['id'];
$id = "33";
$db = new Db();
$sql = "SELECT image, image_type FROM Foto WHERE id = '". $id ."';";
$result = $db->conn->query($sql);
$row = $result->fetch_assoc();
if(sizeof($row) == 2)
{
header("Content-type: ".$row['image_type']);
echo $row['image'];
}
else
{
throw new Exception("Out of bounds Error");
}
?>
You're not actually inserting the image data. Read up on the fopen() function, it doesn't return the image data, but a file handle that can then be used for reading from or writing to a file (using, for example, fread() or fwrite()). Easy way out is using file_get_contents().
But take my advice, it's really bad practice to store images in the database. They're files and better off stored on the file system (hence the name). Makes serving them a lot faster too, as no PHP request has to be executed. Store the filename and maybe a relative path to the file in the database instead.
This code is to update database. it updates everything even uploads image sucessfully but after image upload the whole page gets blank and only "Array()" is displayed at top. Why is that?
<?php
if(!isset($_GET["prid"])){
header("Location: prjedit.php");
}
else {
$prid = intval($_GET["prid"]);
$sqlprj = "SELECT * FROM projects WHERE id = ? LIMIT 1";
$statement = $db->prepare($sqlprj);
$statement->execute(array($prid));
$project = $statement->fetchObject();
//submitted form
if( (isset($_POST["title"])) && (isset($_POST["details"])) ) {
$title = $_POST['title'];
$desc = $_POST['descr'];
$details = $_POST['details'];
if(!empty($_FILES['image']['name'])) {
//update image
$file = basename($_FILES['image']['name']);
$dir = "projects/";
$target_path = $dir . basename($_FILES['image']['name']);
$tempname = $_FILES['image']['tmp_name'];
if(!file_exists($target_path)) {
if(move_uploaded_file($tempname, $target_path)) {
$sqlimg = "UPDATE projects SET image = ? WHERE id = ?";
$statement = $db->prepare($sqlimg);
$statement->execute(array($file, $prid));
if($statement->rowCount() > 0) {
try {
chdir('./projects/');
unlink($project->image);
chdir('..');
}
catch (Exception $e) {
$message = "Sorry image delete failed ";
echo $e->getMessage();
}
}
else {
die ($db->errorInfo());
}
}
else {
$message = "Sorry Image update failed";
}
}
else {
$message = "Sorry this image already exists but text";
}
}
// update project texts
$sqlupd = "UPDATE projects SET title = ?, descinfo = ?, details = ? WHERE id = ?";
$statement = $db->prepare($sqlupd);
$statement->execute(array($title, $desc, $details, $prid));
if($statement->rowCount()) {
$message = " Saved successfully";
}
else {
die($db->errorInfo());
}
}
}
?>
Looking at Pdo::codeInfo documentation, it returns an array.
When you write die($db->errorInfo()); it will try to display this array.
As suggested by the documentation itself, you could try print_r($db->errorInfo()); die; and see what happens.