I'm working on a script to upload files. The files are uploaded into a folder and the path is written into a table. One table is used to store the descriptions, names etc and the other table the path. I can upload files, I can edit the descriptions and names but I cannot overwrite old files with new files. I'm not getting any errors. Permissions on the folder are set to 777. I have adapted a script I used to upload images and didn't have any issues updating images so I don't understand why it's not working? This is the edit script.
NON WORKING CODE
<?php
require "authenticate.php";
error_reporting(E_ERROR);
$message = $_GET['message'];
function uploadfile($dir){
if(!empty($_FILES)){
$url ='';
// $file = ($_FILES["file"]["tmp_name"]);
$allowedExts = array("gif", "jpeg", "jpg", "png", "JPG", "JPEG", "PNG", "GIF", "mp3");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "audio/mpeg")
)
&& ($_FILES["file"]["size"] < 209715200)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
$path = $dir . $_FILES["file"]["name"];
{
move_uploaded_file($_FILES["file"]["tmp_name"],
$dir . $_FILES["file"]["name"]);
$path = $dir . $_FILES["file"]["name"];
}
}
}
else
{
$message = "Wrong format";
}
}
return $path;
}
//declare form field and form field error variables
$descriptionErr = $categoryErr = $titleErr = "";
$description = $category = $title = "";
//form field validation
function validate_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (isset($_POST['Submit']))
{
$has_errors = false;
if(empty($_FILES["file"]["tmp_name"])){
$has_errors = true;
$fileErr = "Missing Show!";
}else{
$dir = "audio/";
}
if (empty($_POST["title"])) {
$has_errors = true;
$titleErr = "Enter a title";
}else {
$title = validate_input($_POST["title"]);
}
if (empty($_POST["description"])) {
$has_errors = true;
$descriptionErr = "Enter a description";
}else{
$description = validate_input($_POST["description"]);
}
if (empty($_POST["category"])) {
$has_errors = true;
$categoryErr = "Enter a category";
}else {
$category = validate_input($_POST["category"]);
}
//write data into database table
if (!$has_errors)
{
$Link = mysql_connect($Host, $User, $Password);
$user = $_SESSION['UserName'];
$path = uploadfile($dir);
$Query = "INSERT INTO ccshowcontent VALUES ('','".mysql_escape_string($user)."','".mysql_escape_string($title)."','".mysql_escape_string($description)."',
'".mysql_escape_string($category)."')";
//pass id from form table into file table in order to link files to form data
if(mysql_db_query ($DBName, $Query, $Link)) {
$formid = mysql_query("SELECT id FROM ccshowcontent ORDER BY id DESC LIMIT 1");
$formid = mysql_fetch_array($formid);
$Query = "INSERT INTO ccaudio VALUES ('{$formid[0]}','".mysql_escape_string($user)."','{$path}')";
} else {
die("Query was: $Query. Error: ".mysql_error($Link));
}
if($sql = mysql_db_query ($DBName, $Query, $Link)) {
$message = "Show Saved";
header("Location: ccuploadshow.php?message=".urlencode($message));
} else {
die("Query was: $Query. Error: ".mysql_error($Link));
}
}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="styles/all.css" />
<link rel="stylesheet" href="styles/formcomiccon.css" />
<link rel="stylesheet" href="styles/slideshow.css" />
<script type="text/javascript" src="js/jquery-2.1.1.js"></script>
<link href='//fonts.googleapis.com/css?family=Economica:700,400italic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Voltaire' rel='stylesheet' type='text/css'>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
<title>Audio File Upload</title>
<meta name="Description" content="Audio File Upload" />
<meta name="Keywords" content="Audio File Upload" />
<script>
$(function(){
$(document).click(function(){
$('.messagebox').hide();
});
});
</script>
</head>
<body id="bodyform">
<p class="header">Audio File Upload</p>
<form action="ccuploadshow.php" method ="post" enctype="multipart/form-data" name="myForm">
<fieldset>
<div class="legendcreate">Upload</div>
<div class="audiocontainer">
<div class="audiocontainerinner">
<?php if(isset($_GET['message']) && !empty($message)): ?>
<div class="messagebox">
<?php echo $message ?>
</div>
<?php endif; ?>
<div><label class="labelcard">Title</label><input id="title" class="insetcard" name="title" type="text" placeholder="Title" value="<?PHP print $title ; ?>"/>
<p class="errorcard"><?php echo $titleErr;?></p></div>
<div><label class="labelcard">Category</label><input id="category" class="insetcard" name="category" type="text" placeholder="Category" value="<?PHP print $category ; ?>"/>
<p class="errorcard"><?php echo $categoryErr;?></p></div>
<div><textarea id="description" name="description" class="textareadescription" placeholder="Enter show description" value="<?PHP print $description ; ?>"></textarea>
<p class="errordescription"><?php echo $descriptionErr;?></p></div>
<p class="errorfiles"><?php echo $fileErr;?>
<div class="uploadimgbtn"><p class="upload">Select Audio<input id="upfile" type="file" name="file" class="uploadbtn"/></p></div>
<div class="submit"><input name="Reset" type="reset" class="resetbtn" value="Reset"/></div>
<div class="submit"><input name="Submit" type="submit" class="submitbtn" value="Create"></div>
</div>
</div>
</fieldset>
</form>
</body>
</html>
I've posted the solution for those who have had similar problems or need a script for this task.
<?php
require "authenticate.php";
error_reporting(E_ERROR);
$message = $_GET['message'];
function uploadfile($dir){
if(!empty($_FILES)){
$url ='';
$file = ($_FILES["file"]["tmp_name"]);
$allowedExts = array("gif", "jpeg", "jpg", "png", "JPG", "JPEG", "PNG", "GIF", "mp3");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "audio/mpeg")
)
&& ($_FILES["file"]["size"] < 2009715200)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
$path = $dir . $_FILES["file"]["name"];
{
move_uploaded_file($_FILES["file"]["tmp_name"],
$dir . $_FILES["file"]["name"]);
$path = $dir . $_FILES["file"]["name"];
}
}
}
else
{
$message = "Wrong format";
}
}
return $path;
}
//declare form field and form field error variables
$titleErr = $descriptionErr = $categoryErr = "";
$title = $description = $category = "";
//form field validation
function validate_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
$data = mysql_real_escape_string($data);
return $data;
}
if (isset($_POST['Submit']))
{
$has_errors = false;
if(empty($_FILES["file"]["tmp_name"])){
$path = mysql_real_escape_string($_POST['path']);
}else{
$dir = "audio/";
}
if (empty($_POST["title"])) {
$has_errors = true;
$titleErr = "Enter A Title";
} else {
$title = validate_input($_POST["title"]);
}
if (empty($_POST["description"])) {
$has_errors = true;
$descriptionErr = "Enter A Description";
} else {
$description = validate_input($_POST["description"]);
}
if (empty($_POST["category"])) {
$has_errors = true;
$categoryErr = "Enter A Category";
} else {
$category = validate_input($_POST["category"]);
}
if (!$has_errors)
{
$Link = mysql_connect($Host, $User, $Password);
$user = $_SESSION['UserName'];
if(empty($path)){
$path = uploadfile($dir);
}
//write edited data into tables matching logged in user with their data
$ccid = mysql_real_escape_string($_POST['ccid']);
$Query = "UPDATE ccshowcontent SET title='$title', description='$description', category='$category' WHERE id='$ccid' AND '$user'='$user'";
if(mysql_db_query ($DBName, $Query, $Link)) {
$Query = "UPDATE ccaudio SET path='$path' WHERE id='$ccid'";
} else {
die("Query was: $Query. Error: ".mysql_error($Link));
}
if($sql = mysql_db_query ($DBName, $Query, $Link)) {
$message = "Changes Saved";
$current = $_GET['page'];
header("Location: cceditshow.php?page=".$current."&message=".urlencode($message));
} else {
die("Query was: $Query. Error: ".mysql_error($Link));
}
}
}
//show logged in user their updated data
$user = $_SESSION['UserName'];
$result = mysql_query("SELECT * FROM ccshowcontent JOIN ccaudio USING (id) WHERE ccshowcontent.username = '$user'")
or die(mysql_error());
$count = mysql_num_rows($result);
while($row = mysql_fetch_array($result)){
$id[] = $row['id'];
$name[] = $row['name'];
$title[] = $row['title'];
$description[] = $row['description'];
$category[] = $row['category'];
$audio_paths[] = $row['path'];
}
//create counts and links for pagination
if(empty($_GET['page'])){
$i = 0;
$current = $i + 1;
}else{
$i = $_GET['page'];
$current = $i;
$i = $i - 1;
}
if($i == 0 && $count == 1){
$prevlink = "";
$next = $current + 1;
$nextlink = "";
}elseif($i == 0 && $count > 1){
$prevlink = "";
$next = $current + 1;
$nextlink = "<a href='?page=$next'>Next</a>";
}elseif($current > 0 && $current < $count){
$prev = $current - 1;
$next = $current + 1;
$prevlink = "<a href='?page=$prev'>Previous</a>";
$nextlink = "<a href='?page=$next'>Next</a>";
}elseif($current == $count){
$prev = $current - 1;
$prevlink = "<a href='?page=$prev'>Previous</a>";
$nextlink = "";
}
//delete form and image data when users clicks delete button
if (isset($_POST['Delete'])){
$deletecard = $_POST['Delete'];
mysql_query("DELETE FROM ccshowcontent WHERE id = '$deletecard'");
mysql_query("DELETE FROM ccaudio WHERE id = '$deletecard'");
mysql_query("ALTER TABLE ccshowcontent AUTO_INCREMENT = 1");
$message = 'Show Deleted';
header("Location: cceditshow.php?&message=".urlencode($message));
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="styles/all.css" />
<link rel="stylesheet" href="styles/formcomiccon.css" />
<link rel="stylesheet" href="styles/slideshow.css" />
<script type="text/javascript" src="javascript/jquery-2.1.1.js"></script>
<link href='//fonts.googleapis.com/css?family=Economica:700,400italic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Voltaire' rel='stylesheet' type='text/css'>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
<title>File Upload</title>
<meta name="Description" content="File Upload" />
<meta name="Keywords" content="File Upload" />
<script>
$(function(){
$(document).click(function(){
$('.messagebox').hide();
});
});
</script>
</head>
<body id="bodyform">
<p class="header">File Upload</p>
<ul id="navigation">
<li>Admin<ul>
<li>Edit</li>
<li>Shows</li>
<li>Upload</li>
</ul></li>
<li>Register</li>
<li>Logout</li>
</ul>
<br style="clear:left;"/>
<form action="" method ="post" enctype="multipart/form-data" name="editform">
<fieldset>
<div class="legendcreate">Edit</div>
<div class="audiocontainer">
<div class="audiocontainerinner">
<?php if(isset($_GET['message']) && !empty($message)): ?>
<div class="messagebox">
<?php echo $message ?>
</div>
<?php endif; ?>
<div><label class="labelcard">Title</label><input id="title" label="title" class="insetcard" name="title" type="text" placeholder="title" value="<?PHP print $title[$i] ; ?>"/><p class="errorcard"><?php echo $titleErr;?></p></div>
<div><label class="labelcard">Description</label><input id="category" class="insetcard" name="category" type="text" placeholder="category" value="<?PHP print $category[$i] ; ?>"/>
<p class="errorcard"><?php echo $categoryErr;?></p></div>
<div><textarea id="description" name="description" class="textareadescription" placeholder="Enter character description"><?php
$out = htmlspecialchars_decode($description[$i]);
$out = str_replace( '\n', '<br />', $out );
echo $out;
?></textarea>
<p class="errorbio"><?php echo $biographyErr;?></p></div>
<input type="hidden" name="path" value="<?php echo $audio_paths[$i]; ?>"/>
<p class="errorimage"><?php echo $imageErr;?>
<div class="uploadimgbtn"><p class="upload">Select File<input id="upfile" type="file" name="file" class="uploadbtn"/></p></div>
<div class="submit"><input name="Submit" type="submit" class="savebtn" value="Save"/></div>
<input type="hidden" name="Delete" value="<?php echo $id[$i]; ?>">
<div class="delete"><input name="deletebtn" type="submit" class="deletebtn" value="Delete"/></div>
<input type="hidden" name="ccid" value="<?php echo $id[$i]; ?>"/>
</div>
</div>
</form>
</fieldset>
<div class="previouscardedit"><?php echo $prevlink; ?></a></div>
<div class="countpreviousedit"><?php if($prevlink != ""){ echo $prev."/".$count; } ?></div>
<div class="nextcardedit"><a class="tcg"><?php echo $nextlink; ?></a></div>
<div class="countnextedit"><?php if($nextlink != ""){ echo $next."/".$count; } ?></div>
<div class="currentcardedit"><?php echo "Show ".$current." of ".$count; ?></div>
<br style="clear:left;"/>
</body>
</html>
Related
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 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();
}
I have created a back end form that allows me to upload images and input values into form fields. If any form fields are empty, when trying to upload an image, an error message should display next to the empty form field. The image should not be able to upload until all form fields contain a value. For some reason, the error message is displaying not to fields before the add button is click. The only form field I don't want required, is the link form field. How do I stop image from uploading if form field is empty?
This is the code of index.php:
<!DOCTYPE html>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $videoErr = $LinkErr = $captionErr = "";
$name = $video = $Link = $caption = "";
//if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["video"])) {
$videoErr = "video is required";
} else {
$video = test_input($_POST["video"]);
}
if (empty($_POST["Link"])) {
$Link = "";
} else {
$Link = test_input($_POST["Link"]);
}
if (empty($_POST["caption"])) {
$captionErr = "caption is required";
} else {
$caption = test_input($_POST["caption"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Upload porn thumbnail and video</h2>
<p><span class="error">* required field.</span></p>
<form enctype="multipart/form-data" method="post" action="insert.php">
<label for="video">Name:</label>
<input type="text" id="name" name="name" value="<?php if (!empty($name)) echo $name; ?>" />
<span class="error">* <?php echo $nameErr;?></span><br><br>
<label for="video">Video:</label>
<input type="text" id="video" name="video" value="<?php if (!empty($video)) echo $video; ?>" />
<span class="error">* <?php echo $videoErr;?></span><br><br>
<label for="Link">Link:</label>
<input type="text" id="Link" name="Link" value="<?php if (!empty($Link)) echo $Link; ?>" />
<span class="error"> <?php echo $LinkErr;?></span><br><br>
<label for="Caption">Caption:</label>
<input type="text" id="caption" name="caption" value="<?php if (!empty($caption)) echo $caption; ?>" />
<span class="error">* <?php echo $captionErr;?></span><br><br>
<label for="image">Image:</label>
<input type="file" id="image" name="image" />
<input type="submit" value="Add" name="submit" />
</form>
</body>
</html>
This is the code to insert.php:
<?php
require_once('appvars.php');
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(!mysqli_select_db($conn,'image_display'))
{
echo 'Database not selected';
}
#$name = mysqli_real_escape_string($conn, trim($_POST['name']));
$caption = mysqli_real_escape_string($conn, trim($_POST['caption']));
$Link = mysqli_real_escape_string($conn, trim($_POST['Link']));
$video = mysqli_real_escape_string($conn, trim($_POST['video']));
$image = mysqli_real_escape_string($conn, trim($_FILES['image']['name']));
$image_type = $_FILES['image']['type'];
$image_size = $_FILES['image']['size'];
if (!empty($caption) && !empty($image)) {
if ((($image_type == 'image/gif') || ($image_type == 'image/jpeg') || ($image_type == 'image/pjpeg') || ($image_type == 'image/png'))
&& ($image_size > 0) && ($image_size <= TN_MAXFILESIZE)) {
if ($_FILES['image']['error'] == 0) {
// Move the file to the target upload folder
$target = TN_UPLOADPATH . $image;
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
// Write the data to the database
#$query = "INSERT INTO table1(image1,name,imagelink,caption,video) VALUES ('$image', '$name', '$link', '$caption', '$video')";
mysqli_query($conn, $query);
// Confirm success with the user
echo '<p>Thanks for adding your new image</p>';
//echo '<p><strong>Name:</strong> ' . $name . '<br />';
//echo '<strong>Score:</strong> ' . $score . '<br />';
echo '<img src="' . TN_UPLOADPATH . $image . '" alt="" /></p>';
echo '<p><< Back to page</p>';
// Clear form
$name = "";
$caption = "";
$Link = "";
$video = "";
$image = "";
mysqli_close($conn);
}
else {
echo '<p class="error">Sorry, there was a problem uploading your screen shot image.</p>';
}
}
}
else {
echo '<p class="error">The screen shot must be a GIF, JPEG, or PNG image file no greater than ' . (TN_MAXFILESIZE / 1024) . ' file size is too big.</p>';
}
// Try to delete the temporary image file
#unlink($_FILES['image']['tmp_name']);
}
else {
echo '<p class="error">Please enter all of the information to add file.</p>';
}
?>
You have to make validation in insert.php , Move validation code on insert.php and only upload if validation is ok.
<?php
// define variables and set to empty values
$nameErr = $videoErr = $LinkErr = $captionErr = "";
$name = $video = $Link = $caption = "";
//if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["video"])) {
$videoErr = "video is required";
} else {
$video = test_input($_POST["video"]);
}
if (empty($_POST["Link"])) {
$Link = "";
} else {
$Link = test_input($_POST["Link"]);
}
if (empty($_POST["caption"])) {
$captionErr = "caption is required";
} else {
$caption = test_input($_POST["caption"]);
}
require_once('appvars.php');
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(!mysqli_select_db($conn,'image_display'))
{
echo 'Database not selected';
}
#$name = mysqli_real_escape_string($conn, trim($_POST['name']));
$caption = mysqli_real_escape_string($conn, trim($_POST['caption']));
$Link = mysqli_real_escape_string($conn, trim($_POST['Link']));
$video = mysqli_real_escape_string($conn, trim($_POST['video']));
$image = mysqli_real_escape_string($conn, trim($_FILES['image']['name']));
$image_type = $_FILES['image']['type'];
$image_size = $_FILES['image']['size'];
if (!empty($caption) && !empty($image)) {
if ((($image_type == 'image/gif') || ($image_type == 'image/jpeg') || ($image_type == 'image/pjpeg') || ($image_type == 'image/png'))
&& ($image_size > 0) && ($image_size <= TN_MAXFILESIZE)) {
if ($_FILES['image']['error'] == 0) {
// Move the file to the target upload folder
$target = TN_UPLOADPATH . $image;
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
// Write the data to the database
#$query = "INSERT INTO table1(image1,name,imagelink,caption,video) VALUES ('$image', '$name', '$link', '$caption', '$video')";
mysqli_query($conn, $query);
// Confirm success with the user
echo '<p>Thanks for adding your new image</p>';
//echo '<p><strong>Name:</strong> ' . $name . '<br />';
//echo '<strong>Score:</strong> ' . $score . '<br />';
echo '<img src="' . TN_UPLOADPATH . $image . '" alt="" /></p>';
echo '<p><< Back to page</p>';
// Clear form
$name = "";
$caption = "";
$Link = "";
$video = "";
$image = "";
mysqli_close($conn);
}
else {
echo '<p class="error">Sorry, there was a problem uploading your screen shot image.</p>';
}
}
}
else {
echo '<p class="error">The screen shot must be a GIF, JPEG, or PNG image file no greater than ' . (TN_MAXFILESIZE / 1024) . ' file size is too big.</p>';
}
// Try to delete the temporary image file
#unlink($_FILES['image']['tmp_name']);
}
else {
echo '<p class="error">Please enter all of the information to add file.</p>';
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
I found a code from one of the questions here on SO. I wonder where I will put this code on my upload function so it will insert this line:
<?xml-stylesheet type="text/xsl" href="foreach_template.xsl"?>
before it would be uploaded on the database.
*note: I have this table on the database which has the following columns:
id - int(3)
title - varchar(50)
name - varchar(50)
type - varchar(25)
size - int(10)
content - mediumblob
*note: Also I have a folder where the xml files are uploaded
uploadprocess.php
<?php
include 'connection.php';
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$title = $_POST['title'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
//$fileName = $_FILES['userfile']['name'];
$xml = strip_tags(mysql_real_escape_string($_FILES['userfile']['name']));
$filename = strip_tags(mysql_real_escape_string(pathinfo($xml, PATHINFO_FILENAME)));
$ext = strip_tags(mysql_real_escape_string(".xml"));
$file = strip_tags(mysql_real_escape_string($filename.$ext));
$full_local_path = strip_tags(mysql_real_escape_string('../xml/images/'.$filename.$ext));
$extension = end(explode(".", $_FILES["userfile"]["name"]));
$loc = strip_tags(mysql_real_escape_string('xml/images/'));
if ($_FILES["userfile"]["type"] == "text/xml")
{
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
$query = "INSERT INTO xmltable (title, name, size, type, content) ".
"VALUES ('$title','$file', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
move_uploaded_file($_FILES["userfile"]["tmp_name"], $full_local_path);
echo "<script> alert ('upload successful'); location.href='upload.php';</script>";
}
else
{
echo "<script> alert('Invalid File Type'); history.back(); </script>";
}
}
?>
upload.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css">
<title>XML Upload</title>
</head>
<body>
<div style="font-family:verdana;padding:50px 10px 0px 0px;border:5px solid #4D4D4D;">
<form action="uploadprocess.php" enctype="multipart/form-data" method="post">
<center>
<p>
TITLE OF THE ARTICLE <input name="title" type="text" id="title" /><br /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile" />
<input name="upload" type="submit" class="box" id="upload" value=" Upload ">
</p>
</center>
</div>
<br />
<div>
<table border="1" align="center">
<tr>
<td align="center" width="100px">ID</td>
<td align="center" width="100px">TITLE</td>
<td align="center" width="100px">LINK</td>
</tr>
<?php
include ('connection.php');
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$resultsPerPage = 5;
$startResults = ($page - 1) * $resultsPerPage;
$numberOfRows = mysql_num_rows(mysql_query('SELECT id FROM xmltable'));
$totalPages = ceil($numberOfRows / $resultsPerPage);
$query = mysql_query("SELECT * FROM xmltable LIMIT $startResults, $resultsPerPage");
while ($output = mysql_fetch_assoc($query))
{
echo "<tr><td>".$output['id']."</td>";
echo "<td>".$output['title']."</td>";
echo "<td>";
?>
<a class="del" href="/xml/images/<?php echo $output['name']; ?>" class="del">View Article</a>
</td></tr>
<?php
}
?>
</div>
<div id="pagination">
<div id="pagiCount">
<center>
<?php
echo '<span id="prev"> | First |</span>';
if ($page > 1)
{
echo '<span id="prev"> <a href="?page='.($page - 1).'">| Prev |';
}
for($i = 1; $i <= $totalPages; $i++)
{
if($i == $page)
echo '<strong>'.$i.'</strong>';
else
echo ''.$i.'';
}
if ($page < $totalPages)
echo '<span id="next"> | Next |</span>';
echo '| Last |';
?>
</center>
</div>
</div>
</table>
</form>
</body>
and view.php
<?php
include 'connection.php';
$name=$_GET['name'];
$sql="SELECT * FROM xmltable WHERE name = '$name'";
$rs=mysql_query($sql);
if (!$rs)
{
echo "failed to connect";
}
else
{
while($row = mysql_fetch_array($rs))
{
show_source("images/".$row['name']);
}
}
?>
Where can I put this code? And is it correct?
$dom = new DOMDocument();
$dom->loadXml('<?xml version="1.0" encoding="UTF-8" ?><root/>');
$dom->insertBefore($dom->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="foreach_template.xsl"'), $dom->documentElement);
echo $dom->saveXml();
Sorry if you find it long to read. Please help. Thank You!
<?php
include 'connection.php';
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
//$fileName = $_FILES['userfile']['name'];
if ($_FILES['userfile']['type'] == 'text/xsl')
{
echo "<script> alert('Invalid File Type'); history.back(); </script>";
}
else if($_FILES['userfile']['type'] != 'text/xml')
{
echo "<script> alert('Invalid File Type'); history.back(); </script>";
}
else
{
$userfile = strip_tags(mysql_real_escape_string($_FILES['userfile']['name']));
$filename = strip_tags(mysql_real_escape_string(pathinfo($userfile, PATHINFO_FILENAME)));
$ext = strip_tags(mysql_real_escape_string(".xml"));
$extension = end(explode(".", $_FILES["userfile"]["name"]));
$loc = strip_tags(mysql_real_escape_string('xml/images/'));
$xslt = strip_tags(mysql_real_escape_string($filename.$ext));
$xml = new DOMDocument('1.0', 'utf-8');
$xml->load($tmpName);
$xml->insertBefore($xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="xsl/foreach_template.xsl"'), $xml->documentElement);
$xml->formatOutput = true;
$xml->saveXml();
$xml->save($tmpName);
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
print_r($tmpName);
var_dump($tmpName);
$full_local_path = strip_tags(mysql_real_escape_string('../xml/images/'.$filename.$ext));
move_uploaded_file($tmpName, $full_local_path);
$query = "INSERT INTO xmltable (name, size, type, content) "."VALUES ('$xslt', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
echo "<script> alert ('upload successful'); location.href='upload.php';</script>";
}
}
?>
I'm trying to make a site in which I can upload a file to my sql database, but it does not seem to work.
This is my code;
<html>
<head>
<title>Upload an image</title>
</head>
<body>
<form action="upload.php" method="POST" enctype="multipart/form-data">
File:
<input type="file" name="Image">
<input type="submit" value="Upload">
</form>
<?php
//Connecting to the database
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("picturedatabase") or die(mysql_error());
$file = $_FILES['Image']['tmp_name'];
if(!isset($file))
{
echo "Select an image";
}
else
{
$image = addslashes(file_get_contents($_FILES['Image']['tmp_name']));
$image_name = addslashes($FILES['Image']['name']);
$image_size = getimagesize($FILES['Image']['tmp_name']);
}
if($image_size==FALSE)
{
echo "That's not an image.";
}
else
{
if(!$insert = mysql_query("INSERT INTO images VALUES('','$image_name','$image')"))
{
echo "There was a problem uploading the image";
}
else
{
$lastid = mysql_insert_id();
echo "Image uploaded!<p />Your image:<p /> <img src=show.php?id=$lastid>";
}
}
?>
</body>
</html>
And when I run the file, the form stuff shows up (the buttons and I can also select a file), but it also says
"Notice: Undefined index: Image in C:\ProgramFiles\Xampp\htdocs\Database\upload.php on line 16
Notice: Undefined variable: image_size in C:\ProgramFiles\Xampp\htdocs\Database\upload.php on line 29"
Could someone tell me what I did wrong and help me fix this?
You should save the files in some folder during the upload process and save the name of file in database, so later you can call the name of file from database and link it as a hyperlink to download, i am using the following code to upload images in a folder called files and saving the name of files in database. At the end i have the file name in variable $newname
if ($_FILES['file']['name']) {
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 500000)
&& in_array($extension, $allowedExts)
) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
$ext = end(explode(".", $_FILES["file"]["name"]));
$filename = current(explode(".", $_FILES["file"]["name"]));
$newname = $filename . '_' . time() . '.' . $ext;
move_uploaded_file($_FILES["file"]["tmp_name"],
"files/" . $newname);
}
} else {
echo "<div class='alert alert-success'>Image type or size is not valid.</div>";
}
}
I hope this helps you:
<html>
<head>
<title>Upload an image</title>
</head>
<body>
<?php
function output_errors($error) {
echo '<ul><li><font color="red">'.$error.'</font>/li></ul>';
}
if($_POST) {
//Connecting to the database
$connect = mysqli_connect("localhost", "root" ,"", "picturedatabase");
$name = $_FILES['Image']['name'];
if(!empty($name)) {
$tmp = $_FILES['Image']['tmp_name'];
$type = $_FILES['Image']['type'];
$allowed_type = array('image/jpg', 'image/jpeg', 'image/gif', 'image/png');
if(!in_array($type, $allowed_type)) {
$error[] = $type. ' is not allowed file type';
}
} else {
$error[] = 'There are empty fields';
}
if(!empty($error)) {
echo output_errors($error);
} else if(empty($error)){
$path = 'images/'.$name;
$query = mysqli_query($connect, "INSERT INTO `images` (`image`) VALUES ('$path')");
if(!$query) {
echo 'Insert into db went wrong';
} else {
move_uploaded_file($tmp, $path);
echo '<font color="green">Upload succesful</font>';
}
}
}
?>
<form action="upload.php" method="POST" enctype="multipart/form-data">
File:
<input type="file" name="Image">
<input type="submit" value="Upload">
</form>
</body>
</html>