PHP FileUpload is not working - php

I am on Ubuntu. I am trying to take user file upload of small images. I checked the $_FILES it's filled with data. I tried to debug the move command but it doesnot echo anything.
if ($_SERVER['REQUEST_METHOD'] == 'POST' ){
//Now handle everything
if(isset($_POST["submit"])) {
print_r($_FILES);
//Store the image
if(!empty($_FILES['uploaded_file']))
{
$path = "/neel/public/img/";
$path = $path.basename($_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
echo 'Its working';
} else{
echo 'I am done!!!';
die();
}
}
createnewEvent($conn);
header('Location:/neel/index.php');
}
}

You can check if the file exists by checking its name.
if(!empty($_FILES['file']['name']))
Where file is the name of input field for file.

P. G above here is correct.
Instead of checking, if $_POST['submit']
You should check this:
if(isset($_FILES['uploaded_file']['name']))

Try this code it's a complete sign up form with PHP , Bootstrap
HTML
<div class="container">
<div class="row">
<br>
<h1 class="text-center">Create new account</h1>
<br>
<div class="col-lg-4 col-md-6 col-sm-12">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<div class="form-group">
<input type="text" class="form-control form-control-lg" name="name" placeholder="Your Name">
</div>
<div class="form-group">
<input type="text" class="form-control form-control-lg" name="username" placeholder="Username">
</div>
<div class="form-group">
<input type="password" class="form-control form-control-lg" name="password" placeholder="Password">
</div>
<div class="form-group text-center">
<div class='file-input'>
<input type='file' name="profile-img">
<span class='button label' data-js-label>Choose your profile image</span>
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-success form-control form-control-lg" name="signup" value="Signup">
</div>
</form>
</div>
</div>
</div>
PHP
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors;
if (empty($_POST['name'])) {
$errors[] = "Name field is empty";
}
if (empty($_POST['username'])) {
$errors[] = "Username field is empty";
}
if (empty($_POST['password'])) {
$errors[] = "Password field is empty";
}
if (empty($_FILES['profile-img'])) {
$errors[] = "You should upload profile image";
} else{
$img = $_FILES['profile-img'];
$ext = end(explode('.', $img['name']));
$allowed_extensions = array('jpg', 'jpeg', 'png', 'gif');
$max_size = 4; //MegaBytes
if (! in_array($ext, $allowed_extensions)) {
$errors[] = "Please , Choose a valid image";
}
$img_size = $img['size'] / 1000000; // By Megabyte
if ($img_size > $max_size) {
$errors[] = "This picture is so large";
}
}
if (!empty($errors)) {
echo '<div class="container">';
foreach ($errors as $error) {
echo '
<div class="alert alert-danger" role="alert">
' . $error . '
</div>
';
}
echo "</div>";
} else {
$username = filter_var(htmlentities(trim($_POST['username'])), FILTER_SANITIZE_STRING);
$name = filter_var(htmlentities(trim($_POST['name'])), FILTER_SANITIZE_STRING);
$password = sha1(filter_var(htmlentities(trim($_POST['password'])), FILTER_SANITIZE_STRING));
// Profile Picture :-
$imgname = uniqid(uniqid()) . #date("Y-m-d") . "." . $ext;
$target_bath = "uploads/imgs/";
$target_bath = $target_bath . basename($imgname);
$orginal_img = $img['tmp_name'];
if (move_uploaded_file($orginal_img, $target_bath)) {
$sql = "INSERT INTO users(name, username, password,profile_picture, r_d) VALUES ('$name', '$username', '$password', '$target_bath', NOW())";
$result = mysqli_query($conn, $sql);
header('location: ./login.php');
}
}
}

The script you've shown shown will only "not echo anything" if $_SERVER['REQUEST_METHOD'] is not "POST". Assuming your description of events is accurate, then the problem is in the form #halojoy has asked that you show here.
I do hope that you are not redirecting the script back to itself. Also you shouldn't attempt to do a redirect after an echo.

Related

Form with Upload file attachment

