Check if file was uploaded or not - php

I am creating a social site. I have the option to upload up to 10 images with or without text, and the option to upload text without images.
So below I am trying to see if the user uploaded only text, or text with images. If the user uploaded only text then I want the text to be inserted into it's own separate table. If the user uploaded text with images or just images I want to check for that too. How can I check if the user uploaded images and if so run the images script and if not, jump out of the file ? This is what I have so far.
<input name="files[]" id='files' accept="image/png,image/gif,image/jpeg" type="file" multiple="multiple" />
$date_time = date('Y-m-d_H-i-s');
$img_limit = 10;
$maxsize = 4367463;
if(isset($_POST['submit'])) {
$errors = '';
if ($_POST['title_post'] == '') {
$errors = "Choose a topic.";
} else {
$create_topic = $con->prepare("INSERT INTO subtopic (subtopic, description)
VALUES (?, ?)");
$create_topic->bind_param("ss", $_POST['title_post'], $_POST['description']);
$create_topic->execute();
}
// --------------- CHECK IMAGES ----------****
$file_count = count($_FILES['files']['name']);
if ($file_count > 0) {
if ($file_count > $img_limit) {
$errors = 'Cannot upload more than 10 images';
}
if (!$errors) {
$stmt = $con->prepare("INSERT INTO images (image) VALUES (?)");
$stmt->bind_param('s', $file_path);
// Loop through each file
for( $i=0; $i < $file_count; $i++ ) {
$file_name = $_FILES['files']['name'][$i];
$file_size = $_FILES['files']['size'][$i];
$file_tmp = $_FILES['files']['tmp_name'][$i];
$imageFileType = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
if ($file_size >= $maxsize) {
$errors = "Your file is too large";
} elseif ($imageFileType != "jpeg" && $imageFileType != "jpg" &&
$imageFileType != "png" && $imageFileType != "gif") {
$errors = "File type not allowed.";
}
//Make sure we have a file path
if (!$errors /* && $file_tmp != "" */) {
$picToUpload = $date_time . " -#- " . md5($file_name) . " -#- " . $_FILES['files']['name'][$i];
$uploadPicture = move_uploaded_file($file_tmp, "uploads/" . $picToUpload);
$file_path = "uploads/" . $picToUpload;
$stmt->execute();
}
}
}} else {
header('Location: index4.php');
exit();
}
// --------------- CHECK IMAGES ----------****
}

You need to check the current file - for example:
if(!file_exists($_FILES['files']['tmp_name'][0]) || !is_uploaded_file($_FILES['files']['tmp_name'][0])){
}
Where 0 is equal to $i

Related

check input file type for images

I'm trying to check if in my multiple input field, the images are really images, or not. The problem is, my code still allows to upload pdf, and other files aswell. I read questions here about it, but couldn't this is the only thing I've found, but I don't really understand how else I should use it. This is how it looks like:
$selectid = $conn->prepare("SELECT max(id) AS id FROM cards");
$selectid->execute();
$cardid = $selectid->get_result()->fetch_array()['id'];
$stmt = $conn->prepare("INSERT INTO cardimages(image, cardid) VALUES(?, ?)");
$target_file = $_FILES['file']['tmp_name'];
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
if (count($_FILES['file']['tmp_name']) > 5) {
header("Location: addbusiness.php?message=3");
} else {
$everyPicUnder2Mb = true;
for ($i = 0; $i < count($_FILES['file']['tmp_name']); $i++) {
if ($_FILES["file"]["size"][$i] > 2100000) {
$everyPicUnder2Mb = false;
}
}
if ($everyPicUnder2Mb) {
for ($i = 0; $i < count($_FILES['file']['tmp_name']); $i++) {
$file = $_FILES['file']['tmp_name'][$i];
if (is_uploaded_file($file)) {
$imgData = file_get_contents($file);
$stmt->bind_param("si", $imgData, $cardid);
$stmt->execute();
}
}
} else {
header("Location: addbusiness.php?message=2");
}
}
EDIT: Here's my code now. The problem with this is it always gets a '.temp' file so it always thinks it's not an image.
if ($everyPicUnder2Mb) {
for ($i = 0; $i < count($_FILES['file']['tmp_name']); $i++) {
$file = $_FILES['file']['tmp_name'][$i];
$imageFileType = strtolower(pathinfo($file, PATHINFO_EXTENSION)); #get current file's extension
if ($imageFileType !== "jpg" && $imageFileType !== "png" && $imageFileType !== "jpeg" && $imageFileType !== "gif") {
echo 'HIBA! A következő fájl: ' . $file . ' nem JPG, PNG, JPEG vagy GIF formátum.';
exit;
}
if (is_uploaded_file($file)) {
$imgData = file_get_contents($file);
$stmt->bind_param("si", $imgData, $cardid);
$stmt->execute();
}
}
}
With #MaxK's answer I could solve the problem. Here's how I did it:
$allowed_types = array (IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
$detectedType = exif_imagetype($_FILES['file']['tmp_name'][$i]);
if (!in_array($detectedType, $allowed_types))
{
echo 'Only JPG/JPEG/PNG/GIF';
}

File name too long while uploading image in database

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.

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.

How to Upload Photo and return GPS co-ords

All,
I'm tinkering with a simp[le form to upload a photo, store it within my server & then return the GPS co-ordinates.
I'm using the standard PHP file upload script and a GPs solution i found here. It allows me to upload files but does not return the GPS co-ordinates. Can anyone help identify the issue please?
My complete php is:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// 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 "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 5000000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
read_gps_location($target_file);
/**
* Returns an array of latitude and longitude from the Image file
* #param image $file
* #return multitype:number |boolean
*/
function read_gps_location(){
if (is_file($target_file)) {
$info = exif_read_data($target_file);
if (isset($info['GPSLatitude']) && isset($info['GPSLongitude']) &&
isset($info['GPSLatitudeRef']) && isset($info['GPSLongitudeRef']) &&
in_array($info['GPSLatitudeRef'], array('E','W','N','S')) && in_array($info['GPSLongitudeRef'], array('E','W','N','S'))) {
$GPSLatitudeRef = strtolower(trim($info['GPSLatitudeRef']));
$GPSLongitudeRef = strtolower(trim($info['GPSLongitudeRef']));
$lat_degrees_a = explode('/',$info['GPSLatitude'][0]);
$lat_minutes_a = explode('/',$info['GPSLatitude'][1]);
$lat_seconds_a = explode('/',$info['GPSLatitude'][2]);
$lng_degrees_a = explode('/',$info['GPSLongitude'][0]);
$lng_minutes_a = explode('/',$info['GPSLongitude'][1]);
$lng_seconds_a = explode('/',$info['GPSLongitude'][2]);
$lat_degrees = $lat_degrees_a[0] / $lat_degrees_a[1];
$lat_minutes = $lat_minutes_a[0] / $lat_minutes_a[1];
$lat_seconds = $lat_seconds_a[0] / $lat_seconds_a[1];
$lng_degrees = $lng_degrees_a[0] / $lng_degrees_a[1];
$lng_minutes = $lng_minutes_a[0] / $lng_minutes_a[1];
$lng_seconds = $lng_seconds_a[0] / $lng_seconds_a[1];
$lat = (float) $lat_degrees+((($lat_minutes*60)+($lat_seconds))/3600);
$lng = (float) $lng_degrees+((($lng_minutes*60)+($lng_seconds))/3600);
//If the latitude is South, make it negative.
//If the longitude is west, make it negative
$GPSLatitudeRef == 's' ? $lat *= -1 : '';
$GPSLongitudeRef == 'w' ? $lng *= -1 : '';
return array(
'lat' => $lat,
'lng' => $lng
);
}
}
return false;
}
?>
You invoke function read_gps_location($target_file); but you don't print the output
try changing this line
read_gps_location($target_file);
to
print_r(read_gps_location($target_file));
To see the output. It should be either array or false.

PHP: How to pass "current $_FILE" to another function after iterate $_FILES global variable?

If I submit a form with multiple files in it, how can I upload each of them after some kind of execution one by one?
Add something like this to your PHP page
//upload image 1
if ($filename1<>"") {
$filename = $filename1;
$file = 'file1';
$temp = explode(".", $_FILES["file1"]["name"]);
include "upload_file.php";
$updateimageurl = mysql_query("update yacht set image1 = '$newfilename' where yachtid = '$yachtid'");
}
//upload image 2
if ($filename2<>"") {
$filename = $filename2;
$file = 'file2';
$temp = explode(".", $_FILES["file2"]["name"]);
include "upload_file.php";
$updateimageurl = mysql_query("update yacht set image2 = '$newfilename' where yachtid = '$yachtid'");
}
And then the file called "upload_file.php should look something like this (change the validation sections if you want it to validate on different file names). Also, this renames the file to a random name before saving it to your location);
<?php
$length = 30;
$characters = "0123456789abcdefghijklmnopqrstuvwxyz";
$code = "";
for ($p = 0; $p < $length; $p++) {
$pos = mt_rand(0, strlen($characters)-1);
$code .= $characters{$pos};
}
$parts = explode('.',$filename);
$extension= end($parts);
$newfilename=$code .".".$extension;
$success = 0;
$allowedExts = array("gif", "jpeg", "jpg", "png");
$extension = end($temp);
if ((($_FILES[$file]["type"] == "image/gif") || ($_FILES[$file]["type"] == "image/jpeg") || ($_FILES[$file]["type"] == "image/jpg")
|| ($_FILES[$file]["type"] == "image/pjpeg") || ($_FILES[$file]["type"] == "image/x-png") || ($_FILES[$file]["type"] == "image/png"))
&& ($_FILES[$file]["size"] < 1000000) && in_array($extension, $allowedExts)) {
$filenamepng = "./images/yacht/".$code.".png";
$filenamegif = "./images/yacht/".$code.".gif";
$filenamejpeg = "./images/yacht/".$code.".jpeg";
$filenamejpg = "./images/yacht/".$code.".jpg";
$filenamepjpeg = "./images/yacht/".$code.".pjpeg";
$filenamexpng = "./images/yacht/".$code.".x-png";
if (file_exists($filenamepng)||file_exists($filenamegif)||file_exists($filenamejpeg)||file_exists($filenamejpg)||file_exists($filenamepjpeg)||file_exists($filenamexpng)) {
if (file_exists($filenamepng)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.png';
unlink($filename);
}
if (file_exists($filenamegif)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.gif';
unlink($filename);
}
if (file_exists($filenamejpeg)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.jpeg';
unlink($filename);
}
if (file_exists($filenamejpg)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.jpg';
unlink($filename);
}
if (file_exists($filenamepjpeg)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.pjpeg';
unlink($filename);
}
if (file_exists($filenamexpng)) {
$dir = './images/yacht/';
$filename = $dir.$code.'.x-png';
unlink($filename);
}
}
move_uploaded_file($_FILES[$file]["tmp_name"],
"images/yacht/" . $newfilename);
//echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
unset($code);
$success = 1;
}
else
{
$error = "Your image is over 1mb OR is not in an accepted format; gif, jpeg, jpg, pjpeg, x-png, or png. Please try again.";
}
?>
www.clubtray.com
www.clubtray-clubmembershipsoftware.com

Categories