File name too long while uploading image in database - php

I have written a line of codes to upload an image in the database, however, trying to upload image gives me this error
File name too long
Following is my code to upload an image to database:
if($_SERVER['REQUEST_METHOD']=="POST")
{
$pid = rand(1000,9000);
$title = $_POST['title'];
$descpt = $_POST['description'];
$push = isset($_POST['send_push']) ? $_POST['send_push'] : "";
$feature_image = array();
$fy = $_POST['fy'];
if(empty($title) || empty($descpt) || empty($fy))
{
array_push($this->errors, MEND_FIELD_ERROR);
return;
}
if(!empty($_FILES['feature_image']['name'][0]))
{
$image = $_FILES['feature_image'];
$allowed_ext = array('jpeg','jpg','png','pdf','docx');
$allowed_size = 20000000;
foreach($image['name'] as $pos=>$image_name)
{
$dir = "./cdn/uploads/notice/".$title;
$tmp = $image['tmp_name'][$pos];
$img_size = $image['size'][$pos];
$img_error = $image['error'][$pos];
$img_ext = explode('.', $image_name);
$img_name = $img_ext[0];
$img_ext = strtolower(end($img_ext));
if(in_array($img_ext, $allowed_ext))
{
if($img_size <= $allowed_size)
{
if(!file_exists($dir))
{
mkdir($dir);
}
$image_new_name = $img_name.'$$'.uniqid('', true).'.'.$img_ext;
$upload_destination = $dir.'/'.$image_new_name;
if(move_uploaded_file($tmp, $upload_destination))
{
array_push($feature_image, $image_new_name);
}
else
{
array_push($this->errors, $img_error);
return;
}
}
}
else
{
array_push($this->errors, $img_ext.' is not an allowed file extension.');
return;
}
}
}
$s_feature_image = json_encode($feature_image, JSON_UNESCAPED_UNICODE);
$statement = $this->db->prepare("INSERT INTO `notice` (`pid`,`title`,`descpt`,`date`,`photo`,`fy`)
VALUES (?,?,?,?,?,?)");
if($statement->execute([$pid,$title,$descpt,DAT, $s_feature_image, $fy]))
{
if($push == "checked")
{
$descpt = strip_tags($descpt);
$tek = array("message"=>$descpt,"title"=>$title);
$tokens = $this->getTokens();
$this->push_notification($tokens,$tek);
}
ExitThis::send_to(URL.'notice?id='.$pid);
}
else
{
array_push($this->errors, DATABASE_ERROR);
return;
}
}
Is it because of permission issue or something else? If so, what is causing me this problem and how do I fix this?

this is how I upload the file into the server and save the file name + extension into the database.
<?php
include 'connection.php';
$id = $_POST['id'];
$imgFile = $_FILES['photo']['name'];
$tmp_dir = $_FILES['photo']['tmp_name'];
$imgSize = $_FILES['photo']['size'];
$folder = 'images/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile, PATHINFO_EXTENSION)); // get image extension
// valid image extensions
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
// rename uploading image
$img = rand(1000, 1000000) . "." . $imgExt;
// allow valid image file formats
if (in_array($imgExt, $valid_extensions)) {
// Check file size '5MB'
if ($imgSize < 5000000) {
move_uploaded_file($tmp_dir, $folder . $img);
} else {
$errMSG = "Sorry, your file is too large.";
}
} else {
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
$query = mysqli_query($con, "UPDATE `profile` SET `photo` = '$img' WHERE `id` = '$id'");
if ($query) {
echo "<script>alert('Profile Updated'); window.location ='index.php?data=profile' </script>";
} else {
echo "<script>alert('Failed'); window.location ='index.php?data=profile' </script>";
}
?>
Hope this helps.
Cheers.

Related

How to move a object(GdImage) to a specific folder?

I'm working on a image converter that convert jpg and png to webp and webp to jpg and png and i've been trying to make that the converted files go to a specific folder instead of my working folder but it doesn't go on my convert forlder
here's my code
<?php
require "db.php";
$pdo = new \PDO(DSN, USER, PASS);
if (!empty($_FILES['files']['name'][0])) {
$files = $_FILES['files'];
$fileName = $_POST['name'];
$fileTag = $_POST['tag'];
$fileDescription = $_POST['description'];
$convert = $_POST['convert'];
$uploaded = array();
$failed = array();
$allowed = array('jpg', 'jpeg', 'png', 'webp');
foreach ($files['name'] as $position => $file_name) {
$file_tmp = $files['tmp_name'][$position];
$file_size = $files['size'][$position];
$file_error = $files['error'][$position];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
if (in_array($file_ext, $allowed)) {
if ($file_error === 0) {
if ($file_size <= 2097152) /* 2mb */ {
$file_name_new = uniqid('IMG-', true) . '.' . $file_ext;
$file_destination = 'uploads/' . $file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
$uploaded[$position] = $file_destination;
$query = "INSERT INTO images(name, tag, description, images) VALUES (:name, :tag, :description,:images)";
$statement = $pdo->prepare($query);
$statement->bindValue(':name', $fileName, \PDO::PARAM_STR);
$statement->bindValue(':tag', $fileTag, \PDO::PARAM_STR);
$statement->bindValue(':description', $fileDescription, \PDO::PARAM_STR);
$statement->bindValue(':images', $file_name_new, \PDO::PARAM_STR);
$statement->execute();
$upload = $statement->fetchAll();
} else {
$failed[$position] = "[{$file_name}] failed to upload.";
}
} else {
$failed[$position] = "[{$file_name}] is too large.";
}
} else {
$failed[$position] = "[{$file_name}] failed to upload {$file_error}.";
}
} else {
$failed[$position] = "[{$file_name}] file extension '{$file_ext}' is not allowed.";
}
}
if (!empty($uploaded)) {
print_r($uploaded);
}
if (!empty($failed)) {
print_r($failed);
}
} else {
echo 'no files';
}
if (exif_imagetype($file_destination) == IMAGETYPE_PNG && $convert ==='webp') {
$image = imagecreatefrompng($file_destination);
imagewebp($image, str_replace('png', 'webp', $file_name_new));
move_uploaded_file($file_destination, 'convert/');
} elseif (exif_imagetype($file_destination) == IMAGETYPE_JPEG && $convert ==='webp') {
$image = imagecreatefromjpeg($file_destination);
imagewebp($image, str_replace('jpg', 'webp', $file_name_new));
move_uploaded_file($file_tmp, 'convert/');
} elseif (exif_imagetype($file_destination) == IMAGETYPE_WEBP && $convert ==='png') {
$image = imagecreatefromwebp($file_destination);
imagepng($image, str_replace('webp', 'png', $file_name_new));
move_uploaded_file($file_tmp, 'convert/');
}elseif (exif_imagetype($file_destination) == IMAGETYPE_WEBP && $convert ==='jpg') {
$image = imagecreatefromwebp($file_destination);
imagepng($image, str_replace('webp', 'jpg', $file_name_new));
move_uploaded_file($file_tmp, 'convert/');
}else {
echo "can't convert it";
}var_dump($image);
I tried changing the variable in the move_uploaded_file but still won't let me

Warning: exif_imagetype(IMG-635b877fbb2892.73329302.jpg): Failed to open stream: No such file or directory

I'm making an image converter and I wanted to make a condition to check the file extension et change it to another one, ex: if it's jpg/png change it to webp
I keep having the warning on the line 85, 90 and 95
<?php
require "db.php";
$pdo = new \PDO(DSN, USER, PASS);
if (!empty($_FILES['files']['name'][0])) {
$files = $_FILES['files'];
$fileName = $_POST['name'];
$fileTag = $_POST['tag'];
$fileDescription = $_POST['description'];
$uploaded = array();
$failed = array();
$allowed = array('jpg', 'jpeg', 'png', 'webp');
foreach ($files['name'] as $position => $file_name) {
$file_tmp = $files['tmp_name'][$position];
$file_size = $files['size'][$position];
$file_error = $files['error'][$position];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
if (in_array($file_ext, $allowed)) {
if ($file_error === 0) {
if ($file_size <= 2097152) /* 2mb */ {
$file_name_new = uniqid('IMG-', true) . '.' . $file_ext;
$file_destination = 'uploads/' . $file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
$uploaded[$position] = $file_destination;
$query = "INSERT INTO images(name, tag, description, images) VALUES (:name, :tag, :description,:images)";
$statement = $pdo->prepare($query);
$statement->bindValue(':name', $fileName, \PDO::PARAM_STR);
$statement->bindValue(':tag', $fileTag, \PDO::PARAM_STR);
$statement->bindValue(':description', $fileDescription, \PDO::PARAM_STR);
$statement->bindValue(':images', $file_name_new, \PDO::PARAM_STR);
$statement->execute();
$upload = $statement->fetchAll();
} else {
$failed[$position] = "[{$file_name}] failed to upload.";
}
} else {
$failed[$position] = "[{$file_name}] is too large.";
}
} else {
$failed[$position] = "[{$file_name}] failed to upload {$file_error}.";
}
} else {
$failed[$position] = "[{$file_name}] file extension '{$file_ext}' is not allowed.";
}
}
if (!empty($uploaded)) {
print_r($uploaded);
}
if (!empty($failed)) {
print_r($failed);
}
} else {
echo 'no files';
}/*
$image = imagecreatefromjpeg($file_destination);
imagewebp($image, str_replace('jpg', 'webp', $file_name_new));
$image = imagecreatefrompng($file_destination);
imagewebp($image, str_replace('png', 'webp', $file_name_new));
$image = imagecreatefromwebp($file_destination);
imagepng($image, str_replace('webp', 'png', $file_name_new));
$image = imagecreatefromwebp($file_destination);
imagejpeg($image, str_replace('webp', 'jpg', $file_name_new));
*/
if (exif_imagetype($file_name_new) == IMAGETYPE_PNG) {
$image = imagecreatefrompng($file_destination);
imagewebp($image, str_replace('png', 'webp', $file_name_new));
} elseif (exif_imagetype($file_name_new) == IMAGETYPE_JPEG) {
$image = imagecreatefromjpeg($file_destination);
imagewebp($image, str_replace('jpg', 'webp', $file_name_new));
} elseif (exif_imagetype($file_name_new) == IMAGETYPE_WEBP) {
$image = imagecreatefromwebp($file_destination);
imagepng($image, str_replace('webp', 'png', $file_name_new));
}
It's not the best but i'll be working on making it better once the warning is gone
I tried to change the condition but kept having this warning
It also appeared when I made the converted file go to a folder

