move_uploaded_file - file name of image? - javascript

The Script:
<?php
if (isset($_POST['submit'])) {
$j = 0; //Variable for indexing uploaded image
$target_path = "uploads/"; //Declaring Path for uploaded images
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed
$ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
$file_extension = end($ext); //store extensions in the variable
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
$j = $j + 1;//increment the number of uploaded images according to the files in array
if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else {//if file was not moved.
echo $j. ').<span id="error">please try again!.</span><br/><br/>';
}
} else {//if file size and file type was incorrect.
echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
?>
This script also uses javascript for multiple image upload.
This script works fine, though when the multiple files get moved into the "uploads" folder the file names come out like this:
"2f594262c1f8fb56c39cc01d4543bcb9.jpg"
"2f594262c1f8fb56c39cc01d4543bcb9.jpgf00008a16882f01d2bd7ed6d9805a4bf.jpg"
"2f594262c1f8fb56c39cc01d4543bcb9.jpgf00008a16882f01d2bd7ed6d9805a4bf.jpge967f7fbaea4e2aee9b6f56067739aed.jpg"
How to solve this issue?

Reset your $target_path inside the for loop. Right now you're just continually appending to it.
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array
$target_path = "uploads/"; //Declaring Path for uploaded images

Related

Uploading capture image and store it in a folder changing it's filename to be unique using the userID

I have this code from this reference https://github.com/jhuckaby/webcamjs/blob/master/DOCS.md?fbclid=IwAR0Q3W5mw8qWlJEdiabmyZJiw7wGJ5YDPRl2Ej0IKF3GCt_78HXeqAEjI6Y
it will display the webcam and take snapshots and make it to an image element using the data_uri but the problem is I want to get that file and store it with a declared filename into a folder here's the script I use
<script src="webcam.js"></script> <!--source code script from github for webcam config-->
<div id="my_camera" style="width:320px; height:240px;"></div>
<div id="my_result"></div>
<script type=text/javascript>
Webcam.attach( '#my_camera' );
function take_snapshot() {
Webcam.snap( function(data_uri) {
document.getElementById('my_result').innerHTML = '<img src="'+data_uri+'"/>';
} );
}
</script>
Take Snapshot
I have a button called register that functions like get all information being input and store it into the database like username first name etc together with the image taken by snapshot, here's my upload script in uploading images from a folder and I want to use it as getting the image data_uri and store it in a folder when I click the register button
<?php
session_start();
include_once'database.php';
$uid = $_SESSION['u_id'];
if (isset($_POST['submit'])){
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
//check if ang uploaded file allowed i upload//
if (in_array($fileActualExt, $allowed)){
if ($fileError == 0){
if ($fileSize < 1000000){
$fileNameNew = "profile".$uid.".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
$sql = "UPDATE profileimg SET status=0 WHERE userID ='$uid';";
$result = mysqli_query($conn, $sql);
header("location:../pages/userpage.php");
}
else {
echo "Your file is too big";
}
} else {
echo "There was an error uploading you file!";
}
} else {
echo "You cannot upload files of this type";
}
}
I'm going to use this function as stated in the documentation
Webcam.upload( data_uri, 'myscript.php', function(code, text) {
// Upload complete!
// 'code' will be the HTTP response code from the server, e.g. 200
// 'text' will be the raw response content
} );
} );
and have this in my php script
move_uploaded_file($_FILES['webcam']['tmp_name'], 'webcam.jpg');
any idea how should I turn this script into the one I use above in my upload.php? thanks in advance
You need to create image first by image src and then need to save that in a specific folder. You can follow below code:
file_put_contents("fileNameWithLocation.png",file_get_contents($imageSrc));
Here fileNameWithLocation.png will be $fileNameNew = "profile".$uid.".".$fileActualExt; $fileDestination = 'uploads/'.$fileNameNew; You need to make modification accordingly. And $imageSrc will be the image src which you can post via Ajax or form submission.
Hope it helps you.

Upload Images as array

I am trying to upload multiple images to a folder and is working properly. I have a problem when i am trying to store the name of images in database. If i upload just one is working. If i upload more than one I get just one name in my database.
Whats the way to upload, making an array with images titles, to my db?
Here is the code:
<div id="maindiv">
<div id="formdiv">
<h4>Upload Image for </h4>
<form enctype="multipart/form-data" action="" method="post">
<p class="alert alert-info">Only JPEG,PNG,JPG Type Image Uploaded. Image Size Should Be Less Than 100KB.</p>
<hr/>
<div id="filediv"><input name="file[]" type="file" id="file"/></div><br/>
<input type="button" id="add_more" class="upload" value="Add More Files"/>
<input type="submit" value="Upload File" name="add_images" id="upload" class="upload"/>
</form>
</div>
And here is my php:
if (isset($_POST['add_images'])) {
$j = 0;
$target_path = "images/";
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
$validextensions = array("jpeg", "jpg", "png");
$ext = explode('.', basename($_FILES['file']['name'][$i]));//store extensions in the variable
$name_of_img = basename($_FILES['file']['name'][$i]);
$target_path = $target_path . $name_of_img;
$j = $j + 1;
if (($_FILES["file"]["size"][$i] < 1000000)
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
print_r($name_of_img);
$query = "UPDATE post SET ";
$query .= "images = '{$name_of_imgs}' ";
$query .= "WHERE post_id = {$the_post_id}";
$update_cruise_img = sqlsrv_query($con, $query);
} else {
echo $j. ').<span id="error">please try again!.</span><br/><br/>';
}
} else {//if file size and file type was incorrect.
echo $j. ').<span id="error">Wrong file Size or Type</span><br/><br/>';
}
}
}
I tried by creating array like this $name_of_imgs = json_encode($_POST['file']);
but is not working
You need to update the post table outside the for loop.
if (isset($_POST['add_images'])) {
$j = 0;
$name_of_imgs = [];
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
$validextensions = array("jpeg", "jpg", "png");
$ext = explode('.', basename($_FILES['file']['name'][$i]));//store extensions in the variable
$name_of_img = basename($_FILES['file']['name'][$i]);
// define target path here so that it won't concat the last value
$target_path = "images/" . $name_of_img;
$j = $j + 1;
if (($_FILES["file"]["size"][$i] < 1000000) && in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
$name_of_imgs[] = $name_of_img;
} else {
echo $j. ').<span id="error">please try again!.</span><br/><br/>';
}
} else {//if file size and file type was incorrect.
echo $j. ').<span id="error">Wrong file Size or Type</span><br/><br/>';
}
}
// update here
$query = "UPDATE post SET ";
$query .= "images = '" . implode(',', $name_of_imgs) . "' ";
$query .= "WHERE post_id = {$the_post_id}";
$update_cruise_img = sqlsrv_query($con, $query);
}
You may consider creating another table for images.
Hello you have run update query in upload file. it's make sure this_post_id in single that's way may be update record in single file name.

