PHP and JSON based CRUD operations - php

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; ?>

Related

PHP File upload, image not posted

I'm trying to create a form to upload a file, the problem is that the file won't be uploaded. in my code it returns "Image not uploaded".
I've searched a lot online and all the examples uses the same code.
Code:
<?php
if (isset($_FILES['image_url']) && is_uploaded_file($_FILES['image_url']['tmp_name'])) {
$is_img = getimagesize($_FILES['image_url']['tmp_name']); //Is an image?
if (!$is_img) {
$userfile_name = "It isn't an image";
}
else {
if (!file_exists("/images/products/" . $_FILES['image_url']['name'])) {
$uploaddir = '/images/products/';
$userfile_tmp = $_FILES['image_url']['tmp_name'];
$userfile_name = $_FILES['image_url']['name'];
move_uploaded_file($userfile_tmp, $uploaddir . $userfile_name);
}
else {
$userfile_name = $_FILES['image_url']['name'];
}
}
}
else {
$userfile_name = "Image not uploaded";
}
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?> " enctype=”multipart/form-data”>
<p><label for="image">Immagine: </label>
<input type="file" name="image_url"/></p>
<p><input type="submit" value="Salva" /></p>
</form>
The form has also other fields and the data are correctly send to the server.
Try this
<?php
if (isset($_FILES['image_url']) && is_uploaded_file($_FILES['image_url']['tmp_name'])) {
$is_img = getimagesize($_FILES['image_url']['tmp_name']); //Is an image?
if (!$is_img) {
$userfile_name = "It isn't an image";
}
else {
if (!file_exists("images/products/" . $_FILES['image_url']['name'])) {
$uploaddir = 'images/products/';
$userfile_tmp = $_FILES['image_url']['tmp_name'];
$userfile_name = $_FILES['image_url']['name'];
move_uploaded_file($userfile_tmp, $uploaddir . $userfile_name);
}
else {
$userfile_name = $_FILES['image_url']['name'];
}
}
}
else {
$userfile_name = "Image not uploaded";
}
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?> " enctype="multipart/form-data">
<p><label for="image">Immagine: </label>
<input type="file" name="image_url"/></p>
<p><input type="submit" value="Salva" /></p>
</form>

PHP undefined image

session_start();
$_SESSION['id'] = '$id';
$_SESSION['name'] = '$name';
$_SESSION['phone'] = '$phone';
$_SESSION['email'] = '$email';
$_SESSION['image'] = '$image';
$_SESSION['error'] = '$error';
<form id="formm" action="" method="post">
<strong>Image: *</strong> <input type="file" src=images id="imageUpload" name="imageUpload"value="<?php echo $image; ?>"/>
add-student.php
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$image = $_POST['image'];
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["imageUpload"]["name"]). " has been uploaded.";
}
I get an error message:
Undefined index: imageUpload
What am I doing wrong?
First, make sure you have file_uploads = On enabled in your php.ini configuration
Then fix your form code, it should look like this:
<form action="add-student.php" id="formm" method="post" enctype="multipart/form-data">
<strong>Select image to upload:</strong>
<input type="file" name="imageUpload" id="imageUpload" value="<?php echo $image; ?>">
<input type="submit" value="Upload Image" name="submit">
</form>
That will make your file be submitted back to the php file.
I hope it helps :)
<input type="file" src=images id="imageUpload" name="imageUpload"value="<?php echo $image; ?>"/>
shouldn't be :
<form ....... enctype="multipart/form-data">
<input type="file" src="path/to/images" id="imageUpload" name="imageUpload" />
without the value
another thing, I see that you are using a variable between '', It will be token as a string and will not have the value of the variable here :
$_SESSION['id'] = '$id';
$_SESSION['name'] = '$name';
$_SESSION['phone'] = '$phone';
$_SESSION['email'] = '$email';
$_SESSION['image'] = '$image';
$_SESSION['error'] = '$error';
shouldn't be :
$_SESSION['id'] = $id;
$_SESSION['name'] = $name;
$_SESSION['phone'] = $phone;
$_SESSION['email'] = $email;
$_SESSION['image'] = $image;
$_SESSION['error'] = $error;

How to make an attachment button in php? I don't mean styling the original button but using an image as a button [duplicate]

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">

Errors when running php code to upload image to a given path