Just Inserting Blank array() inside in mysql error

I want to store image name only inside mysql table but issue is that it's uploading blank array and giving error
array to string conversion.
if(isset($_POST['prd_submit']) && isset($_FILES['prd_image'])){
// Define Input Variables
$name = user_input($_POST['prd_name']);
$detail = user_input($_POST['prd_detail']);
$image = $_FILES['prd_image'];
$buy_link = user_input($_POST['prd_link']);
$price = user_input($_POST['prd_price']);
$category = $_POST['prd_category'];
$country = $_POST['prd_country'];
// Control Error Inputs
if(empty($name)){
$name_err = "Name is missing";
}
if(empty($detail)){
$detail_err = "Detail is missing";
}
if(empty($price)){
$price_err = "Price is missing";
}
if(empty($buy_link)){
$buy_link_err = "Link is missing";
}
// File Upload Function
$OutFiles = array();
foreach($image as $Index=>$Items){
foreach($Items as $Key=>$Item){
$OutFiles[$Key][$Index] = $Item;
}
}
if($OutFiles[0]['error']){
$image_err = $Errors[$OutFiles[0]['error']];
}else{
foreach($OutFiles as $Index=>$File){
$UploadDir = $DocRoot.'/upload/';
$imageName = $File['name'];
//GETTING FILE EXTENTION
$file_ext = explode('.',$imageName);
$file_ext = $file_ext[count($file_ext)-1];
//FILE NAME
$filename = (rand()).'-'.(time()).'.'.$file_ext;
//FILE EXTENTION ERROR
if($file_ext != "jpg" && $file_ext != "png" && $file_ext != "jpeg" && $file_ext != "gif"){
$error = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}elseif(move_uploaded_file($File['tmp_name'],$UploadDir.$filename)){
$OutFiles[$Index]['name'] = $filename;
$uploadok++;
}elseif($uploadok == 0){
$error = "Sorry File is Not Upload";
}else{
$uploadok--;
$error = "Sorry File is Not Upload";
}
}
}
// Insert DB
if($name_err == '' && $detail_err == '' && $image_err == '' && $price_err == '' && $buy_link_err == ''){
$Code = 0;
try{
$insert_data = ("INSERT INTO product (name,country,detail,image,price,buy_link,category,date_posted) VALUES ('$name','$country','$detail','$image','$price','$buy_link','$category','$date')");
$insert_data = $conn->query($insert_data);
}catch(PDOException $E){
$Code = $E->getCode();
}
if($Code == 0){
$error = "<div class='alert alert-success'>Your Product Registration Request Has Submitted!</div>";
}elseif($Code == 23000){
$error = "<div class='alert alert-info'>Duplicate Entry</div>";
}else{
$error = "Unabel to enter data";
}
}
To much confuse what thing i'm doing wrong in it and if implode array but how i can implode i just need name only.
Change $image To $filename in your INSERT query.
Because, $image = $_FILES['prd_image']; is an array and you wanted to store the file name which is just uploaded to upload folder. So, use $filename which is uploaded using elseif(move_uploaded_file($File['tmp_name'],$UploadDir.$filename)){
Query
$insert_data = "INSERT INTO product (name,country,detail,image,price,buy_link,category,date_posted) VALUES ('$name','$country','$detail','$filename','$price','$buy_link','$category','$date')";
Uploading Multiple File : Move your INSERT Query inside foreach. It will insert into table on every successful upload.
foreach ($OutFiles as $Index => $File) {
$UploadDir = $DocRoot . '/upload/';
$imageName = $File['name'];
//GETTING FILE EXTENTION
$file_ext = explode('.', $imageName);
$file_ext = $file_ext[count($file_ext) - 1];
//FILE NAME
$filename = (rand()) . '-' . (time()) . '.' . $file_ext;
//FILE EXTENTION ERROR
if ($file_ext != "jpg" && $file_ext != "png" && $file_ext != "jpeg" && $file_ext != "gif") {
$error = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
} elseif (move_uploaded_file($File['tmp_name'], $UploadDir . $filename)) {
$OutFiles[$Index]['name'] = $filename;
$insert_data = "INSERT INTO product (name,country,detail,image,price,buy_link,category,date_posted) VALUES ('$name','$country','$detail','$filename','$price','$buy_link','$category','$date')";
$insert_data = $conn->query($insert_data);
$uploadok++;
} elseif ($uploadok == 0) {
$error = "Sorry File is Not Upload";
} else {
$uploadok--;
$error = "Sorry File is Not Upload";
}
}
And, remove try/catch from below as now it's INSERTING on every UPLOAD.

file not found after upload in php and mysql

I would like to upload some files to my server. So far, they have been successfully stored in a MySQL database, but the problem is that the uploaded file is not found in a folder that is located on the server.
Here's my code:
$dir = $filename;
$target_dir = "file/$dir/";
if( is_dir($target_dir) === false )
{
mkdir($target_dir);
}
if(isset($_POST["submit"])) {
$formatfile = array('pdf');
$filetest= $_FILES['filetest']['name'];
$x = explode('.', $filetest);
$existence= strtolower(end($x));
$pdfsize = $_FILES['filetest']['size'];
$file_tmp = $_FILES['filetest']['tmp_name'];
if(in_array($existence, $formatfile) === true){
if($pdfsize < 1044070){
move_uploaded_file($file_tmp, "$target_dir.$filetest");
}
}
}
$sql = "INSERT INTO test (filename) VALUES ('$filetest')";
Is there anything I missed?
Please change $formatfile = array('pdf') to $formatfile = array('.pdf'=>'application/pdf');
$dir = $filename; Whis is vlaue of $filename ?
please use like this.
$dir = '/var/www/uploads/';
if(in_array($existence, $formatfile)){
if($pdfsize < 1044070){
move_uploaded_file($file_tmp, "$target_dir.$filetest");
}
}
}
whenever you are uploading a file.try the full path.
<?php
$dir = $filename;
$target_dir = dirname(__FILE__).'/file/'.$dir.'/';
if (is_dir($target_dir) === false) {
mkdir($target_dir);
}
if (isset($_POST['submit'])) {
$formatfile = array('pdf');
$filetest = $_FILES['filetest']['name'];
$x = explode('.', $filetest);
$existence = strtolower(end($x));
$pdfsize = $_FILES['filetest']['size'];
$file_tmp = $_FILES['filetest']['tmp_name'];
if (in_array($existence, $formatfile) === true) {
if ($pdfsize < 1044070) {
move_uploaded_file($file_tmp, $target_dir.$filetest);
}
}
}
$sql = 'INSERT INTO test (filename) VALUES ('.$filetest.')';
$dir = $filename;
$target_dir = "file/$dir/";
if( is_dir($target_dir) === false )
{
mkdir($target_dir);
}
if(isset($_POST["submit"])) {
$formatfile = array('pdf');
$filetest= $_FILES['filetest']['name'];
$x = explode('.', $filetest);
$existence= strtolower(end($x));
$pdfsize = $_FILES['filetest']['size'];
$file_tmp = $_FILES['filetest']['tmp_name'];
if(in_array($existence, $formatfile) === true){
if($pdfsize < 1044070){
//Remove ""
move_uploaded_file($file_tmp, $target_dir.$filetest);
//If file upload then and then execute query.
$sql = "INSERT INTO test (filename) VALUES ('$filetest')";
}else{
//Fire error
}
}else{
//Fire error
}
}else{
//Fire error
}

PHP Upload images script

This is my code:
function secure_img_upload($file, $path, $options = array()){
// HANDLE OPTIONS
$validExtensions = isset($options['validExtensions']) ? $options['validExtensions'] : array('jpg', 'jpeg', 'png');
$surfix = isset($options['surfix']) ? $options['surfix'] : '';
// HANDLES FILES
$tempFile = $file['tmp_name'];
$fileName = $file['name'];
$extension = explode(".", $fileName);
$extension = strtolower(end($extension));
$imageName = sha1($fileName.uniqid());
$destination = rtrim($path, '/').'/'.$imageName.$surfix.'.'.$extension;
if(in_array($extension, $validExtensions)) {
$validExtension = true;
} else {
$validExtension = false;
}
// Run getImageSize function to check that we're really getting an image
if(getimagesize($tempFile) == false) {
$validImage = false;
} else {
$validImage = true;
}
if($validExtension == true && $validImage == true) {
if(move_uploaded_file($tempFile, $destination)) {
return $destination;
}else{
return array('s'=>'ko', 'm'=>T("Invalid path."));
}
}else{
return array('s'=>'ko', 'm'=>T("Invalid extension."));
}
}
My problem is that in this way, Images are uploaded in a random way.
But I need that images are uploaded in the order I select them. Any tips? Thank you

Categories