Not updating a field if no image is inserted - php

I am quite new to PHP, but i'm having a problem with my thought process around some code i am writing.
I am trying to get the below to work so that a user can upload two images in a form, which uploads to the server, and updates the field in SQL, but i'm having a hard time working out how to make it so that the SQL field isn't updated unless an image is uploaded - I've managed to make it work with one image using;
$uploadArtwork = $_FILES['asset_name']['tmp_name'];
if($uploadArtwork == null) {
$sql = "";
}
else {
$sql = "";
}
I am struggling to work out, how i can do it for two images (and eventually more than two images?)
Tried a lot of googling, but without much luck yet!

$uploadArtwork1 = $_FILES['asset_name1']['tmp_name'];
$uploadArtwork2 = $_FILES['asset_name2']['tmp_name'];
// Image1 and/or image2 was uploaded successfully
if(($uploadArtwork1 != null) || ($uploadArtwork2 != null)) {
$sql = "";
// No images were selected, or there were problems uploading them
} else {
$sql = "";
}
Though it would be better to check $_FILES['asset_name']['error'] == UPLOAD_ERR_OK to determine if an image was uploaded successfully:
$uploadArtwork1 = $_FILES['asset_name1']['error'];
$uploadArtwork2 = $_FILES['asset_name2']['error'];
// Image1 and/or image2 was uploaded successfully
if(($uploadArtwork1 == UPLOAD_ERR_OK) || ($uploadArtwork2 == UPLOAD_ERR_OK)) {
// Do something with $_FILES['asset_name1']['tmp_name'] and $_FILES['asset_name2']['tmp_name']
$sql = "";
// No images were selected, or there were problems uploading them
} else {
$sql = "";
}
Update:
require_once("Inc/classCloud.php");
$sql = "UPDATE assets SET asset_title='$post_asset_title'";
if ($uploadArtwork != null) {
$getImageID= $res['data'];
$sql .= ", asset_name='$getImageID'";
}
if ($uploadMock != null) {
$getImageID2= $res2['data'];
$sql .= ", product_artwork='$getImageID2'";
}
$sql .= " WHERE asset_id='$post_asset_id'";

Here is a basic structure to work with.
Basically looping through all uploaded files and if they have been found then move them to a new location on the server and write the entry to database.
This code has not been tested.
<?php
// Loops through all possible file uploads.
foreach ($_FILES as $file) {
// Checks a file has been chosen.
if (isset($file['tmp_name']) && !empty($file['tmp_name'])) {
// Checks the uploaded (object) is a file.
if (is_file($file['tmp_name'])) {
// The filepath for the uploaded file.
$destination = 'LOCATION TO MOVE THE UPLOADED FILE TO';
/*
* Perform SQL Write here
*/
if (WRITE WAS SUCCESSFUL) {
// Move FIle
move_uploaded_file($file['tmp_name'], $destination);
}
}
}
}

Related

update issue with image validation in php