This is the php i've used for uploading an image (from W3schools):
<?php
$target_dir = "images/";
$target_file = $target_dir . basename("firstfood.jpg");
$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 "firstfood.jpg");
if($check !== false) {
echo "File is an image - " . $check "mime" . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES "firstfood.jpg", $target_file)) {
echo "The file ". basename( $_FILES "firstfood.jpg"). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
When I add it to the mainphp file (see in the middle of below code), with the path substitutions,
<?php // sqltest.php
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
if (isset($_POST['delete']) && isset($_POST['isbn']))
{
$isbn = get_post($conn, 'isbn');
$query = "DELETE FROM classics WHERE isbn='$isbn'";
$result = $conn->query($query);
if (!$result) echo "DELETE failed: $query<br>" .
$conn->error . "<br><br>";
}
if (isset($_POST['author']) &&
isset($_POST['title']) &&
isset($_POST['category']) &&
isset($_POST['year']) &&
isset($_POST['isbn']) &&
isset($_POST['sleeve']))
{
$author = get_post($conn, 'author');
$title = get_post($conn, 'title');
$category = get_post($conn, 'category');
$year = get_post($conn, 'year');
$isbn = get_post($conn, 'isbn');
$sleeve = get_post($conn, 'sleeve');
$query = "INSERT INTO classics VALUES" .
"('$author', '$title', '$category', '$year', '$isbn', '$sleeve')";
$result = $conn->query($query);
if (!$result) echo "INSERT failed: $query<br>" .
$conn->error . "<br><br>";
}
echo <<<_END
<form enctype="multipart/form-data" action="sqltest.php" method="post"><pre>
Author <input type="text" name="author">
Title <input type="text" name="title">
Category <input type="text" name="category">
Year <input type="text" name="year">
ISBN <input type="text" name="isbn">
Sleeve <input type="file" name="sleeve">
<input type="submit" value="Upload Image">
<?php
$target_dir = "images/";
$target_file = $target_dir . basename("firstfood.jpg");
$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 "firstfood.jpg");
if($check !== false) {
echo "File is an image - " . $check "mime" . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES "firstfood.jpg", $target_file)) {
echo "The file ". basename( $_FILES "firstfood.jpg"). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
<input type="submit" value="ADD RECORD">
</pre></form>
_END;
$query = "SELECT * FROM classics";
$result = $conn->query($query);
if (!$result) die ("Database access failed: " . $conn->error);
$rows = $result->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);
echo <<<_END
<pre>
<form enctype="multipart/form-data" action="sqltest.php" method="post">
Author <input type="text" name="author" value=$row[0]>
Title <input type="text" name="title" value=$row[1]>
Category <input type="text" name="category" value=$row[2]>
Year <input type="text" name="year" value=$row[3]>
ISBN <input type="text" name="isbn" value=$row[4]>
</pre>
<input type="hidden" name="delete" value="yes">
<input type="hidden" name="isbn" value="$row[4]">
<input type="submit" value="EDIT RECORD"></form>
<input type="submit" value="DELETE RECORD"></form>
_END;
}
$result->close();
$conn->close();
function get_post($conn, $var)
{
return $conn->real_escape_string($_POST[$var]);
}
?>
It throws out a whole bunch of errors (all of which relate to the section of code i pasted first - for uploading an image). Here are a few:
Notice: Undefined variable: target_dir
Notice: Undefined variable:imageFileType
Notice: Undefined variable: target_file
Would really appreciate guidance on this, as I'm just starting out and can get around this. thanks,
you won't get interpreted that <?php ?> inserted between <<<_END _END;
echo <<<_END
<form>
<?php $string = ''; echo $string ?>
</form>
_END;
this gonna be treated as
echo "<form><?php $string = ''; echo $string ?></form>";
so you see errors "undefined variable" because it's same as
echo "<form><?php ". $string ."= ''; echo ". $string ." ?></form>";
check the source code of generated page, you will get sure.
Try this instead, it's not ideal, but will work in every case ;)
<?php ob_start(); ?>
<form>
<?php $string = ''; echo $string ?>
</form>
<?= ob_get_clean() ?>
and btw you have 2x </form> there
<input type="submit" value="EDIT RECORD"></form>
<input type="submit" value="DELETE RECORD"></form>

Simple PHP video upload system

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>

Categories