I am using contact.php for contact form. I added an attachment field for upload file/image, pdf, docx in contact form using . But i can not integrate php functions for file attachment. I am weak in php, but this is very important for me to add this in my contact form.
Please someone help me. My form code and php code are given below. Thanks in advance.
//** This is html markup
<form id="Frmgroupa" class="form-style" method="post" onsubmit="return validator4(this)" action="contact.php">
<div class="col-md-6">
<div class="form-group">
<label for="form_name">Name of Candidate *</label>
<input type="text" id="name" class="form-control" name="name" placeholder="Name" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['name'] : '' ?>" placeholder="" required autofocus />
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_need">State</label>
<select id="State" class="form-control" name="State" placeholder="" required autofocus>
<option value="UTTAR PRADESH">UTTAR PRADESH</option>
</select>
</div>
</div>
<div class="col-md-6">
<p>Address Proof *</p>
<div class="custom-file mb-3">
<input type="file" class="custom-file-input" id="Address_Proof" name="filename" >
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
</div>
<div class="col-md-6">
<p>Identity Proof *</p>
<div class="custom-file mb-3">
<input type="file" class="custom-file-input" id="Identity_Proof" name="filename">
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
</div>
</div>
<input type="submit" class="btn btn-warning btn-3d" value="SUBMIT" id="submit-button" />
<?php unset($_SESSION['cf_returndata']); ?>
</form>
//* This is the contact.php code
<?php
$myemail = "amit.joshi98#gmail.com";
$subject = "file Upload";
/* Check all form inputs using check_input function */
$name = check_input($_POST['name'], "Enter your name");
$State = $_POST['State'];
/* If URL is not valid set $website to empty */
if (!preg_match("/^(https?:\/\/+[\w\-]+\.[\w\-]+)/i", $website))
{
$website = 'http://google.com';
}
/* Let's prepare the message for the e-mail */
$message = "Hello!
Your contact form has been submitted by:
Name: $name
State: $State
End of message
";
/* Send the message using mail() function */
mail($myemail, $subject, $message);
/* Redirect visitor to the thank you page */
header('Location: thank-you.html');
exit();
/* Functions we used */
function check_input($data, $problem = '')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<b>Please correct the following error:</b><br />
<?php echo $myError; ?>
</body>
</html>
<?php
exit();
}
?>
First you need to write the following phrase in the form tag
enctype="multipart/form-data"
Like this ...
<form action="process.php" method="post" enctype="multipart/form-data">
and then in process.php file check submit and save file in your path
$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 = 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;
}
}
for limit file Type
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
for last check error and set message for user
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 ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
you can Check if file already exists or Check file size
But i suggest you write an uploader function for the file and use it wherever you want.
In this example, photo file types were used that you can change according to your needs

Is it possible to have multiple enctypes on an html form?

I'm very new to any web development issues and I couldn't find a solution to this problem. I have a form for uploading files so I use the enctype="multipart/form-data". However, I was also trying to take the fields from the form and encode them in a JSON file and read those out in a table in my html on my webpage. With the default enctype, the JSON encoding works great but obviously the file upload functionality doesn't work and vice versa. I followed a lot of W3Schools tutorials but I'm still lost. Is it possible to use two enctypes or what is the work around to this problem? I'm only uploading my files to localhost, no databases used. I apologize if I give too much info here but my form html looks like:
<form class="modal-content animate" enctype="multipart/form-data" method="post">
<div class="imgcontainer">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
</div>
<div class="container">
<label for="artist"><b>Artist Name</b></label>
<input class="form-control" type="text" placeholder="Enter name of artist" name="artist" required>
<label for="song"><b>Song Name</b></label>
<input class="form-control" type="text" placeholder="Enter name of song." name="song" required>
<label for="instrument"><b>Instrument Type</b></label>
<input class="form-control" type="text" placeholder="Enter type of instrument for tab." name="instrument" required>
<label for="myfile"><b>Tablature</b></label>
<input class="form-control" type="file" placeholder="Select your file." name="myfile" id="myfile" required>
<input type="submit" name="submit" value="Upload Tab PDF" class="w3-hover-purple" style="color:black; background-color:#A9A9A9"></input>
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
</div>
</form>
My php code is structured as such:
<?php
$message = '';
$error = '';
if(isset($_POST["submit"])) {
if(empty($_POST["artist"])) {
$error = "<label class='text-danger'>Enter artist</label>";
}
else if(empty($_POST["song"])) {
$error = "<label class='text-danger'>Enter song name</label>";
}
else if(empty($_POST["instrument"])) {
$error = "<label class='text-danger'>Enter instrument</label>";
}
else if(empty($_POST["myfile"])) {
$error = "<label class='text-danger'>Enter file to upload</label>";
}
else {
if(file_exists('tablature.json')) {
$current_data = file_get_contents('tablature.json');
$array_data = json_decode($current_data, true);
$extra = array(
'artist' => $_POST['artist'],
'song' => $_POST['song'],
'instrument' => $_POST['instrument'],
'myfile' => $_POST['myfile']
);
$array_data[] = $extra;
$final_data = json_encode($array_data);
if(file_put_contents('tablature.json', $final_data)) {
$message = "<label class='text-success'>File Appended Successfully.</label>";
}
else {
$error = 'JSON File does not exist';
}
}
}
$target_dir = "Tablature/";
$target_file = $target_dir . basename($_FILES["myfile"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if file already exists
if (file_exists($target_file)) {
$error = "Sorry, file already exists.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$error = "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["myfile"]["tmp_name"], $target_file)) {
$message = "The file has been uploaded.";
} else {
$error = "Sorry, there was an error uploading your file.";
}
}
}
?>
Finally, on my page I print out my JSON contents on my page like so:
<table style="width:100%">
<tr>
<th>Artist</th>
<td>Song Name</td>
<td>Instrument Type</td>
<td style="float:right; margin-right:100px;">File</td>
</tr>
<?php
$read_data = file_get_contents("tablature.json");
$read_data = json_decode($read_data, true);
print("Working<br>");
foreach($read_data as $row) {
print('<tr><th>'.$row["artist"].'</th><td>'.$row["song"].'</td><td>'.$row["instrument"].'</td><td style="float:right">'.$row["myfile"].'</td></tr>');
}
?>
</table><br>
Any help would be greatly appreciated. Thank you in advance.