How to display PHP echo with JavaScript in HTML?

I want to transfer PHP echo text into HTML through JavaScript.I've seen that it can be done with the function document.getelementbyid() and innerHTML but I tried and it did not work.
This PHP Code:
<?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"] > 500000) {
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.";
}
}
?>
I want to echo the text displays in HTML Without switching to upload.php!!
On id statusbar I want to show echo text!
This HTML code:
<form action="../assets/php/upload.php" method="post" enctype="multipart/form-data">
<label>Izaberi fotografiju:</label>
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit" onClick="info()">
<p id="statusbar"></p>
</form>
let's say you have to print this in your uploading html page
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
}
change this to below
if ($uploadOk == 0) {
$message = "Sorry, your file was not uploaded.";
header("Location: /index.php?message="$message);
// if everything is ok, try to upload file
}
then get the message and print in your html page
You have to write code inside <?php ?> tag.Like this.
<script type="text/javascript">
//js code..
<?php echo "Sory, only PNG, JPG, GIF"; ?>
</scrip>
You can directly echo things to html. You can also echo things to a js variable directly like this, then set the html content with js.
<script>
var string = <?php echo "Sory, only PNG, JPG, GIF"; ?>
document.getElementById("notify-container").innerText = string;
</script>
Say your HTML element was the following:
<div id="error"></div>,
you'd assign the error message to a JavaScript variable like so: <script>
var errorMsg = <?php echo "Sory, only PNG, JPG, GIF"; ?>
</script>
Then you can show the message like so:
document.getElementById('error').innerHTML = errorMsg;

Php upload multiple images along with two input text field eg:email and folder name

PHP upload multiple images along with two input text field eg:email and folder name here is my code where I should add code that I could send multiple images along email and folder name:
$max_size = 1024*1024*30; // 30mb
$extensions = array('jpeg', 'jpg', 'png');
$dir = 'http://54.221.28.145:8080/kv_image_rest_service/rest/files/upload';
$count = 0;
if ($_SERVER['REQUEST_METHOD'] == 'POST' and isset($_FILES['files']))
{
// loop all files
foreach ( $_FILES['files']['name'] as $i => $name )
{
// if file not uploaded then skip it
if ( !is_uploaded_file($_FILES['files']['tmp_name'][$i]) )
continue;
// skip large files
if ( $_FILES['files']['size'][$i] >= $max_size )
continue;
// skip unprotected files
if( !in_array(pathinfo($name, PATHINFO_EXTENSION), $extensions) )
continue;
// now we can move uploaded files
if( move_uploaded_file($_FILES["files"]["tmp_name"][$i], $dir . $name) )
$count++;
}
}
echo json_encode(array('count' => $count));

DropzoneJS As Part Of PHP Form

I have this simplified situation :
<form action='process.php' method='post'>
<div class="dropzone no-margin">
<div class="fallback">
<input name="file" type="file" multiple/>
</div>
</div>
</form>
$(".dropzone").dropzone({
url: "/test2.php",
maxFilesize: 2,
maxFiles: 5
});
test2.php works just fine, it upload files dropped on the dropzone immediately. but, the problem is, I need to pass those file names of uploaded files to the form as hidden text input.
here's test2.php looks like :
<?php
$target_dir = "user/product/";
$target_file = $target_dir . basename($_FILES["file"]["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["file"]["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"] > 500000) {
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["file"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
I'm a beginner in javascript or jquery world. So, I really need your help to give me a clue how to pass the file names to the form as hidden text input so it can be written into database later on.
thank you so much and I really appreciate you help.
Try this :
there is method in Dropzone i.e sending that will use to send data before file is sent.if multiple files are uploaded then use sendingmultiple method.
$(".dropzone").dropzone({
url: "/test2.php",
maxFilesize: 2,
maxFiles: 5,
sending:function (data, xhr, formdata) {
console.log("data :",data);
//here you can get file name from data variable.you can add that to your form by following line.
formdata.append('hidden field name', 'file name');
//you can add as much parameter you want to pass to your post data by formdata.append() function. That will add data to your form data.you can refer that value by using $_POST['hidden_field_name'] at PHP side.
}
});
Please check following link for detail :
http://www.dropzonejs.com/#events

Categories