I had a form which has Name, Image, Gender and Designation fields.
I am storing those form variables in a Json file.
I am storing the images in a uploads folder and updating the form inputs, image path in a json file.
[{"name":"John", "image":"uploads/john-2019061656551615.jpg", "gender":male, "designation":developer},
{"name":"Russel", "image":"uploads/russel-201906161515.jpg", "gender":male, "designation":developer},
{"name":"Jason", "image":"uploads/jason-20190616451657.jpg", "gender":male, "designation":developer}
]
I want update the Json file whenever it's required.I tried to edit the json file with the below code but every time when i submitting the edit form it is updating as a new record.
if (isset($_GET["id"])) {
$id = (int) $_GET["id"];
$getfile = file_get_contents('data.json');
$all = json_decode($getfile, true);
$jsonfile = $all;
$jsonfile = $jsonfile[$id];
$post["name"] = isset($_POST["name"]) ? $_POST["name"] : "";
$post["gender"] = isset($_POST["gender"]) ? $_POST["gender"] : "";
$post["fileToUpload"] = isset($_POST["fileToUpload"]) ? $_POST["fileToUpload"] : "";
$post["designation"] = isset($_POST["designation"]) ? $_POST["designation"] : "";
}
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
if(isset($_POST["submit"])) {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
if(file_exists('data.json'))
{
$current_data = file_get_contents('data.json');
$array_data = json_decode($current_data, true);
$extra = array(
'name' => $_POST["name"],
'image' => $target_file,
'gender' => $_POST["gender"],
'designation' => $_POST["designation"]
);
$array_data[] = $extra;
$final_data = json_encode($array_data);
if(file_put_contents('data.json', $final_data))
{
$message = "<label class='text-success'>File Appended Success fully</p>";
}
}
else
{
$error = 'JSON File not exits';
}
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
<?php if (isset($_GET["id"])): ?>
<form action="" method="POST">
<input type="hidden" value="<?php echo $id ?>" name="id"/>
<input type="text" value="<?php echo $jsonfile["name"] ?>" name="name"/>
<input type="text" value="<?php echo $jsonfile["gender"] ?>" name="gender"/>
<input class="button button2" type="file" name="fileToUpload" id="fileToUpload">
<input type="text" value="<?php echo $jsonfile["designation"] ?>" name="designation"/>
<input type="submit" value="Submit" name="submit">
</form>
<?php endif; ?>
How to edit only particular record and update it in json file ?
instead of pushing new data $array_data[] = $extra; you can maintain unique record id and search that id in array and update that specific array
something like below
[{"uid":100,name":"John", "image":"uploads/john-2019061656551615.jpg",
"gender":male, "designation":developer}, {"uid":101,"name":"Russel",
"image":"uploads/russel-201906161515.jpg", "gender":male,
"designation":developer}, {"uid":102,"name":"Jason",
"image":"uploads/jason-20190616451657.jpg", "gender":male,
"designation":developer} ]
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['uid'] === $id) {
return $key;
}
}
return null;
}
if (isset($_GET["id"])) {
$id = (int) $_GET["id"];
$getfile = file_get_contents('data.json');
$all = json_decode($getfile, true);
$jsonfile = $all;
$jsonfile = $jsonfile[$id];
$post["name"] = isset($_POST["name"]) ? $_POST["name"] : "";
$post["gender"] = isset($_POST["gender"]) ? $_POST["gender"] : "";
$post["fileToUpload"] = isset($_POST["fileToUpload"]) ? $_POST["fileToUpload"] : "";
$post["designation"] = isset($_POST["designation"]) ? $_POST["designation"] : "";
}
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
if(isset($_POST["submit"])) {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
if(file_exists('data.json'))
{
$current_data = file_get_contents('data.json');
$array_data = json_decode($current_data, true);
$key = searchForId($id, $array_data);
$array_data[$key]['name']= $_POST["name"];
$array_data[$key]['image']= $target_file;
$array_data[$key]['gender']= $_POST["gender"];
$array_data[$key]['designation']= $_POST["designation"];
$final_data = json_encode($array_data);
if(file_put_contents('data.json', $final_data))
{
$message = "<label class='text-success'>File Appended Success fully</p>";
}
}
else
{
$error = 'JSON File not exits';
}
}else {
echo "Sorry, there was an error uploading your file.";
}
}
<?php if (isset($_GET["id"])): ?>
<form action="" method="POST">
<input type="hidden" value="<?php echo $id ?>" name="id"/>
<input type="text" value="<?php echo $jsonfile["name"] ?>" name="name"/>
<input type="text" value="<?php echo $jsonfile["gender"] ?>" name="gender"/>
<input class="button button2" type="file" name="fileToUpload" id="fileToUpload">
<input type="text" value="<?php echo $jsonfile["designation"] ?>" name="designation"/>
<input type="submit" value="Submit" name="submit">
</form>
<?php endif; ?>
I searched for some solution and it seems can work by adding some code in it. My codes seems doesn't work. I don't know what to do. I'm new in php. The input type file seems working but the upload button doesn't work and it seems that is the problem of this.
<?php
include ('LoginFunction.php');
$conn = mysqli_connect('localhost','root','','danganan');
$user = $_SESSION['Username'];
$query = "SELECT * FROM tblactivity WHERE Username = '$user'";
$result = mysqli_query($conn,$query);
$row = mysqli_fetch_array($result);
This is the upload function
if (isset($_POST['upload'])) {
$file_name = $_FILES['file']['name'];
$file_type = $_FILES['file']['type'];
$file_size = $_FILES['file']['size'];
$file_tem_loc = $_FILES['file']['tmp_name'];
$file_store = "uploads/".$file_name;
if(move_uploaded_file($file_tem_loc, $file_store)) {
echo "Image uploaded!";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Profile info</title>
</head>
<body>
<form method="POST">
<div class="container">
<h1><?php echo "Welcome " . " " . $user; ?></h1>
<img src="<?php $row['Picture']; ?>" width=150; height=150;>
<div class="send-button">
<input type="file" name="file" style="margin-right: -76px;"><br><br>
<input type="submit" name="upload" value="Upload">
<?php
$folder = "uploads/";
if(is_dir($folder)) {
if ($open = opendir($folder)) {
while (($file = readdir($open)) !=false) {
if($file == '.' || $file == '..') continue;
echo '<img src ="uploads/'.$file.'" width = "150" height=150>';
}
closedir($open);
}
}
?>
</div>
<input type="hidden" name="usrid" value="<?php echo $row['ID']; ?>">
<h2>FIRST NAME</h2><input type="text" name="fname" value="<?php echo $row['Fname']; ?>">
<h2>LAST NAME</h2><input type="text" name="lname" value="<?php echo $row['Lname']; ?>">
<h2>USERNAME</h2><input type="text" name="uname" value="<?php echo $row['Username']; ?>">
<h2>PASSWORD</h2><h3><?php echo $row['Password']; ?></h3>
</form>
</body>
</html>
I have tried reading multiple tutorials, the PHP documentation and have no idea what I am doing.
Here is my form
<form action="beta_upload.php" enctype="multipart/form-data" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="20971520" /><!-- 20 Meg -->
<input type="file" name="file[]" />
<input type="file" name="file[]" />
<input type="file" name="file[]" />
<input type="submit" value="submit" name="submit" />
</form>
Now when I send that through here:
<?php
$username = trim($_POST['username']);
$password = trim($_POST['password']);
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$username = preg_replace('/[^(\x20-\x7F)]*/','', $username);
$password = preg_replace('/[^(\x20-\x7F)]*/','', $password);
$name = preg_replace('/[^(\x20-\x7F)]*/','', $name);
$email = preg_replace('/[^(\x20-\x7F)]*/','', $email);
$upload_dir = '/beta_images/';
print_r($_FILES);
foreach ($_FILES['files']['error'] as $key => $error) {
if($error == UPLOAD_ERR_OK) {
$check_name = $_FILES['files']['name'];
$filetype = checkfiletype($check_name, 'jpg,jpeg');
$temp_name = $_FILES['files']['tmp_name'][$key];
$image_name = 'image_' . $name . '1';
move_uploaded_file($tmp_name, $upload_dir . $image_name);
}
}
It brings back
Warning: Invalid argument supplied for foreach() in /blabla on line 18
I don't understand foreachs all too well, and when I print_r the array it dosen't help me one bit.
Would someone be so kind to help me out.
Thanks.
You'd better follow this tutorial: http://www.w3schools.com/php/php_file_upload.asp
foreach ($_FILES['file'] as $file) {
if($file['error'] == UPLOAD_ERR_OK) {
$check_name = $file['name'];
// I assume you have to use the file type here, not name
$filetype = checkfiletype($file['type'], 'jpg,jpeg');
$temp_name = $file['tmp_name'];
$image_name = 'image_' . $file['name'] . '1';
move_uploaded_file($tmp_name, $upload_dir . $image_name);
}
}
Your files are in $_FILES['files'] so using foreach you have to go over each element/file and take its data.
This question already has answers here:
Styling an input type="file" button
(46 answers)
Closed 6 years ago.
I am making a Mail Compose Page.
I want to give the user an option to attach a file.
I also want to make the attachment button as an image which I already have.
I have made an image button but the image is acting like a submit button.
But I want it to be an Browse button.
My form is:
<form method="post" action="" enctype="multipart/form-data">
To: <span class="error">* <?php $receiverIdErr ?></span>
<select id="receiverId" name="receiverId">
<?php
$conn = connect();
$receiverIdQuery = "SELECT Email FROM Users";
$receiverIdResult = $conn->query($receiverIdQuery);
if($receiverIdResult->num_rows > 0) {
while($row = $receiverIdResult->fetch_assoc()) {
$Email = $row["Email"];
echo "<option value=\"$Email\">" . $row["Email"] . "</option>";
}
}
?>
</select>
<br /><br />
Subject: <input type="text" name="Subject" required>
<br /><br />
Body: <span class="error">* <?php $BodyErr ?></span>
<textarea name="Body" rows="10" cols="100" maxlength="300" required>
</textarea>
<br /><br />
Attachment:
<input type="image" src="paperclip4_black.png" width="20" height="20" name="myFile" id="myFile">
<br /><br />
<input type="submit" name="Send" value="Send">
</form>
And my PHP is:
<?php
$BodyErr = $receiverIdErr = "";
$Body = $Subject = $receiverId = $filePath = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$Subject = test_input($_POST["Subject"]);
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Body"]))
$BodyErr = "Body is required";
else
$Body = test_input($_POST["Body"]);
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["receiverId"]))
$receiverIdErr = "Choose a receiver";
else
$receiverId = test_input($_POST["receiverId"]);
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_FILES["myFile"]["name"])) {
$target_dir = "asset/attachments/" . time();
$target_file = $target_dir . basename($_FILES["myFile"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if ($uploadOk == 0) {
$message = "Sorry, your file was not uploaded.<br />";
}
else {
if (move_uploaded_file($_FILES["myFile"]["tmp_name"], $target_file)) {
$filePath = $target_file;
}
else {
$filePath = $target_file;
}
}
}
}
?>
Might be you are looking for this :
<input type="file" name="fileToUpload" id="fileToUpload">
Below is a php function of my post method. I am not receiving any errors but however it is not uploading into the folder I have assigned to.
I am using a localhost and there are no errors regarding the database!
<div id="box">
<form method='post' enctype="multipart/form-data">
<?php
if(isset($_FILES['video'])){
$name = $_FILES['video']['name'];
$type = explode('.', $name);
$type = end($type);
$size = $_FILES['video']['name'];
$random_name = rand();
$tmp = $_FILES['video']['tmp_name'];
if($type != 'mp4' && $type != 'mp4' && $type != 'flv'){
$message = "Video Format Not Supported!";
}
else {
move_uploaded_file($tmp, 'videos/'.$random_name.'.'.$type);
mysql_query("INSERT INTO videos VALUES('.' '$name'; 'videos/$random_name.$type')");
$message = "Successfully Uploaded!";
}
echo "$message";
}
?>
Select Video : <br/>
<input type='file' name="video" />
<br/><br/>
<input type="submit" value="Upload" />
</form>