I know this question is repeated over and over.. But can't seem to find solution for my problem...
How can I create a form which will allow user to upload xy images at once?
Here's my html code:
<form class="pure-form" action="upload.php" enctype="multipart/form-data" method="post">
<div class="upload">
<a onclick="select_file()" class="pure-button">Choose a Image</a>
<input id="image" type="file" name="image[]" multiple="multiple">
</div>
<!--image preview-->
<img src="" style="display:none">
<input class="pure-button pure-button-primary" type="submit" value="Upload!">
</form>
And here's my php code:
$valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$max_size = 2048 * 1024; // max file size (200kb)
$path = 'uploads/'; // upload directory
if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
{
if( #is_uploaded_file($_FILES['image']['tmp_name']) )
{
// get uploaded file extension
$ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
// looking for format and size validity
if (in_array($ext, $valid_exts) AND $_FILES['image']['size'] < $max_size)
{
// unique file path
$path = $path . uniqid(). '.' .$ext;
// move uploaded file from temp to uploads directory
if (move_uploaded_file($_FILES['image']['tmp_name'], $path))
{
$status = 'Image uploaded successfully!';
$status = $path;
}
else {
$status = 'Upload Fail: Unknown error occurred!';
}
}
else {
$status = 'Upload Fail: Unsupported file format or It is too large to upload!';
}
}
else {
$status = 'Upload Fail: File not uploaded!';
}
}
else {
$status = 'Bad request!';
}
// echo out json encoded status
echo json_encode(array('status' => $status));
?>
Is it possible to solve this problem with foreach? If so, how should I do that?
Try this (add as many file fields as you want):
<input type="file" name="image[]" /><br />
<input type="file" name="image[]" /><br />
<input type="file" name="image[]" /><br />
<input type="file" name="image[]" />
Php:
$valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$max_size = 2048 * 1024; // max file size (200kb)
$path = 'uploads/'; // upload directory
if(isset($_FILES['image'])){
for($i=0; $i<count($_FILES['image']['name']); $i++){
if( #is_uploaded_file($_FILES['image']['tmp_name'][$i]) )
{
// get uploaded file extension
$ext = strtolower(pathinfo($_FILES['image']['name'][$i], PATHINFO_EXTENSION));
// looking for format and size validity
if (in_array($ext, $valid_exts) AND $_FILES['image']['size'][$i] < $max_size)
{
// unique file path
$path = $path . uniqid(). '.' .$ext;
// move uploaded file from temp to uploads directory
if (move_uploaded_file($_FILES['image']['tmp_name'][$i], $path))
{
$status = 'Image uploaded successfully!';
$status = $path;
}
else {
$status = 'Upload Fail: Unknown error occurred!';
}
}
else {
$status = 'Upload Fail: Unsupported file format or It is too large to upload!';
}
}
else {
$status = 'Upload Fail: File not uploaded!';
}
echo "<p>$status</p>";
}
}
?>
<form class="pure-form" action="upload.php" enctype="multipart/form-data" method="post">
<div class="upload">
<a onclick="select_file()" class="pure-button">Choose a Image</a>
<input id="image" type="file" name="image[1]" multiple="multiple">
<input id="image" type="file" name="image[2]" multiple="multiple">
</div>
<!--image preview-->
<img src="" style="display:none">
<input class="pure-button pure-button-primary" type="submit" value="Upload!">
</form>
PHP
$valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$max_size = 2048 * 1024; // max file size (200kb)
$path = 'uploads/'; // upload directory
if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
{
if( #is_uploaded_file($_FILES['image1']['tmp_name']) )
{
// get uploaded file extension
$ext = strtolower(pathinfo($_FILES['image1']['name'], PATHINFO_EXTENSION));
// looking for format and size validity
if (in_array($ext, $valid_exts) AND $_FILES['image1']['size'] < $max_size)
{
// unique file path
$path = $path . uniqid(). '.' .$ext;
// move uploaded file from temp to uploads directory
if (move_uploaded_file($_FILES['image1']['tmp_name'], $path))
if( #is_uploaded_file($_FILES['image2']['tmp_name']) )
{
// get uploaded file extension
$ext = strtolower(pathinfo($_FILES['image2']['name'], PATHINFO_EXTENSION));
// looking for format and size validity
if (in_array($ext, $valid_exts) AND $_FILES['image2']['size'] < $max_size)
{
// unique file path
$path = $path . uniqid(). '.' .$ext;
// move uploaded file from temp to uploads directory
if (move_uploaded_file($_FILES['image2']['tmp_name'], $path))
{
$status = 'Image uploaded successfully!';
$status = $path;
}
else {
$status = 'Upload Fail: Unknown error occurred!';
}
}
else {
$status = 'Upload Fail: Unsupported file format or It is too large to upload!';
}
}
else {
$status = 'Upload Fail: File not uploaded!';
}
}
else {
$status = 'Bad request!';
}
}}
// echo out json encoded status
echo json_encode(array('status' => $status));
?>
Related
I have made a form on php and I am adding an image input option there.
<form action="./assets/actions/gallery_post.php" id="upload-form" method="POST">
<input type="text" name="title" placeholder="Image title..." class="form-control" required>
<br>
<input type="text" name="description" placeholder="Image description..." class="form-control">
<br>
<input type="file" name="file", class="form-control" required>
<br>
<button type="submit" name="picture-submit" class="form-control submit">Upload Photo</button>
</form>
The following is my php code to upload the file.
// Check if the button was pressed
if (isset($POST['picture-submit'])) {
echo "Entered";
// Get the inputs
$newfilename = 'gallery';
$title = $_POST['title'];
$description = $_POST['description'];
$file = $_FILES['file'];
if($file){
echo "FILE";
}else{
echo "No File found";
}
console.log($file);
// Obtaining some file information
$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileError = $file['error'];
$fileType = $file['type'];
// Checking file extensions
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
echo "$fileActualExt";
// Allowed extensions
$allowed = array('jpeg', 'jpg', 'png', 'JPG');
// if extension is allowed
if(in_array($fileActualExt, $allowed)){
// check if any error
if($fileError === 0){
// Creating a unique file name
$fileNew = $newfilename. "." . uniqid('', true) . "." . $fileActualExt;
$fileDest = "assets/images/gallery/" . $fileNew;
// Function to upload file
move_uploaded_file($fileTmpName, $fileDest);
// Making a database connection
include_once ('dbh.php');
$stmt = mysqli_stmt_init($conn);
// Move to the database as well using prepared statements
$sql = "INSERT into gallery(location, title, description) VALUES(?, ?, ?)";
echo $sql;
// Binding parameters
mysqli_stmt_bind_param($stmt, "sss", $fileDest, $title, $description);
mysqli_stmt_execute("$stmt");
// Perform a query, check for error
mysqli_query($conn, $sql) or die(mysqli_error($conn));
echo "Query Sent";
header("Location: ../gallery.php?upload=sucess");
}else {
echo "There was an error in file upload.";
}
}else {
echo "You cannnot upload files of this type!";
}
}
It is not even entering the if condition in the above scenario. When I remove the if condition, I get "No file Found". Sort of stumped here now because I have made it work in the past. I even tried the basic HTML query format like this mysqli_query($conn, $sql) or die(mysqli_error($conn)); and this does not work either.
Your form tag has to be enabled enctype="multipart/form-data".
Try this code.
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
// 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'm trying to upload a file to a server then display it to the user. I'm having difficulties to display the image to the user.
If you could provide code that helps me out to display the image to the user. The code should fit in the php file right under //Display image here <---------
html file
<html>
<body>
<form method="post" enctype="multipart/form-data" action="server.php">
<input type="file" name="fileToUpload" id="fileToUpload" size="35">
<br>
<br>
<input type="submit" value="Upload" name="upload">
</body>
</html>
php file
<?php
if(isset($_FILES["fileToUpload"])){
$file = $_FILES['fileToUpload'];
$fileName = $_FILES["fileToUpload"]["name"];
$fileTmpName = $_FILES["fileToUpload"]["tmp_name"];
$fileSize = $_FILES["fileToUpload"]["size"];
$fileError = $_FILES["fileToUpload"]["error"];
$fileType = $_FILES["fileToUpload"]["type"];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
if(in_array($fileActualExt, $allowed)){
//Image code
if($fileError === 0){
if($fileSize < 500000){
$fileDestination = 'uploads/'.$fileName;
move_uploaded_file($fileTmpName, $fileDestination);
header("Location: server.php?uploadsuccess");
//Display image here <----------
}else{
echo "Your file is too big!";
}
}else{
echo "There was an error while uploading your file!";
}
}else{
if(isset($_FILES["fileToUpload"])){
$file = $_FILES["fileToUpload"]["name"];
echo "File: ".$file;
}
}
}
?>
first you have to change .html file to .php and note that i have renamed file as index.php
<html>
<body>
<?php if(isset($_GET['filename'])){ ?>
<img src="<?php echo $_GET['filename']; ?>" />
<?php } ?>
<form method="post" enctype="multipart/form-data" action="server.php">
<input type="file" name="fileToUpload" id="fileToUpload" size="35">
<br>
<br>
<input type="submit" value="Upload" name="upload">
</body>
</html>
server.php
<?php
if(isset($_FILES["fileToUpload"])){
$file = $_FILES['fileToUpload'];
$fileName = $_FILES["fileToUpload"]["name"];
$fileTmpName = $_FILES["fileToUpload"]["tmp_name"];
$fileSize = $_FILES["fileToUpload"]["size"];
$fileError = $_FILES["fileToUpload"]["error"];
$fileType = $_FILES["fileToUpload"]["type"];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
if(in_array($fileActualExt, $allowed)){
//Image code
if($fileError === 0){
if($fileSize < 500000){
$fileDestination = 'uploads/'.$fileName;
move_uploaded_file($fileTmpName, $fileDestination);
// header("Location: server.php?uploadsuccess");
//Display image here <----------
header("Location:index.php?filename=$fileDestination");
}else{
echo "Your file is too big!";
}
}else{
echo "There was an error while uploading your file!";
}
}else{
if(isset($_FILES["fileToUpload"])){
$file = $_FILES["fileToUpload"]["name"];
echo "File: ".$file;
}
}
}
?>
I have done using php but better option is using ajax call .just google it you will get man examples
To be able to display the image, do this :
//Display image here <----------
echo "<img src='" . $fileLocation . "'>";
Replace $file_location with the variable containing the file location
<!-- index.php -->
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file2upload">
<input type="submit" value="upload">
</form>
<!-- sorry i didn't got php code section here , so i m posting php file code here -->
<!-- upload.php file -->
<?php
// target directory where files goes after uploading
$target_dir = "uploads/pictures/";
// target files name and extension save to this target_file variable
// $target_file specifies the path of the file to be uploaded
$target_file = $target_dir . basename($_FILES["file2upload"]["name"]);
$uploadOk = 1;
// checking that target_file is been uploading is a true image file extenion or not
// $audioFileType holds the file extension of the file (in lower case)
$picFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
echo $picFileType."<br />";
if(isset($_POST["submit"])) {
// The filesize() function in PHP is an inbuilt function which is used to return the size of a specified file.
// The filesize() function accepts the filename as a parameter and returns the size of a file in bytes on success and False on failure.
$check = getimagesize($_FILES["file2upload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// step:2
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// step: 3
// Check file size
if ($_FILES["file2upload"]["size"] > 5000000) { // 5MB manual set
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// step: 4
// Allow certain file formats
if($picFileType != "jpeg" && $picFileType != "jpg" && $picFileType != "bmp" && $picFileType != "gif" && $picFileType != "png" ) {
$uploadOk = 0;
echo "<b style='color:red;'> File to be uploading is not have image formates like : .jpeg,.jpg,.bmp, .gif, .png etc </b><br />";
}
// step: 5
// 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["file2upload"]["tmp_name"], $target_file))
{
echo "The file ". basename( $_FILES["file2upload"]["name"]). " has been uploaded. <br />";
<!-- this is the ANSWER -->
<!-- ----------------------------- -->
echo $file_name = basename( $_FILES["file2upload"]["name"]);
echo $file_size = $_FILES["file2upload"]["size"];
echo $fileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
<!-- ----------------------------- -->
}
else {
echo "Sorry, there was an error uploading your file.";
}
}
// }else{ echo "<b style='color:red;'> form have diffrent method ( post/get ) </b><br />"; $uploadOk = 0; }
?>
I'm new in PHP area. This is my try to upload a file:
<?php
if(isset($_FILES['file'])) {
$file = $_FILES['file'];
if($file['error'] === 0) {
$distination = 'uploads/';
$file_ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = $distination . uniqid('', true) . '.' . $file_ext;
if(!move_uploaded_file($file['name'], $filename)) {
echo "File upload failed!";
}
}
}
?>
<form action="testupload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
the return value from the move_uploaded_file always false. I create the uploads folder in the same directory as the upload script file.
Your main problem is fact that you use name instead of tmp_name value from $_FILES array.
name is original name of uploaded file, tmp_name is location of file after upload. Manual Page
Fixed version below. I also added check for destination directory and automatic creation of it if not available.
<?php
if(isset($_FILES['file'])) {
$file = $_FILES['file'];
if($file['error'] === 0) {
$distination = 'uploads/';
if(!file_exists($distination)){
mkdir($distination, 0777, true);
}
$file_ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = $distination . uniqid('', true) . '.' . $file_ext;
print_r($file);
if(!move_uploaded_file($file['tmp_name'], $filename)) {
echo "File upload failed!";
}
}
}
?>
<form action="testupload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
I know how to upload image file and save to other location by using the following code. However, I need to do in such a way that user upload image and automatically convert to base64 without saving that image in my location. How should I do?
<?php
//print_r($_FILES);
if(isset($_FILES['image']))
{
$errors=array();
$allowed_ext= array('jpg','jpeg','png','gif');
$file_name =$_FILES['image']['name'];
// $file_name =$_FILES['image']['tmp_name'];
$file_ext = strtolower( end(explode('.',$file_name)));
$file_size=$_FILES['image']['size'];
$file_tmp= $_FILES['image']['tmp_name'];
echo $file_tmp;echo "<br>";
$type = pathinfo($file_tmp, PATHINFO_EXTENSION);
$data = file_get_contents($file_ext);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
echo "Base64 is ".$base64;
if(in_array($file_ext,$allowed_ext) === false)
{
$errors[]='Extension not allowed';
}
if($file_size > 2097152)
{
$errors[]= 'File size must be under 2mb';
}
if(empty($errors))
{
if( move_uploaded_file($file_tmp, 'images/'.$file_name));
{
echo 'File uploaded';
}
}
else
{
foreach($errors as $error)
{
echo $error , '<br/>';
}
}
// print_r($errors);
}
?>
<form action="" method="POST" enctype="multipart/form-data">
<p>
<input type="file" name="image" />
<input type="submit" value="Upload">
</p>
</form>
There is a mistake in your code:
$data = file_get_contents( $file_ext );
This should be:
$data = file_get_contents( $file_tmp );
This should solve your problem.
I have a script:
if(isset($_FILES['image'])){
$errors = array();
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$file_name = $_FILE['image']['name'];
$file_ext = strtolower(end(explode('.', $file_name)));
$file_size = $_FILE['image']['size'];
$file_tmp = $_FILE['image']['tmp_name'];
if(in_array($file_ext, $allowed_ext) === false){
$errors[] = 'Extension not allowed';
}
if($file_size > 2097152){
$errors[] = 'file size must be under 2mb';
}
if(empty($errors)){
if(move_uploaded_file($file_tmp, "../../img/usr/profile/.$file_name")){
echo 'File uploaded';
}
}else{
foreach($errors as $error){
echo $error, '<br>';
}
}
}
And it's not working. It is supposed to upload an image to a certain directory. Here's the html:
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="image">
<input type="submit" name="submit" value="Update Info">
</form>
When I click submit, there is an error at the top of the screen saying 'Extension not allowed'. The html and php is in the same file (I just gave you a small snippet.) Does anything look wrong with my code? thanks!
To access the files, you have to use the $_FILES variable.
In your code, you have sometimes used $_FILE, which does not work ;)