I am trying to upload a file to an images folder and also insert the directory path into a mysql db.
Here is my HTML form
<form enctype="multipart/form-data" method="post" action="newfacility.php">
<fieldset>
<legend>New Facility</legend>
...
<label for="photo">Facility Photo:</label>
<input type="file" id="facilityphoto" name="facilityphoto" /><br />
<label for="province">Photo Description:</label>
<input type="text" id="photodesc" name="photodesc" /><br />
....
<input type="submit" value="Create" name="submit" />
</fieldset>
</form>
newfacility.php
require_once('../appvars.php');
require_once('upload_image.php');
//connect to db and test connection.
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$dbc) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset($_POST['submit'])) {
// Grab the user data from the POST
$facilityNumber = mysqli_real_escape_string($dbc, trim($_POST['facilitynumber']));
....
....
//This is defined in appvars.php -- define('MM_UPLOADPATH', 'images/');
//facility photo
$facilityPhoto = MM_UPLOADPATH . basename($_FILES["facilityphoto"]["name"]);
$facilityPhotoDesc = mysqli_real_escape_string($dbc, trim($_POST['photodesc']));
// check if the faciliy info already exists.
if (!empty($facilityNumber) && !empty($facilityName) && !empty($facilityAddress) && !empty($facilityCity)) {
$query = "SELECT * FROM facility WHERE facility_number = '$facilityNumber' AND facility_name = '$facilityName' "
. "AND facility_address = '$facilityAddress' AND facility_city = '$facilityCity'";
$data = mysqli_query($dbc, $query);
//if the facility is unique insert the data into the database
if (mysqli_num_rows($data) == 0) {
//insert into facility table
$query = "INSERT INTO facility (facility_id, account_id, facility_number, facility_name, facility_address,"
. " facility_city, facility_province, facility_postal_code, facility_photo, facility_roof_plan,"
. " facility_roof_size, facility_roof_size_inspected, facility_last_inspected_date, facility_inspected_by)"
. " VALUES (NULL, '$selectedAssocAccount', '$facilityNumber', '$facilityName', '$facilityAddress', "
. "'$facilityCity', '$facilityProvince', '$facilityPostalCode', '$facilityRoofSize', "
. "'$facilityRoofSizeInspected', '$facilityDayInspected', '$facilityInspectedBy')";
mysqli_query($dbc, $query);
//query used to get the facility_id of the facility we had just entered -- I haven't tested this yet.
$getFacilityID = "SELECT facility_id FROM facility WHERE facility_number = '$facilityNumber' AND facility_name = '$facilityName' "
. "AND facility_address = '$facilityAddress' AND facility_city = '$facilityCity'";
$facilityID = mysqli_query($dbc, $getFacilityID);
//insert into photo table
$photoQuery = "INSERT INTO photo (photo_id, facility_id, photo, photo_desc)"
. "VALUES (NULL, $facilityID, $facilityPhoto, $facilityPhotoDesc)";
mysqli_query($dbc, $photoQuery);
// Confirm success with the user
echo '<p>You have succesfully created a new facility. '
. 'Please go back to the admin panel.</p>';
//testing to see if I can view the image
echo '<img class="profile" src="' . MM_UPLOADPATH . $facilityPhoto . '"/>';
//close db connection
mysqli_close($dbc);
exit();
}
And finally here is upload_image.php
if(isset($_FILES["facilityphoto"])) {
// Check if file already exists
if (file_exists($facilityPhoto)) {
echo "Sorry, facility photo already exists.";
}
if($_FILES['facilityphoto']['error'] !==0) {
echo "Error uploading facility photo image.";
} else {
if (move_uploaded_file($_FILES["facilityphoto"]["tmp_name"], $facilityPhoto)) {
echo "The file ".( $_FILES["facilityphoto"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading the facility photo.";
}
}
}
So the error I keep hitting right now is: echo "Sorry, there was an error uploading the facility photo.";
I don't understand what I am doing wrong here that is resulting in the image not being uploaded into my images/ directory.
I am going to provide an answer that addresses only the file upload problem, all the database stuff is striped from the answer as it is not relevant.
// returns true only if the file was written to $to,
// the value of $status_msg will be a user friendly string
// representing the outcome.
function save_facility_photo($from, $to, &$status_msg) {
// Check if file already exists
if (file_exists($to)) {
$status_msg = "Sorry, facility photo already exists.";
return false;
}
if (move_uploaded_file($from, $to)) {
$status_msg = "The file ".basename($to)." has been uploaded.";
return true;
}
$status_msg = "Sorry, there was an error uploading the facility photo.";
return false;
}
if (isset($_POST['submit'])) {
define('MM_UPLOADPATH', 'images/');
$facilityPhoto = MM_UPLOADPATH . basename($_FILES["facilityphoto"]["name"]);
if ($_FILES['facilityphoto']['error'] == UPLOAD_ERR_OK) {
$status_msg = '';
$from = $_FILES["facilityphoto"]["tmp_name"];
$saved = save_facility_photo($from, $facilityPhoto, $status_msg);
}
else {
// handle upload error
}
// continue with code
}
The following is an explanation of what I think is happening in your scripts.
At the top of newfacility.php, require_once('upload_image.php'); is called. Now lets step though upload_image.php noting that $facilityPhoto has not yet been defined
// this is very likely true
if(isset($_FILES["facilityphoto"])) {
// $facilityPhoto is undefined so file_exists(NULL) will return false
if (file_exists($facilityPhoto)) { }
// the image upload was probably successful, so we jump to the else branch
if($_FILES['facilityphoto']['error'] !==0) {
}
else {
// $facilityPhoto is undefined move_uploaded_file('p/a/t/h', NULL)
// will return false, so we jump to the else branch
if (move_uploaded_file($_FILES["facilityphoto"]["tmp_name"], $facilityPhoto)) {
}
else {
// resulting in this error
echo "Sorry, there was an error uploading the facility photo.";
}
}
}
Replace these lines:
if (move_uploaded_file($_FILES["facilityphoto"]["tmp_name"], $facilityPhoto)){
echo "The file ".( $_FILES["facilityphoto"]["name"]). " has been uploaded.";
}
with these:
if (move_uploaded_file($_FILES["facilityphoto"]["tmp_name"], 'images/'. $_FILES["facilityphoto"]["name"])){
echo "The file ".( $_FILES["facilityphoto"]["name"]). " has been uploaded.";
}
Related
I still have the error 2 days after. Help...
I have an error with picture upload in my code. The file upload works perfectly when i remove anything image related but fails once i add anything image related.
I get 2 errors
"Sorry, there was a problem uploading your file." and
"Problem uploading item". I have no idea why...
I'll post the section i have the problem with.
if((($_FILES["pic"]["type"] != "image/jpg")
|| ($_FILES["pic"]["type"] != "image/jpeg")
|| ($_FILES["pic"]["type"] != "image/png")
|| ($_FILES["pic"]["type"] != "image/pjpeg"))
&& ($_FILES["pic"]["size"] > 1000000))
{
$_SESSION['itemerror'][] = "Pic must be jpg, jpeg, png or pjpeg and must be less than 1mb";
}
//final disposition
if (count($_SESSION['itemerror']) > 0) {
die(header("Location: postitem.php"));
} else {
if(registerItem($_POST)) {
unset($_SESSION['formAttempt']);
$_SESSION['itemsuccess'][] = "Successfully Uploaded";
die(header("Location: postitem.php"));
} else {
error_log("Problem uploading item: {$_POST['name']}");
$_SESSION['itemerror'][] = "Problem uploading item";
die(header("Location: upload.php"));
}
}
function registerItem($userData) {
$mysqli = new mysqli(DBHOST,DBUSER,DBPASS,DB);
if ($mysqli->connect_errno) {
error_log("Cannot connect to MySQL: " . $mysqli->connect_error);
return false;
}
$target = "img/";
$target = $target . basename( $_FILES['pic']['name']);
$pic=($_FILES['pic']['name']);
$poster = htmlspecialchars($mysqli->real_escape_string($_POST['user']));
$itemcategory = htmlspecialchars($mysqli->real_escape_string($_POST['category']));
$itemname = htmlspecialchars($mysqli->real_escape_string($_POST['name']));
$itemdescription = htmlspecialchars($mysqli->real_escape_string($_POST['description']));
$itemprice = htmlspecialchars($mysqli->real_escape_string($_POST['price']));
$itemlocation = htmlspecialchars($mysqli->real_escape_string($_POST['addr']));
$itemcity = htmlspecialchars($mysqli->real_escape_string($_POST['city']));
$itemstate = htmlspecialchars($mysqli->real_escape_string($_POST['state']));
$itemphone = htmlspecialchars($mysqli->real_escape_string($_POST['phone']));
$itemnegotiate = htmlspecialchars($mysqli->real_escape_string($_POST['negotiate']));
if(move_uploaded_file($_FILES['pic']['tmp_name'],$target)){
$query = "INSERT INTO Product
(category,name,upload_date,user,
description,price,location,city,
state,phone,negotiatable,pic_link)" .
" VALUES ('{$itemcategory}','{$itemname}',NOW(),'{$poster}',
'{$itemdescription}','{$itemprice}','{$itemlocation}'" .
",'{$itemcity}','{$itemstate}','{$itemphone}','{$itemnegotiate}', '{$pic}')";
if ($mysqli->query($query)) {
$itemname = $mysqli->insert_itemname;
error_log("Inserted {$itemname} as ID {$id}");
return true;
} else {
error_log("Problem inserting {$query}");
return false;
}
} else {
$_SESSION['itemerror'][] = "Sorry, there was a problem uploading your file.";
}
}
The form contains this:
<form id="userForm" method="POST" action="upload.php">
And this for the picture input:
<label for="pic">Pictures: </label>
<input class="input100" type="file" id="pic" name="pic">
Add the attribute enctype="multipart/form-data" to your <form>
Like this
<form id="userForm" method="POST" action="upload.php" enctype="multipart/form-data">
I do not know if that will solve your problem, but it will probably help you.
It seems to me that it's mandatory for an upload form.
I am working on a project where each item could have multiple images, I created a form that would accept the images and store them into an array. The problem is whenever I try inserting the images into a table row in the database it displays an error:
"Array to string conversion"
How can I fix this? And also how do I fetch each images on another page from the same database table. Below is my code.
-Form code
<form method="post" enctype="multipart/form-data" >
<input required type="text" name="name">
<input required type="text" name="location">
<input required type="text" name="status">
<select required name="category">
<option>Category</option>
<option value="construct">Construction</option>
<option value="promgt">Project Development</option>
<option value="archdesign">Architectural Designs</option>
</select>
<textarea required class="form-control" name="descrip" rows="5"></textarea>
<input style="text-align:left" type="file" name="imgs[]" multiple>
<button type="submit" name="submit" formaction="addaction.php">Add Project</button>
</form>
-Addaction.php code
<?php
$db=mysqli_connect("localhost","root","dbpassword","dbname");
if(!empty($_FILES['imgs']['name'][0])){
$imgs = $_FILES['imgs'];
$uploaded = array();
$failed = array();
$allowed = array('jpg', 'png');
foreach($imgs['name'] as $position => $img_name){
$img_tmp = $imgs['tmp_name'][$position];
$img_size = $imgs['size'][$position];
$img_error = $imgs['error'][$position];
$img_ext = explode('.',$img_name);
$img_ext = strtolower(end($img_ext));
if(in_array($img_ext, $allowed)) {
if($img_error === 0){
if($img_size <= 500000) {
$img_name_new = uniqid('', true) . '.' . $img_ext;
$img_destination = 'img/'.$img_name_new;
if(move_uploaded_file($img_tmp, $img_destination)){
$uploaded[$position] = $img_destination;
}else{
$failed[$position] = "[{$img_name}] failed to upload";
}
}else{
$failed[$position] = "[{$img_name}] is too large";
}
}else{
$failed[$position] = "[{$img_name}] error";
}
}else{
$failed[$position] = "[{$img_name}] file extension";
}
}
if(!empty($uploaded)){
print_r($uploaded);
}
if(!empty($failed)){
print_r($failed);
}
}
if(isset($_POST['submit'])){
$name = $_POST['name'];
$location = $_POST['location'];
$status = $_POST['status'];
$descrip = $_POST['descrip'];
$category = $_POST['category'];
$img_name_new = $_FILES['imgs']['name'];
if ($db->connect_error){
die ("Connection Failed: " . $db->connect_error);
}
$sql_u = "SELECT * FROM projects WHERE name='$name'";
$sql_e = "SELECT * FROM projects WHERE category='$category'";
$res_u = mysqli_query($db, $sql_u);
$res_e = mysqli_query($db, $sql_e);
if (mysqli_num_rows($res_u) && mysqli_num_rows($res_e) > 0) {
echo "<div style='margin: 0 80px' class='alert alert-danger' role='alert'> Error. Item Already exists </div>";
header("refresh:3 url=add.php");
}else{
$sql_i = "INSERT INTO items (name, location, status, descrip, imgs, category) VALUES ('$name','$location','$status,'$descrip','$img_name_new','$category')";
}
if (mysqli_query($db, $sql_i)){
echo "Project Added Successfully";
}else{
echo mysqli_error($db);
}
$db->close();
}
?>
$img_name_new = $_FILES['imgs']['name'] is an array of one or more image names.
You will need to decide how you wish to store the array data as a string in your database.
Here are a couple of sensible options, but choosing the best one will be determined by how you are going to using this data once it is in the database.
implode() it -- $img_name_new = implode(',', $_FILES['imgs']['name']);
json_encode() it -- $img_name_new = json_encode($_FILES['imgs']['name']);
And here is my good deed for the year...
Form Script:
<?php
if (!$db = new mysqli("localhost", "root", "", "db")) { // declare and check for a falsey value
echo "Connection Failure"; // $db->connect_error <-- never show actual error details to public
} else {
if ($result = $db->query("SELECT name FROM items")) {
for ($rows = []; $row = $result->fetch_row(); $rows[] = $row);
$result->free();
?>
<script>
function checkName() {
var names = '<?php echo json_encode($rows); ?>';
var value = document.forms['project']['name'].value;
if (names.indexOf(value) !== -1) { // might not work on some old browsers
alert(value + ' is not a unique name. Please choose another.');
return false;
}
}
</script>
<?php
}
?>
<form name="project" method="post" enctype="multipart/form-data" onsubmit="return checkName()">
Name: <input required type="text" name="name"><br>
Location: <input required type="text" name="location"><br>
Status: <input required type="text" name="status"><br>
Category: <select required name="category">
<?php
if ($result = $db->query("SELECT category, category_alias FROM categories")) {
while ($row = $result->fetch_assoc()) {
echo "<option value=\"{$row['category']}\">{$row['category_alias']}</option>";
}
}
?>
</select><br>
<textarea required class="form-control" name="descrip" rows="5"></textarea><br>
<input style="text-align:left" type="file" name="imgs[]" multiple><br>
<button type="submit" name="submit" formaction="addaction.php">Add Project</button>
</form>
<?php
}
*notice that I have made a separate category table for validation.
Submission Handling Script: (addaction.php)
<?php
if (isset($_POST['submit'], $_POST['name'], $_POST['location'], $_POST['status'], $_POST['descrip'], $_POST['category'], $_FILES['imgs']['name'][0])) {
$paths = [];
if (!empty($_FILES['imgs']['name'][0])) {
$imgs = $_FILES['imgs'];
$allowed = array('jpg', 'png');
foreach($imgs['name'] as $position => $img_name){
$img_tmp = $imgs['tmp_name'][$position];
$img_size = $imgs['size'][$position];
$img_error = $imgs['error'][$position];
$img_ext = strtolower(pathinfo($img_name)['extension']);
if (!in_array($img_ext, $allowed)) {
$errors[] = "File extension is not in whitelist for $img_name ($position)";
} elseif ($img_error) {
$errors[] = "Image error for $img_name ($position): $image_error";
} elseif ($img_size > 500000) {
$errors[] = "Image $image_name ($position) is too large";
} else {
$img_destination = 'img/' . uniqid('', true) . ".$img_ext";
if (!move_uploaded_file($img_tmp, $img_destination)) {
$errors[] = "Failed to move $img_name ($position) to new directory";
} else {
$paths[] = $img_destination;
}
}
}
}
if (!empty($errors)) {
echo '<ul><li>' , implode('</li><li>', $errors) , '</li></ul>';
} elseif (!$db = new mysqli("localhost", "root", "", "db")) { // declare and check for a falsey value
echo "Connection Failure"; // $db->connect_error <-- never show actual error details to public
} elseif (!$stmt = $db->prepare("SELECT COUNT(*) FROM categories WHERE category = ?")) {
echo "Prepare Syntax Error"; // $db->error; <-- never show actual error details to public
} elseif (!$stmt->bind_param("s", $_POST['category']) || !$stmt->execute() || !$stmt->bind_result($found) || !$stmt->fetch()) {
echo "Category Statement Error"; // $stmt->error; <-- never show actual error details to public
} elseif (!$found) {
echo "Category Not Found - Project Not Saved";
} else {
$stmt->close();
$cs_paths = (string)implode(',', $paths);
// Set the `name` column in `items` to UNIQUE so that you cannot receive duplicate names in database table
if (!$stmt = $db->prepare("INSERT INTO items (name, location, status, category, descrip, imgs) VALUES (?,?,?,?,?,?)")) {
echo "Error # prepare"; // $db->error; // don't show to public
} elseif (!$stmt->bind_param("ssssss", $_POST['name'], $_POST['location'], $_POST['status'], $_POST['category'], $_POST['descrip'], $cs_paths)) {
echo "Error # bind"; // $stmt->error; // don't show to public
} elseif (!$stmt->execute()) {
if ($stmt->errno == 1062) {
echo "Duplicate name submitted, please go back to the form and change the project name to be unique";
} else {
echo "Error # execute" , $stmt->error; // $stmt->error; // don't show to public
}
} else {
echo "Project Added Successfully";
}
}
}
I'm getting the error message when uploading a form in php.
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near"
I've followed instructions from other posts as follows, to no avail:
1-Wrapped the column heading names in backticks.
2-Made sure all strings were passed as strings, and ints as ints.
3-Cleaned up any strings before sending out.
4-Made sure the connection to the database works and we can query from it.
5-Checked and re-checked my html code.
Here's my php code:
<?php
include('../config/config.php');
// Redirect browser if the upload form WAS NOT submited.
if (!isset($_POST['submit_upload']))
{
header("location: upload.html");
}
// Continue if the upload form WAS SUBMITED
else
{
// Set the upload directory path
$target_path = realpath( dirname( __FILE__ ) ) . "/uploads/audio/";
// Array to store validation errors
$error_msg = array();
// Validation error flag, if this becomes true we won't upload
$error_flag = false;
// We get the data from the upload form
$filename = $_FILES['file']['name'];
$temp_filename = $_FILES['file']['tmp_name'];
$filesize = $_FILES['file']['size'];
$mimetype = $_FILES['file']['type'];
// Convert all applicable characters to HTML entities
$filename = htmlentities($filename);
$mimetype = htmlentities($mimetype);
// Check for empty file
if ($filename == "")
{
$error_msg[] = 'No file selected!';
$error_flag = true;
}
// Check the mimetype of the file
if ($mimetype != "audio/x-mp3" && $mimetype != "audio/mp3")
{
$error_msg[] = 'The file you are trying to upload does not contain expected data.
Are you sure that the file is an MP3 one?';
$error_flag = true;
}
// Get the file extension, an honest file should have one
$ext = substr(strrchr($filename, '.') , 1);
if ($ext != 'mp3')
{
$error_msg[] = 'The file type or extention you are trying to upload is not allowed!
You can only upload MP3 files to the server!';
$error_flag = true;
}
// Check that the file really is an MP3 file by reading the first few characters of the file
$open = #fopen($_FILES['file']['tmp_name'], 'r');
$read = #fread($open, 3);
#fclose($open);
if ($read != "ID3")
{
$error_msg[] = "The file you are trying to upload does not seem to be an MP3 file.";
$error_flag = true;
}
// Now we check the filesize.
// The file size shouldn't include any other type of character than numbers
if (!is_numeric($filesize))
{
$error_msg[] = 'Bad filesize!';
$error_flag = true;
}
// If it is too big or too small then we reject it
// MP3 files should be at least 1MB and no more than 10 MB
// Check if the file is too large
if ($filesize > 10485760)
{
$error_msg[] = 'The file you are trying to upload is too large!
Please upload a smaller MP3 file';
$error_flag = true;
}
// Check if the file is too small
if ($filesize < 1048600)
{
$error_msg[] = 'The file you are trying to upload is too small!
It is too small to be a valid MP3 file.';
$error_flag = true;
}
// Function to sanitize values received from the form. Prevents SQL injection
function clean($conn, $str)
{
$str = #trim($str);
if (get_magic_quotes_gpc())
{
$str = stripslashes($str);
}
return mysqli_real_escape_string($conn, $str);
}
// Sanitize the POST values
$title = clean($conn, $_POST['title']);
$context = clean($conn, $_POST['context']);
$source = clean($conn, $_POST['source']);
$interviewer = clean($conn, $_POST['interviewer']);
$interviewee = clean($conn, $_POST['interviewee']);
$intervieweeAge = (int)$_POST['intervieweeAge'];
$geoRegion = clean($conn, $_POST['geoRegion']);
$language = clean($conn, $_POST['language']);
$recDate = clean($conn,$_POST['recDate']);
$keywords = $_POST['keywords'];
if ($title == '')
{
$error_msg[] = 'Title is missing';
$error_flag = true;
}
if ($interviewee == '')
{
$error_msg[] = 'Interviewee name/anonymous is missing';
$error_flag = true;
}
// If there are input validations, show errors
if ($error_flag == true)
{
foreach($error_msg as $c => $p) echo "Error " . $c . ": " . $p . "<br />";
}
// Else, all checks are done, move the file.
else
{
if (is_uploaded_file($temp_filename))
{
// Generate an uniqid
$uniqfilename = $interviewee . '_' . str_replace("_", "", $recDate) . '.mp3';
$filePath = '/uploads/audio/' . $uniqfilename;
// If the file was moved, change the filename
if (move_uploaded_file($temp_filename, $target_path . $uniqfilename))
{
// Again check that the file exists in the target path
if (#file_exists($target_path . $uniqfilename))
{
// Assign upload date to a variable
$upload_date = date("Y-m-d");
// Create INSERT query
$qry = "INSERT INTO FDM177_AUDIO_CLIPS (title,context,source,interviewer,interviewee,intervieweeAge,geoRegion,language,recDate,fileName,filePath)
VALUES('$title','$context','$source','$interviewer',$interviewee',$intervieweeAge,'$geoRegion','$language','$recDate','$uniqfilename','$filePath')";
$result = mysqli_query($conn, $qry) or die(mysqli_error($conn));
if ($result)
{
$id = mysqli_insert_id($conn);
echo "File uploaded. Now it is called :" . $uniqfilename . "<br />" . $date . "<br />";
}
else
{
echo "There was an error uploading the file, please try again!";
}
if(1) {
//if (is_array($keywords) || is_object($keywords)) {
foreach($keywords as $k) {
// $idQuery = "SELECT keyword_ID from KEYWORDS WHERE keywordName=" . $k";
$idQuery = mysqli_query($conn, "SELECT * FROM FDM177_KEYWORDS WHERE (`keywordName` LIKE '%".$k."%')") or die(mysql_error());
$matchingKArray = mysqli_fetch_array($idQuery);
$keyword_FK = $matchingKArray[keyword_ID];
// echo $kQuery;
echo $keyword_FK;
$qry = "INSERT INTO FDM177_JNCT_KWDS_CLIPS (keyword_FK, clip_FK)
VALUES ('$keyword_FK', '$id')";
$result = mysqli_query($conn, $qry);
if ($result)
{
echo 'inserted with keyword.' . $k . ' <br />';
}
}
}
else {
echo "keywords are missing";
}
}
}
else {
echo "There was an error uploading the file, please try again!";
}
}
else
{
echo "There was an error uploading the file, please try again!";
}
}
}
?>
The problem occurs at the first MYSQL query that starts as MYSQL query INSERT INTO FDM177_AUDIO_CLIPS...
What am I missing?
Thank you!
quotes breaking in one query '$interviewer',$interviewee',
$qry = "INSERT INTO FDM177_AUDIO_CLIPS
(title, context, source,interviewer, interviewee,
intervieweeAge,geoRegion,language,recDate,fileName,filePath)
VALUES
('$title', '$context', '$source', '$interviewer', '$interviewee',
$intervieweeAge,'$geoRegion','$language','$recDate','$uniqfilename','$filePath')";
I am new to php. I made a simple upload form in php. This is my code.
<html><head></head>
<body>
<form method="post" action="" enctype="multipart/form-data">
Upload File:
<input type="file" name="upload" /><br>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
<?php
include("config.php");
if(isset($_POST['submit']) )
{
$filename = $con->real_escape_string($_FILES['upload']['name']);
$filedata= $con->real_escape_string(file_get_contents($_FILES['upload']['tmp_name']));
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);
if ($_FILES['upload']['name'] == 0 ){
echo "<br><br> New record created successfully";
}
else {
$query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES ('$filename','$filedata','$filetype','$filesize')" ;
if ($con->query($query) === TRUE) {
echo "<br><br> New record created successfully";
} else {
echo "Error:<br>" . $con->error;
}
}
$con->close();
}
?>
It works fine. But if I press the submit with no files attached, it displays the error, Warning: file_get_contents(): Filename cannot be empty in C:\xampp\htdocs\contractdb\filetest.php on line 20 .
I want uploading files to be optional because not every user has the files to attach. I also want the user to download the files after uploading without removing file_get_contents($_FILES['upload']['tmp_name']).
How do I do this?
Your check should take in place before calling file_get_content() so it does not throw an error and you only call the function if file input is not empty:
if(isset($_POST['submit']) ) {
if ($_FILES['upload']['size'] != 0 ) {
$filename = $con->real_escape_string($_FILES['upload']['name']);
$filedata= $con->real_escape_string(file_get_contents($_FILES['upload']
['tmp_name']));
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);
$query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES ('$filename','$filedata','$filetype','$filesize')" ;
if ($con->query($query) == TRUE) {
echo "<br><br> New record created successfully";
} else {
echo "Error:<br>" . $con->error;
}
}
else {
echo 'error: empty file';
}
}
Try this:
if (isset($_POST['submit']) & ($_FILES['upload']['name']!=''))
{
// Statement
}
I can't seem to get the values to upload into the database table. It keeps giving me this error:
Upload Error, please try again.
Here is my code:
if(isset($_FILES['musicFile']['name']))
{
$uploaddir = "/accounts/groups/MDM2013.02/public_html/TPFinal/music/";
$uploadfile = basename($_FILES['musicFile']['name']);
$uploadpath = $uploaddir . $uploadfile;
//echo substr($uploadfile, -3);
//echo $uploaddir;
//echo $uploadpath;
//var_dump($uploadfile);
if((strcasecmp(substr($uploadfile, -3), "mp3") == 0))//||(strcasecmp(substr($uploadfile, -3, 3), "wav") == 0))
{
if(!is_file($uploadpath))
{
if (move_uploaded_file($_FILES['musicFile']['tmp_name'],$uploadpath))
{
if((strcasecmp($type,"audio/mp3") == 0))// || (strcasecmp($type, "music/wav")== 0))
{
echo "File of a valid type ($type), and was stored as $uploadfile<br/>\n";
$data = $_POST['musicFile']; $art = $_POST['ArtistName']; $title = $_POST['MusicTitle'];
$sql = "INSERT INTO Music(UserName,MusicName,MusicType, Artist, Data) VALUES ('$username','$title','$type', '$art', '$data')";
$result= mysql_query($sql);
if($result)
{
if(mysql_affected_rows() == 1)
{
echo "Music inserted into Database, with ID = ",
mysql_insert_id();
}
}
}else{echo "Failed mime-checking <br/>"; unlink($uploadpath);}
}else{echo "Upload Error, please try again! <BR/> \n";}
}else echo "File already exists <br/>\n";}
else echo "Only MP3 files are acceptable ($uploadfile) <br/>\n";}
include_once ("db_close.php");
?>
You can actually check what specific error you are getting. Try checking your errors here