i am using below code to upload an image through php form in fresh file, its working fine.
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
</html>
<?php
if (isset($_FILES["photo"]["error"])) {
if ($_FILES["photo"]["error"] > 0) {
echo "Error: " . $_FILES["photo"]["error"] . "<br>";
} else {
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if (!array_key_exists($ext, $allowed))
die("Error: Please select a valid file format.");
// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if ($filesize > $maxsize)
die("Error: File size is larger than the allowed limit.");
// Verify MYME type of the file
if (in_array($filetype, $allowed)) {
// Check whether file exists before uploading it
if (file_exists("upload/" . $_FILES["photo"]["name"])) {
echo $_FILES["photo"]["name"] . " is already exists.";
} else {
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $_FILES["photo"]["name"]);
echo "Your file was uploaded successfully.";
}
} else {
echo "Error: There was a problem uploading your file - please try again.";
}
}
} else {
echo "Error: Invalid parameters - please contact your server administrator.";
}
?>
but when i used same code in already existed form page as below code [ name, email....etc ], its not saving in folder path , looks like part of code is conflicting, i am really just started to learn php, so please kindly help me.
<?php
include 'home.php';
$userID = ""; //Initialization value; Examples
//"" When you want to append stuff later
//0 When you want to add numbers later
//isset()
$userID = isset($_POST['userID']) ? $_POST['userID'] : '';
//empty()
$userID = !empty($_POST['userID']) ? $_POST['userID'] : '';
// session_start();
require_once 'class.user.php';
$user_home = new USER();
if (!$user_home->is_logged_in()) {
header("Location: index.php");
die();
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid" => $_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<?php
/* php codde */
$FORM['uname'] = "";
$FORM['txtuname'] = "";
if (isset($_POST['submit'])) {
// new data
$uname = $_POST['txtuname'];
$email = $_POST['txtemail'];
$phone = $_POST['phone'];
$street_address = $_POST['street_address'];
$street_address_2 = trim($_POST['street_address_2']);
$city = trim($_POST['city']);
$state = trim($_POST['state']);
$zip_code = trim($_POST['zip_code']);
$country = trim($_POST['country']);
$sold_by = trim($_POST['sold_by']);
$portfolio = trim($_POST['portfolio']);
$paypal_email_id = trim($_POST['paypal_email_id']);
$account_holder_name = trim($_POST['account_holder_name']);
$account_number = trim($_POST['account_number']);
$branch_name = trim($_POST['branch_name']);
$bank_name = trim($_POST['bank_name']);
$ifsc_code = trim($_POST['ifsc_code']);
$uid = (isset($_GET['userID']) ? intval($_GET['userID']) : -1);
// query
if ($user_home->update($uname, $email, $phone, $street_address, $street_address_2, $city, $state, $zip_code, $country, $sold_by, $portfolio, $paypal_email_id, $account_holder_name, $account_number, $branch_name, $bank_name, $ifsc_code, $uid))
; {
header("Location: profile.php");
die();
}
}
/* php codde end */
?>
<!DOCTYPE html>
<html class="no-js">
<h2> Welcome to profile page</h2>
<head>
<title><?php echo $row['userEmail']; ?></title>
<title><?php echo $row['userEmail']; ?></title>
<!-- Bootstrap -->
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">
<link href="assets/styles.css" rel="stylesheet" media="screen">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<form action="profile1.php" method="POST" enctype="multipart/form-data">
<h3>Personal details</h3>
Name :
<input type="text" name="txtuname" value="<?php echo $row['userName'] ?>" /><br/>
Email :
<input type="text" name="txtemail" value="<?php echo $row['userEmail'] ?>" /><br>
Sold_by :
<input type="text" name="sold_by" value="<?php echo $row['sold_by'] ?>" /><br/>
Portfolio :
<input type="text" name="portfolio" value="<?php echo $row['portfolio'] ?>" /><br>
<h3>ADDRESS</h3>
Phone :
<input type="text" name="phone" value="<?php echo $row['phone'] ?>" /><br>
street address :
<input type="text" name="street_address" value="<?php echo $row['street_address'] ?>" /><br>
street address 2 :
<input type="text" name="street_address_2" value="<?php echo $row['street_address_2'] ?>" /><br>
city :
<input type="text" name="city" value="<?php echo $row['city'] ?>" /><br>
state :
<input type="text" name="state" value="<?php echo $row['state'] ?>" /><br>
country :
<input type="text" name="country" value="<?php echo $row['country'] ?>" /><br>
zip :
<input type="text" name="zip_code" value="<?php echo $row['zip_code'] ?>" /><br>
<h3>Payment details</h3>
<input type="text" name="paypal_email_id" value="<?php echo $row['paypal_email_id'] ?>" /><br>
<h4>Wiretransfer </h4><br/>
Account holder name :
<input type="text" name="account_holder_name" value="<?php echo $row['account_holder_name'] ?>" /><br>
account number :
<input type="text" name="account_number" value="<?php echo $row['account_number'] ?>" /><br>
Branch name :
<input type="text" name="branch_name" value="<?php echo $row['branch_name'] ?>" /><br>
Bank name :
<input type="text" name="bank_name" value="<?php echo $row['bank_name'] ?>" /><br>
IFSC CODE :
<input type="text" name="ifsc_code" value="<?php echo $row['ifsc_code'] ?>" /><br>
<h3>Other information : </h3>
<h2>Upload File</h2>
<label for="fileSelect">Filename1:</label>
<input type="file" name="photo" id="fileSelect"><br>
<input type="submit" name="submit" value="Save" />
</form>
</html>
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
</html>
<?php
if (isset($_FILES["photo"]["error"])) {
if ($_FILES["photo"]["error"] > 0) {
echo "Error: " . $_FILES["photo"]["error"] . "<br>";
} else {
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if (!array_key_exists($ext, $allowed))
die("Error: Please select a valid file format.");
// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if ($filesize > $maxsize)
die("Error: File size is larger than the allowed limit.");
// Verify MYME type of the file
if (in_array($filetype, $allowed)) {
// Check whether file exists before uploading it
if (file_exists("upload/" . $_FILES["photo"]["name"])) {
echo $_FILES["photo"]["name"] . " is already exists.";
} else {
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $_FILES["photo"]["name"]);
echo "Your file was uploaded successfully.";
}
} else {
echo "Error: There was a problem uploading your file - please try again.";
}
}
} else {
echo "Error: Invalid parameters - please contact your server administrator.";
}
?>
when i remove below code from above page, image is uploading fine, i tried to remove lot of code and make it short, so that its going to be helpfull for readers to solve issue easily, but i end up in getting lot of different kinds of errors, so i posted full code, i am extremely sorry for that....
<?php
/* php codde */
$FORM['uname'] = "";
$FORM['txtuname'] = "";
if (isset($_POST['submit'])) {
// new data
$uname = $_POST['txtuname'];
$email = $_POST['txtemail'];
$phone = $_POST['phone'];
$street_address = $_POST['street_address'];
$street_address_2 = trim($_POST['street_address_2']);
$city = trim($_POST['city']);
$state = trim($_POST['state']);
$zip_code = trim($_POST['zip_code']);
$country = trim($_POST['country']);
$sold_by = trim($_POST['sold_by']);
$portfolio = trim($_POST['portfolio']);
$paypal_email_id = trim($_POST['paypal_email_id']);
$account_holder_name = trim($_POST['account_holder_name']);
$account_number = trim($_POST['account_number']);
$branch_name = trim($_POST['branch_name']);
$bank_name = trim($_POST['bank_name']);
$ifsc_code = trim($_POST['ifsc_code']);
$uid = (isset($_GET['userID']) ? intval($_GET['userID']) : -1);
// query
if ($user_home->update($uname, $email, $phone, $street_address, $street_address_2, $city, $state, $zip_code, $country, $sold_by, $portfolio, $paypal_email_id, $account_holder_name, $account_number, $branch_name, $bank_name, $ifsc_code, $uid))
; {
header("Location: profile.php");
die();
}
}
/* php codde end */
?>
This is not going to do what you expect as there is a ; in the wrong place here
// query
if ($user_home->update($uname, $email, $phone, $street_address, $street_address_2, $city, $state, $zip_code, $country, $sold_by, $portfolio, $paypal_email_id, $account_holder_name, $account_number, $branch_name, $bank_name, $ifsc_code, $uid))
; // <-- remove this
{
header("Location: profile.php");
die();
}
Related
I am having trouble displaying an image in php. In the first file I have an input that gets the image. <input type="file" name="imageOrVideo" accept="video/*,image/*" multiple>. In a second php file I want to get the image and display it. I get the file using $imageOrVideo = $_POST['imageOrVideo']; If I echo $imageOrVideo all I get is a string. I tried using echo img echo "<img src=Image/".$imageOrVideo."/>"; and echo "<img src=".$imageOrVideo."/>"; But neither worked. I read that you can only echo strings so maybe I should not use echo but some other method to display an image. Here is the full code so as to see where the problem might be. Thanks for any help.
This is the first file.
<!DOCTYPE html>
<html>
<head>
<title>Create Recipe</title>
<link rel="stylesheet" type="text/css" href="../CSS/createRecipe.css">
</head>
<body>
<div class="topnav">
Sign Out
My Recipes
Home
</div>
<form action="includes/createRecipe.inc.php" method="post">
<div class="leftSide">
<input type="file" name="imageOrVideo" accept="video/*,image/*" multiple><br><br>
<!--
<input type="file" name="imageOrVideo" accept="image/*" ><br><br>
-->
<div class="prepTimeCookTime">
<label>Prep Time</label><br><br>
<textarea type="" name="prepTime" class="prepTime"> </textarea><br>
<label>Cook Time</label><br><br>
<textarea type="" name="cookTime" class="cookTime"> </textarea><br>
</div>
<div class="readyTimeNumberOfServings">
<label></label>Ready Time<br><br>
<textarea type="" name="readyTime" class="readyTime"> </textarea><br>
<label>Number of Servings</label><br><br>
<textarea type="" name="numberOfServings" class="numberOfServings"> </textarea><br>
</div>
</div>
<div class="rightSide">
<label>Recipe Title</label><br><br>
<textarea type="" name="recipeTitle" class="recipeTitle"> </textarea><br>
<label>Description</label><br><br>
<textarea type="" name="description" class="description"> </textarea><br>
<label>Ingrediants</label><br><br>
<textarea type="" name="ingredients" class="ingredients" placeholder="Put each ingrediant on its own line."></textarea><br>
<label>Directions</label><br><br>
<textarea type="" name="directions" class="directions" placeholder="Put each step on its own line."></textarea><br>
<button type="submit" name="recipe-submit">Submit</button>
</div>
</form>
</body>
</html>
Here is the second file.
<?php
if(isset($_POST['recipe-submit'])){
require 'dbh.inc.php';
session_start();
$imageOrVideo = $_POST['imageOrVideo'];
$uidUsers = $_SESSION['userUid'];
$prepTime = $_POST['prepTime'];
$cookTime = $_POST['cookTime'];
$readyTime = $_POST['readyTime'];
$numberOfServings = $_POST['numberOfServings'];
$recipeTitle = $_POST['recipeTitle'];
$description = $_POST['description'];
$ingredients = $_POST['ingredients'];
$directions = $_POST['directions'];
//echo "<img src='" . $_POST['imageOrVideo'] . "' alt='img'>";
//echo "<img src='/images/test/" . $_POST['imageOrVideo'] . "' alt='img'>";
//print $imageOrVideo;
//echo "<img src=".$imageOrVideo."/>";
//echo "<img src=Image/".$imageOrVideo."/>";
/*
$sql = "INSERT INTO recipes (videoOrImages, uidUsers, prepTime, cookTime, readyTime, numberOfServings, recipeTitle, description, ingredients, directions) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)){
header("Location: ../createRecipe.php?error=sqlError");
exit();
}
else{
mysqli_stmt_bind_param($stmt, "bsssssssss", $imageOrVideo, $uidUsers, $prepTime, $cookTime, $readyTime, $numberOfServings, $recipeTitle, $description, $ingredients, $directions);
mysqli_stmt_execute($stmt);
header("Location: ../index.php?signup=success");
exit();
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
*/
}
else{
header("Location: ../createRecipe.php");
exit();
}
As i mentioned in the comment your not actually managing the uploaded file. try something like this :
$uidUsers = $_SESSION['userUid'];
$prepTime = $_POST['prepTime'];
$cookTime = $_POST['cookTime'];
$readyTime = $_POST['readyTime'];
$numberOfServings = $_POST['numberOfServings'];
$recipeTitle = $_POST['recipeTitle'];
$description = $_POST['description'];
$ingredients = $_POST['ingredients'];
$directions = $_POST['directions'];
$imageOrVideo = $_POST['imageOrVideo'];
$uploaddir = 'uploads/'; //or wherever you want to upload the file
$uploadfile = $uploaddir . basename($_FILES['file']['name']);
$imageuploaded = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// then check to see if its actually an image
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
echo "File is an image";
$imageuploaded = 1;
} else {
echo "File is not an image.";
$imageuploaded = 0;
}
// you can check to see if the file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$imageuploaded = 0;
}
// then process the file
if ($imageuploaded == 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"], $uploadfile)) {
echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
if you wanted to make sure its a specific file type you can try something like this :
// 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;
}
i haven't tested the code but it should work or at least set you off on the right path
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'm using Linux Debian
trying to make Login & Registration System With php
on control page
index.php:
<?php
include("connect.php");
global $tf_handle;
$error = "";
if (isset($_POST['submit']))
{
$firstName = $_POST['fname'];
$lastName = $_POST['lname'];
$email = $_POST['email'];
$password = $_POST['password'];
$passwordConfirm = $_POST['passwordConfirm'];
$image = $_FILES['image']['name'];
$tmp_image = $_FILES['image']['tmp_name'];
$imageSize = $_FILES['image']['size'];
if($image == "")
{
$error = "Please Upload Image ";
}
else
{
$insertQuery = "INSERT INTO users (firstName,lastName,email,password,image)
VALUES ('$firstName','$lastName','$email','$password','$image')";
if(mysqli_query($tf_handle,$insertQuery))
{
if(move_uploaded_file($tmp_image,"images/$image"))
{
$error = "You're successfully registered";
}
else
{
$error = "Image isn't Uploaded";
}
}
}
}
?>
<!doctype html>
<html>
<head>
<title>Registration Page</title>
<link rel="stylesheet" href="css/styles.css" />
</head>
<body>
<div id="error"><?php echo $error;?></div>
<div id="wrapper">
<div id="formDiv">
<form method="POST" action="index.php" enctype="multipart/form-data">
<label>First Name:</label><br/>
<input type="text" name="fname" required /><br/><br/>
<label>Last Name:</label><br/>
<input type="text" name="lname" required /><br/><br/>
<label>Email:</label><br/>
<input type="text" name="email" required /><br/><br/>
<label>Password:</label><br/>
<input type="password" name="password" required /><br/><br/>
<label>Re-enter Password:</label><br/>
<input type="password" name="passwordConfirm" required /><br/><br/>
<label>Image:</label><br/>
<input type="file" name="image" required /><br/><br/>
<input type="submit" name="submit" value="Registration" />
</form>
</div>
</div>
</body>
</html>
While running the script
The Query Works Fine and it inserts information into Database
the problem it doesn't move the image to (images) Folder
move_uploaded_file($tmp_image,"images/$image");
do i use it in wrong way ??
Result:
Warning: move_uploaded_file(images/snapshot46.png): failed to open stream: Permission denied in /var/www/html/LoginRegistrationSystem/index.php on line 51
I wonder what are you getting when you print the $error:
<div id="error"><?php echo $error;?></div>
From the php manual you get that:
If filename is not a valid upload file, then no action will occur, and
move_uploaded_file() will return FALSE.
If filename is a valid upload file, but cannot be moved for some
reason, no action will occur, and move_uploaded_file() will return
FALSE. Additionally, a warning will be issued.
So I would say:
1- Check the return based on your $error variable and you'll know if the file is a valid upload file.
2- Check the params you're using on move_uploaded_file are (string $filename , string $destination)
3- Check the permissions and path to your folder (if the problem lies in the permissions take a look at this post)
From the manual, the first "move_uploaded_file" example (check how $uploads_dir and $name are being used):
<?php
$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
?>
Im creating a CMS for my site and in my admin page I have an add page that adds new content to my site LOCATED HERE and have added a few form fields.
2 of these are:
IMAGE URL (text box) & UPLOAD IMAGE (select file button)
When I fill in all the fileds and select an image using IMAGE URL and hit add article, it works fine and my form is saved to my database and is then displayed on my site.
When I fill in all the fileds and select an image using UPLOAD IMAGE and hit add article, it adds the image to my selected folder in my cpanel but DOES NOT ADD TO DATABASE.
My question is: How can I get it to add to the database? and save the new images location to the image field on the database?
I have followed this tutorial when adding the upload file button to my page.
Please do not show me links on how to do this as I already have read through them but I stuggle when it comes to adding this to my code.
my add.php code is this.
<?php
session_start();
include_once('../include/connection.php');
if (isset($_SESSION['logged_in'])){
if (isset($_POST['title'], $_POST['content'])) {
$title = $_POST['title'];
$content = nl2br($_POST['content']);
if (!empty($_POST['image']))
{
$image = $_POST['image'];
}
else
{
$image = $_POST['imageupload'];
if (isset($_FILES['imageupload']))
{
$errors = array();
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$file_name = $_FILES['imageupload'] ['name'];
$file_ext = strtolower (end (explode ('.', $file_name)));
$file_size = $_FILES['imageupload'] ['size'];
$file_tmp = $_FILES['imageupload'] ['tmp_name'];
if (in_array ($file_ext, $allowed_ext) === false) {
$errors[] = 'File 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';
$image = $file_name;
}
}else{
foreach ($errors as $error)
echo $error, '<br />';
}
}
}
$link = $_POST['link'];
$category = $_POST['category'];
$brand = $_POST['brand'];
if (empty($title) or empty($content)) {
$error = 'All Fields Are Required!';
}else{
$query = $pdo->prepare('INSERT INTO mobi (promo_title, promo_content, promo_image, promo_link, promo_cat, promo_name) VALUES(?, ?, ?, ?, ?, ?)');
$query->bindValue(1, $title);
$query->bindValue(2, $content);
$query->bindValue(3, $image);
$query->bindValue(4, $link);
$query->bindValue(5, $category);
$query->bindValue(6, $brand);
$query->execute();
header('location: index.php');
}
}
?>
<?php
if (isset($_FILES['Filedata']))
{
// And if it was ok
if ($_FILES['Filedata']['error'] !== UPLOAD_ERR_OK)
exit('Upload failed. Error code: ' . $_FILES['image']['error']);
$filename = $_FILES['Filedata']['name'];
$targetpath = "../img/news/" . $filename; //target directory relative to script location
$copy = copy($_FILES['Filedata']['tmp_name'], $targetpath);
}
?>
<html>
<head>
<title>Add Article</title>
<link rel="stylesheet" href="../other.css" />
</head>
<body>
<div class="container">
<b>← Back</b>
<br />
<div align="center">
<h4>Add Article</h4>
<?php if (isset($error)) { ?>
<small style="color:#aa0000;"><?php echo $error; ?></small><br /><br />
<?php } ?>
<form action="add.php" method="post" autocomplete="off" enctype="multipart/form-data">
<input type="text" name="title" placeholder="Title" /><br /><br />
<textarea rows="15" cols="50" placeholder="Content" name="content"></textarea><br /><br />
<input name="imageupload" type="file" id="image" placeholder="Imageupload" />
<input type="text" name="image" placeholder="Image" /><br /><br />
<input type="link" name="link" placeholder="Link" /><br /><br />
<input type="category" name="category" placeholder="Category" /><br /><br />
<input type="category" name="brand" placeholder="Brand" /><br /><br />
<input type="submit" value="Add Article" />
</form>
</div>
</div>
</body>
</html>
<?php
}else{
header('location: index.php');
}
?>
Please help.
if (move_uploaded_file($file_tmp, 'images/'.$file_name)) {
echo 'File uploaded';
$image = '/images/'.$filename;//try updating the line like this