Any suggestion or solution to my problem to inject selected list items from dropdownlist to other table in php, mysql

Working on a small image gallery project in php and mysql. The project has two table. Album (albumId and albumName) and gallery(id, imageName, albumId, img_name). So, when user need to create a image gallery, they need to input all the information like title, album name, and image. I am able to do most of the part, the section I was stuck was with inserting the dropdown list, which in my case is album. Here is my add_photo.php
<!--Adding Post Area-->
<form action="add_photo_check.php" method="POST" enctype="multipart/form-data">
<?php
if(isset($_SESSION['message']))
{
echo $_SESSION['message'];
unset($_SESSION['message']);
}
?>
<!--Form for post-->
<div class="form-group">
<label for="posttitle">
<h5>Photo Title</h5>
</label>
<textarea name="imageName" class="form-control" placeholder="photo title.." ></textarea>
</div>
<div class="form-group">
<label for="album">Select Album</label>
<select class="form-control" name="albumId" id="album">
<option>Select Album</option>
<?php
$sql = "select * from album";
$res = mysqli_query($conn,$sql);
while($row=mysqli_fetch_assoc($res)){
echo"<option value=\"" .$row['albumId'] . "\" >" .$row['albumName']."</option>\n";
}
?>
</select>
</div>
<div class="form-group">
<label for="uploadimage">
<h5>Upload image</h5>
</label>
<div class="btn">
<input type="file" name="image">
</div>
</div>
<input type="submit" value="Publish" name="publish" class="btn btn-primary">
</form>
</div>
This is my function file add_photo_check.php
<?php
include "includes/header.php";
if(isset($_POST['publish']))
{
$title=$_POST['imageName'];
$title=mysqli_real_escape_string($conn,$imageName);
$title=htmlentities($imageName);
$id=$_POST['albumId'];
$id=mysqli_real_escape_string($conn,$albumId);
$id=htmlentities($albumId);
$uploadOk = 1;
$img_name = $_FILES['image']['name'];
$errorMessage = "";
if($img_name != "") {
$targetDir = "images/upload/";
$img_name = $targetDir . uniqid() . basename($img_name);
$imageFileType = pathinfo($img_name, PATHINFO_EXTENSION);
if(strtolower($imageFileType) != "jpeg" && strtolower($imageFileType) != "png" && strtolower($imageFileType) != "jpg") {
$_SESSION['message']="<div class='alert alert-danger'> Sorry, only jpeg, jpg and png files are allowed!</div>";
$uploadOk = 0;
}
if($_FILES['image']['size'] > 100000){
$_SESSION['message']="<div class='alert alert-danger'> Image is too big to upload!</div>";
header("Location: add_photo.php");
}
if($uploadOk) {
if(move_uploaded_file($_FILES['image']['tmp_name'], $img_name)) {
//image uploaded okay
}
$sql="insert into gallery (title, id, img_name) value('$imageName','$albumId', '$img_name')";
$res=mysqli_query($conn,$sql);
if($res)
{
$_SESSION['message']="<div class='alert alert-success'> Post Successfuly Published</div>";
header("Location: add_photo.php");
}
else
{
$_SESSION['message']="<div class='alert alert-danger'> Something went wrong!</div>";
header("Location: add_photo.php");
}
}
}
}
?>
Any help will be greatly appreciated. Thank you.