I am new to PHP web development and making a simple website for adding products and categories and I am facing an issue with the update CRUD operation for the categories
when I upload an image.
Updating the image when less than 2MB is ok and the old image will be deleted, for the other scenarios when image is more than 2MB or upload different image extension than the allowed ones it's not being validated only the image name gets added to the database, below is my code and appreciate the help
include("../config/dbconn.php");
if (isset($_POST['update'])) {
$cat_id = mysqli_real_escape_string($dbconn, $_POST['cat_id']);
$cat_name = mysqli_real_escape_string($dbconn, $_POST['cat_name']);
$pervious_cat_name = filter_var($_POST['pervious_cat_name'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$cat_img = $_FILES['cat_img'];
// checking empty fields
if (empty($cat_name) || empty($cat_img)) {
if (empty($cat_name)) {
echo "<font color='red'>category name field is empty!</font><br/>";
}
if (empty($cat_img)) {
echo "<font color='red'>image field is empty!</font><br/>";
}
} else {
//updating the table
if ($cat_img['name']) {
$pervious_cat_path = '../../uploads/' . $pervious_cat_name;
if ($pervious_cat_path) {
unlink($pervious_cat_path);
}
$cat_img_name = $cat_img['name'];
$cat_temp_name = $cat_img['tmp_name'];
$cat_img_destination_path = '../../uploads/' . $cat_img_name;
$allow_files = ['png', 'jpg', 'jpeg','webp'];
$extension = explode('.', $cat_img_name);
$extension = end($extension);
if (in_array($extension, $allow_files)) {
if ($cat_img['size'] < 2000000) {
move_uploaded_file($cat_temp_name, $cat_img_destination_path);
} else {
$_SESSION['category_update'] = "couldn't update category, image size is too large";
}
} else {
$_SESSION['category_update'] = "couldn't update category, image should be png, jpg, jpeg";
}
}
$cat_img_to_insert = $cat_img_name ?? $pervious_cat_name;
$query = "UPDATE category SET cat_name='$cat_name', cat_img='$cat_img_to_insert' WHERE cat_id=$cat_id";
$result = mysqli_query($dbconn, $query);
if ($result) {
//redirecting to the display page. In our case, it is index.php
header("Location: admin_panel.php");
}
}
}
?>
below are a couple of images to see the results:
ok uploaded an image less than 2MB and in the allowed extensions.
image bigger than 2MB and in the allowed extensions.
not allowed image extensions:
appreciate the support.

Upload fails "move uploaded file"

First off, the upload folder is given 777, and my old upload script works, so the server accepts files. How ever this is a new destination.
I use krajee bootstrap upload to send the files. And I receive a Jason response. The error seems to be around move uploaded file. I bet it's a simple error from my side, but I can't see it.
<?php
if (empty($_FILES['filer42'])) {
echo json_encode(['error'=>'No files found for upload.']);
// or you can throw an exception
return; // terminate
}
// get the files posted
$images = $_FILES['filer42'];
// a flag to see if everything is ok
$success = null;
// file paths to store
$paths= [];
// get file names
$filenames = $images['name'];
// loop and process files
for($i=0; $i < count($filenames); $i++){
$ext = explode('.', basename($filenames[$i]));
$target = "uploads" . DIRECTORY_SEPARATOR . md5(uniqid()) . "." . array_pop($ext);
if(move_uploaded_file($_FILES["filer42"]["tmp_name"][$i], $target)) {
$success = true;
$paths[] = $target;
} else {
$success = false;
break;
}
}
// check and process based on successful status
if ($success === true) {.
$output = [];
$output = ['uploaded' => $paths];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];
// delete any uploaded files
foreach ($paths as $file) {
unlink($file);
}
} else {
$output = ['error'=>'No files were processed.'];
}
// return a json encoded response for plugin to process successfully
echo json_encode($output);
?>
I think field name is the issue. Because you are getting image name with filer42 and upload time, you are using pictures.
Please change
$_FILES["pictures"]["tmp_name"][$i]
to
$_FILES["filer42"]["tmp_name"][$i]
And check now, Hope it will work. Let me know if you still get issue.
The error is not in this script but in the post.
I was using <input id="filer42" name="filer42" type="file">
but it have to be <input id="filer42" name="filer42[]" type="file" multiple>
as the script seems to need an arrey.
It works just fine now.

PHP - Renaming a file to disallow duplicates

So I am using this script to upload a file to a directory and show it live.
<?php
function UploadImage($settings = false)
{
// Input allows you to change where your file is coming from so you can port this code easily
$inputname = (isset($settings['input']) && !empty($settings['input']))? $settings['input'] : "fileToUpload";
// Sets your document root for easy uploading reference
$root_dir = (isset($settings['root']) && !empty($settings['root']))? $settings['root'] : $_SERVER['DOCUMENT_ROOT'];
// Allows you to set a folder where your file will be dropped, good for porting elsewhere
$target_dir = (isset($settings['dir']) && !empty($settings['dir']))? $settings['dir'] : "/uploads/";
// Check the file is not empty (if you want to change the name of the file are uploading)
if(isset($settings['filename']) && !empty($settings['filename']))
$filename = $settings['filename'] . "sss";
// Use the default upload name
else
$filename = preg_replace('/[^a-zA-Z0-9\.\_\-]/',"",$_FILES[$inputname]["name"]);
// If empty name, just return false and end the process
if(empty($filename))
return false;
// Check if the upload spot is a real folder
if(!is_dir($root_dir.$target_dir))
// If not, create the folder recursively
mkdir($root_dir.$target_dir,0755,true);
// Create a root-based upload path
$target_file = $root_dir.$target_dir.$filename;
// If the file is uploaded successfully...
if(move_uploaded_file($_FILES[$inputname]["tmp_name"],$target_file)) {
// Save out all the stats of the upload
$stats['filename'] = $filename;
$stats['fullpath'] = $target_file;
$stats['localpath'] = $target_dir.$filename;
$stats['filesize'] = filesize($target_file);
// Return the stats
return $stats;
}
// Return false
return false;
}
?>
<?php
// Make sure the above function is included...
// Check file is uploaded
if(isset($_FILES["fileToUpload"]["name"]) && !empty($_FILES["fileToUpload"]["name"])) {
// Process and return results
$file = UploadImage();
// If success, show image
if($file != false) { ?>
<img src="<?php echo $file['localpath']; ?>" />
<?php
}
}
?>
The thing I am worried about is that if a person uploads a file with the same name as another person, it will overwrite it. How would I go along scraping the filename from the url and just adding a random string in place of the file name.
Explanation: When someone uploads a picture, it currently shows up as
www.example.com/%filename%.png.
I would like it to show up as
www.example.com/randomstring.png
to make it almost impossible for images to overwrite each other.
Thank you for the help,
A php noob
As contributed in the comments, I added a timestamp to the end of the filename like so:
if(isset($settings['filename']) && !empty($settings['filename']))
$filename = $settings['filename'] . "sss";
// Use the default upload name
else
$filename = preg_replace('/[^a-zA-Z0-9\.\_\-]/',"",$_FILES[$inputname]["name"]) . date('YmdHis');
Thank you for the help

How to copy the set of files from one folder to another folder using php

I want to copy set of uploaded files from one folder to another folder.From the below code, all the files in one folder is copied.It takes much time. I want to copy only the currently uploaded file to another folder.I have some idea to specify the uploaded files and copy using for loop.But I don't know to implement.I am very new to developing.Please help me.Below is the code.
<?php
// connect to the database
include('connect-db.php');
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
$file_array=($_FILES['file_array']['name']);
// check to make sure both fields are entered
if ($udate == '' || $file_array=='')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($udate, $file_array, $error);
}
else
{
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
if(isset($_FILES['file_array']))
{
$name_arrray=$_FILES['file_array']['name'];
$tmp_name_arrray=$_FILES['file_array']['tmp_name'];
for($i=0;$i <count($tmp_name_arrray); $i++)
{
if(move_uploaded_file($tmp_name_arrray[$i],"test_uploads/".str_replace(' ','',$name_arrray[$i])))
{
// save the data to the database
$j=str_replace(' ','',$name_arrray[$i]);
echo $j;
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
$provider = mysql_real_escape_string(htmlspecialchars($_POST['provider']));
$existfile=mysql_query("select ubatch_file from batches");
while($existing = mysql_fetch_array( $existfile)) {
if($j==$existing['ubatch_file'])
echo' <script>
function myFunction() {
alert("file already exists");
}
</script>';
}
mysql_query("INSERT IGNORE batches SET udate='$udate', ubatch_file='$j',provider='$provider',privilege='$_SESSION[PRIVILEGE]'")
or die(mysql_error());
echo $name_arrray[$i]."uploaded completed"."<br>";
$src = 'test_uploads';
$dst = 'copy_test_uploads';
$files = glob("test_uploads/*.*");
foreach($files as $file){
$file_to_go = str_replace($src,$dst,$file);
copy($file, $file_to_go);
/* echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Uploaded.\");
window.location = \"uploadbatches1.php\"
</script>";*/
}
} else
{
echo "move_uploaded_file function failed for".$name_array[$i]."<br>";
}
}
}
// once saved, redirect back to the view page
header("Location:uploadbatches1.php");
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','');
}
?>
To copy only the uploaded files, there is only a slight change in the coding which I have made. That is instead of using "." from one folder, I passed the array value. So that only the files which are uploaded will be copied to the new folder instead of copying everything which takes long time.Below is the only change made to do:
$files = glob("test_uploads/$name_arrray[$i]");