i am trying to upload multiple image and store each path in one id but in a separate column in php mysql

This is my html code
<form action="" method="post" enctype="multipart/form-data">
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Product Name</label> (<small class="text-muted">required</small>)
<input type="text" class="form-control" id="inputEmail4" name="prdct_name" placeholder="Product name" required="required">
<small id="passwordHelpBlock" class="form-text text-muted">
please don't input special characters, like numbers, %, $ # and so on.
</small>
</div>
<div class="form-group col-md-6">
<label for="inputPassword4">Category</label> (<small class="text-muted">required</small>)
<input type="text" class="form-control" id="inputPassword4" placeholder="category" required="required" name="cate_gory">
<small id="passwordHelpBlock" class="form-text text-muted">
write the category of the product. eg: Electronics, Men shoes, etc.
</small>
</div>
<div class="form-group col-md-6">
<label for="inputPassword4">product image</label> (<small class="text-muted">required</small>)
<div class="custom-file">
<input type="file" name="files[]" class="custom-file-input" id="customFile" required="required" multiple>
<label class="custom-file-label" for="customFile">Choose files</label>
</div>
<small id="passwordHelpBlock" class="form-text text-muted">
You are allow to select one to four images with png or jpg extension, beyond that will not be accepted.
</small>
</div>
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Product description</label> (<small class="text-muted">required</small>)
<textarea class="form-control" id="exampleFormControlTextarea1" rows="3" required="required" name="about_us" placeholder="product description"></textarea>
<small id="passwordHelpBlock" class="form-text text-muted">
Write the description of the current product you are uploading.
</small>
</div>
<button type="submit" class="btn btn-success" name="upl_prdt">upload</button>
</form>
Php code
if (isset($_POST['upl_prdt']) && isset($_POST['prdct_name']) && isset($_POST['cate_gory']) && isset($_FILES['files'])) {
$product_name = htmlentities(strip_tags(mysqli_escape_string($con,$_POST['prdct_name'])));
$category = htmlentities(strip_tags(mysqli_escape_string($con,$_POST['cate_gory'])));
$desc = htmlentities(strip_tags(mysqli_escape_string($con,$_POST['about_us'])));
$images = $_FILES['files'];
$allowed_files = array('jpg', 'jpeg', 'gif', 'png');
$file_img = array();
if (strpbrk($product_name, '0123456789')) {
$error[] = "please your product name must not contain numbers.";
}
if (strlen($product_name) <= 2) {
$error[] = "the length of your product name must be at least 3 characters.";
}
if (strlen($product_name) >= 32) {
$error[] = "the length of your product name is too long.";
}
if (strpbrk($category, '0123456789')) {
$error[] = "please your category must not contain numbers.";
}
if (strlen($category) <= 2) {
$error[] = "the length of your category must be at least 3 characters.";
}
if (strlen($category) >= 32) {
$error[] = "the length of your category is too long.";
}
if (count($_FILES['files']['name']) > 4) {
$error[] = "Sorry you are only limited to four pictures for one product.";
}
foreach ($images['name'] as $position => $img_name) {
$file_n = $images['name'][$position];
$file_tmp = $images['tmp_name'][$position];
$file_size = $images['size'][$position];
$file_error = $images['error'][$position];
$file_ext = explode('.', $img_name);
$file_ext = strtolower(end($file_ext));
if (in_array($file_ext, $allowed_files) != true) {
$error[] = "This file extension".' <strong>'. $file_ext .'</strong> '."is not allowed";
}
if ($file_size > 3097152) {
$error[] = "This ".' <strong>'. $img_name .'</strong> '."size is too big";
}
}
enter code here
$random_name = rand();
if (empty($_POST) === false && empty($error) === true) {
$name_array = $_FILES['files']['name'];
$tmp_name_array = $_FILES['files']['tmp_name'];
$type_array = $_FILES['files']['type'];
$size_array = $_FILES['files']['size'];
$error_array = $_FILES['files']['error'];
for($i = 0; $i < count($tmp_name_array); $i++){
if($file_destination[] = move_uploaded_file($tmp_name_array[$i], "uploads/".$random_name.$name_array[$i])){
foreach ($file_destination as $key => $value) {
var_dump($value);
}
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}
}
View Page
<form action="upload.php" method="post" enctype="multipart/form-data"><table width="100%"><tr><td>Select Photo (one or multiple):</td><td><input type="file" name="images[]" multiple/></td></tr>
Note: Supported image format: .jpeg, .jpg, .png, .gif
Upload.php
$errors=array();
$extension=array("jpeg","jpg","png","gif");
foreach($_FILES["images"]["tmp_name"] as $key=>$tmp_name)
{
$file_name=$_FILES["files"]["name"][$key];
$file_tmp=$_FILES["files"]["tmp_name"][$key];
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
if(in_array($ext,$extension))
{
if(!file_exists("photo_gallery/".$txtGalleryName."/".$file_name))
{
move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"uploads/".$txtGalleryName."/".$file_name);
}
else
{
$filename=basename($file_name,$ext);
$newFileName=$filename.time().".".$ext;
move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"uploads/".$txtGalleryName."/".$newFileName);
}
}
else
{
array_push($errors,"$file_name, ");
}
}

Upload multiple images in php

i am creating a page called events i have created a form which submits on post file, this is my form code, `
Adding Staff
<div class="box">
<label>Heading</label>
<input type="text" name="heading" id="heading"/>
</div>
<div class="box" style="margin-left: 120px">
<label>Description 1</label>
<textarea cols="30" rows="5" name="description_1" id="description_1"></textarea>
</div>
<div class="box">
<label>Description 2</label>
<textarea cols="30" rows="5" name="description_2" id="description_2"></textarea>
</div>
<div class="clear"> </div>
<div class="box">
<label>Upload Images</label>
<input type="file" name="picture" id="picture"/>
<label>Is Rename <input type="checkbox" name="is_rename"> </label>
</div>
<div class="clear"> </div>
<div class="box" style="width: 100px; margin-left: 350px;">
<input style="padding: 4px" type="submit" name="submit" value="submit">
</div>`
This is my post
<?php
ob_start();
session_start();
include_once "../../classes/addClasses.php";
$heading = $_POST['heading'];
$description_1 = $_POST['description_1'];
$description_2 = $_POST['description_2'];
$picture = $_POST['picture'];
$target_dir = "../../../uploads/";
$target_file = $target_dir . basename($_FILES["picture"]["name"]);
print_r($_FILES);
if( isset( $_POST['is_rename'] ) )
$file_name = time().'-'.basename($_FILES["picture"]["name"]);
else
$file_name = basename($_FILES["picture"]["name"]);
if(empty($_FILES['picture']['name'])){
echo "please select a file to upload";
?>
<script>window.location.href="http://localhost/learner-pack/admin/admin/add_events.php?error=empty"</script>
<?php
}
$target_file = $target_dir . $file_name;
if (move_uploaded_file($_FILES["picture"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["picture"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
if (file_exists($target_file)) {
echo "Sorry, file '".$file_name."' already exists.";
}elseif (move_uploaded_file($_FILES["picture"]["tmp_name"], $target_file)) {
echo "The file " . $file_name . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
/*$created_by = $_POST['created_by'];
$updated_by = $_POST['updated_by'];
$current_date = $_POST['current_date'];
$updated_date = $_POST['updated_date'];
$visitor_counter = $_POST['visitor_counter'];*/
if($admin->addingEvents($heading,$description_1,$description_2, $file_name))
{
header('Location: ../view_events.php?added=true');
}
else
{
echo "Error";
}
?>
please help me to store multiple images in table using one field and retireve them to view on events page when i fetch one row so that all images on that row are fetchable

Categories