Page taking too long to load [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
I find it very difficult to comprehend why one of my pages is taking long before displaying its content. The code on the page is as follows.
Please, advise what could be wrong and if the code is secure. If not how to fix it.
<?php
//open database
include("includes/db_connect.php");
//require("includes/mysql_conn.php");
// Check to see if the type of file uploaded is a valid image type .........................
function is_valid_type($file)
{
// This is an array that holds all the valid image MIME types
// These are the same for all file upload boxes
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif");
// This is an array that holds all valid image extensions
// These are the same for all file upload boxes
$valid_exts = array('jpg', 'jpeg', 'bmp', 'gif');
// This check is optional
if(!in_array($file['type'], $valid_types))
return 0;
// Get the extension from the uploaded filename
$upload_ext = pathinfo($file['name'], PATHINFO_EXTENSION);
// This check is essential for security
if(!in_array($upload_ext, $valid_exts))
return 0;
return 1;
}
//...................................................................................................
// Just a short function that prints out the contents of an array in a manner that's easy to read
// I used this function during debugging but it serves no purpose at run time for this example
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
// Set some constants
// This variable is the path to the image folder where all the images are going to be stored
// Note that there is a trailing forward slash
$TARGET_PATH = "images/";
// Get our POSTed variables
$ctitle = $_POST['ctitle'];
$csubject = $_POST['csubject'];
$creference = $_POST['creference'];
$cyear = $_POST['cyear'];
$cobjecttype = $_POST['cobjecttype'];
$cmaterial = $_POST['cmaterial'];
$ctechnic = $_POST['ctechnic'];
$cwidth = $_POST['cwidth'];
$cheight = $_POST['cheight'];
$cperiod = $_POST['cperiod'];
$cmarkings = $_POST['cmarkings'];
$cdescription = $_POST['cdescription'];
$csource = $_POST['csource'];
$cartist = $_POST['cartist'];
$image = $_FILES['image'];
// Build our target path full string. This is where the file will be moved do
// i.e. images/picture.jpg
$target_path_1 = $TARGET_PATH . $image['name'];
// Sanitize our inputs
$ctitle = mysql_real_escape_string($ctitle);
$csubject= mysql_real_escape_string($csubject);
$creference = mysql_real_escape_string($creference);
$cyear = mysql_real_escape_string($cyear);
$cobjecttype = mysql_real_escape_string($cobjecttype);
$cmaterial = mysql_real_escape_string($cmaterial);
$ctechnic = mysql_real_escape_string($ctechnic);
$cwidth = mysql_real_escape_string($cwidth);
$cheight = mysql_real_escape_string($cheight);
$cperiod = mysql_real_escape_string($cperiod);
$cmarkings = mysql_real_escape_string($cmarkings);
$cdescription = mysql_real_escape_string($cdescription);
$csource = mysql_real_escape_string($csource);
$cartist = mysql_real_escape_string($cartist);
$image['name'] = mysql_real_escape_string($image['name']);
// Make sure all the fields from the form have inputs
if ( $ctitle == "" || $csubject == "" || $creference == "" || $cyear == "" || $cobjecttype == "" || $cmaterial == "" || $ctechnic == "" || $cwidth == "" || $cheight == "" || $cperiod == "" || $cmarkings == "" || $cdescription == "" || $csource == "" || $cartist == "" || $image['name'] == "")
{
echo "All fields are required";
exit;
}
// Check to make sure that our file is actually an image
// You check the file type instead of the extension because the extension can easily be faked
if (!is_valid_type($image))
{
echo "You must upload a jpeg, gif, or bmp";
exit;
}
// Here we check to see if a file with that name already exists
// You could get past filename problems by appending a timestamp to the filename and then continuing
if (file_exists($target_path_1))
{
echo "A file with that name already exists";
exit;
}
// Lets attempt to move the file from its temporary directory to its new home
if (
move_uploaded_file($image['tmp_name'], $target_path_1)
)
{
// NOTE: This is where a lot of people make mistakes.
// We are *not* putting the image into the database; we are putting a reference to the file's location on the server
$sql = "insert into collections (ctitle, csubject, creference, cyear, cobjecttype, cmaterial, ctechnic, cwidth, cheight, cperiod, cmarkings, cdescription, csource, cartist, cfilename) values ('$ctitle', '$csubject', '$creference', '$cyear', '$cobjecttype', '$cmaterial', '$ctechnic', '$cwidth', '$cheight', '$cperiod', '$cmarkings', '$cdescription', '$csource', '$cartist', '" . $image['name'] . "')";
$result = mysql_query($sql) or die ("Could not insert data into DataBase: " . mysql_error());
exit;
}
else
{
// A common cause of file moving failures is because of bad permissions on the directory attempting to be written to
// Make sure you chmod the directory to be writeable
echo "Could not upload file. Check read/write persmissions on the directory";
exit;
}
?>
And my database connection code:
<?php
//set connection variables
$host = "localhost";
$username = "joseph";
$password = "";
$db_name = "collectionsdb"; //database name
//connect to mysql server
$mysqli = new mysqli($host, $username, $password, $db_name);
//check if any connection error was encountered
if(mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}
?>
Thanx.
Joseph
Seems fine to me.
There are three stages.
Time to upload the data(depends on filesize and connection speed)
connect to the database(depends on the load on your database server)
and the moving of the file on the server(depends on the load of your server) ...
If you are on a local test system there could be the virus scan interfering as well. First filtering the post data then scanning the file and scanning the file again when moved(yes, they can be pretty paranoid...).
Advice: Put some "print_r(microtime());" in there and take a look.
The code is not necessarily secure. Sql injection is on thing that I is easily spotted. Do not pass the variables into the query string like that. Although you are using mysql_real_escape_string() there are scenarios where this is not adequate.
Please use parametrized queries. Also you should worry about html markup inserted into your db that could be used for XSS.
Another point to keep in mind is the permissions for you upload folder. Make sure you don't have everyone read and write.
Hope it helps.
See my comment for additional info about the root cause of your slow loads.

Categories