I have a problem when moving an uploaded file into a local directory.
When running the following code, the output is always "error uploading file". It seems to always not meet the condition for the 'move_uploaded_media' function and therefore $result is not being set?
Are there any glaring mistakes?
<?php
$page_title = 'Admin | Multimedia Portfolio';
include('includes/admin_header.html');
if(isset($_POST['submitted']))
{
$uploadDir = 'files/';
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file"; // Here is were the it always gets caught
exit;
}
require_once('mysql_connect.php');
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$query = "INSERT INTO files (name, size, type, path ) VALUES ('$fileName', '$fileSize', '$fileType', '$filePath')";
mysqli_query($dbc, $query) or die('Error, query failed : ' . mysql_error());
mysqli_close($dbc);
echo "<br>Files uploaded<br>";
}
?>
<div id="content-wrap">
<h1>Upload Media</h1>
<div id="content">
<form method="post" action="upload.php" encytype="multipart/form-data">
<fieldset>
<div class="entry">
<label>Which media <span class="highlight">file</span> would you like to upload?</label>
<input type="file" name="userfile" id="userfile" size="30" />
</div>
<fieldset id="button">
<input type="submit" value="Register" />
<input type="hidden" name="submitted" value="TRUE" />
</fieldset>
</fieldset>
</form>
</div>
</div>
<?php
include('includes/admin_footer.html');
?>
Not sure if there is more, but you have encytype instead of enctype in your <form>.
You might also want to perform an is_uploaded_file() check on the temporary file, just to be sure...
Related
I have created a form and wanted to store all the information in PHPMyAdmin. I managed to store the other information but not the image file. It has nothing under the image column in PHPMyAdmin even though it states submitted when I submit the form.
form2.php
<!DOCTYPE html>
<html>
<head>
</head>
<h1>Found Items Handover</h1>
<br>
<div class="container">
<div class="row">
<h2>1. Details of Handover Personnel </h2>
</div>
<form action="insert2.php" method="post" enctype="multipart/form-data">
<div class="row input-container">
<div class="col-md-6 col-sm-12">
<div class="styled-input">
<input type="text" name="name"required />
<label>Staff Name</label>
</div>
</div>
<div class="col-md-6 col-sm-12">
<div class="styled-input" style="float:right;">
<input type="text" name="staffno" required />
<label>Staff Number</label>
</div>
</div> <br>
<div>
<label>Attachment:</label><input type='file' name='file'><br>
</div>
</div>
<br><input type="submit" name="submit" value="submit">
</form>
inser2.php
<?php
$con= mysqli_connect('127.0.0.1','root','','satsform1');
if(!$con)
{
echo 'Not Connected To Server';
}
if(!mysqli_select_db($con,'satsform1'))
{
echo 'Database Not Selected';
}
$name = $_POST['name'];
$staffno = $_POST['staffno'];
$sql = "INSERT INTO handover (name,staffno)
VALUES ('$name','$staffno')";
if(isset($_POST['submit'])){
$name = $_FILES['file']['name'];
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
// Select file type
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Valid file extensions
$extensions_arr = array("jpg","jpeg","png","gif");
// Check extension
if( in_array($imageFileType,$extensions_arr) ){
// Insert record
$query = "insert into images(name) values('".$name."')";
mysqli_query($con,$query);
// Upload file
move_uploaded_file($_FILES['file']['tmp_name'],$target_dir.$name);
}
}
if(!mysqli_query($con,$sql))
{
echo 'Not Submitted';
}
else
{
echo 'Submitted';
}
?>
I expect the URL of the image to be stored in PHPMyAdmin when I submit the form.
please insert following code in insert2.php file with your respective variable and file names.
<?php
$con= mysqli_connect('localhost','root','','join');
if(!$con)
{
echo 'Not Connected To Server';
}
if(!mysqli_select_db($con,'join'))
{
echo 'Database Not Selected';
}
$target_dir = "uploads/";
echo "<br>";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
echo "<br>";
$name = $_POST['name'];
$staffno = $_POST['staffno'];
// get details of the uploaded file
$fileTmpPath = $_FILES['file']['tmp_name'];
$fileName = $_FILES['file']['name'];
$fileSize = $_FILES['file']['size'];
$fileType = $_FILES['file']['type'];
$fileNameCmps = explode(".", $fileName);
$fileExtension = strtolower(end($fileNameCmps));
$allowedfileExtensions = array('jpg', 'gif', 'png','jpeg');
if (in_array($fileExtension, $allowedfileExtensions)) {
if(move_uploaded_file($_FILES['file']['tmp_name'], $target_file)) {
echo "File uploaded successfully!";
$query = "INSERT INTO user (image)
VALUES ('$target_file')";
mysqli_query($con,$query);
if(!mysqli_query($con,$query))
{
echo 'Not Submitted';
}
else
{
echo 'Submitted';
}
} else{
echo "Sorry, file not uploaded, please try again!";
}
}
?>
I am having some input types in a HTML form and a file uploader. But I am unable to upload both data and file at the same time in the MySQL database. Every time blank entries are filled up into the database...
HTML Form
<form method="post" action="upload.php" enctype="multipart/form-data">
<p>
<label>Name:</label>
<input type="text" name="name" size="40">
</p>
<p>
<label>Email:</label>
<input type="email" name="email">
</p>
<p>
<input type="radio" name="gen" value="Male">Male
<input type="radio" name="gen" value="Female">Female</p>
<input type="hidden" name="MAX_FILE_SIZE" value="1000000">
<br>File to upload:
<br>
<input type="file" name="File" size="40">
<p>
<input type="submit" name="submit" value="submit">
</form>
PHP Code
if(isset($_POST['name']) && isset($_POST['email']) &&
isset($_POST['gen']) && $_FILES['File']['size'] > 0) {
$name=get_POST('name');
$email=get_POST('email');
$gender=get_POST('gen');
$filename = $_FILES['File']['name'];
$tmpname = $_FILES['File']['tmp_name'];
$filesize = $_FILES['File']['size'];
$filetype = $_FILES['File']['type'];
$fp = fopen($tmpname, 'r');
$file = fread($fp, filesize($tmpname));
$file = addslashes($file);
fclose($fp);
if(!get_magic_quotes_gpc()) {
$filename = addslashes($filename);
}
$query = "
INSERT INTO uploadform
(Name, Email, Gender, Filename, Filetype, Filesize, File) VALUES
('$name', '$email', '$gender', '$filename', '$filetype', '$filesize', '$file');";
mysql_query($query) or die('Error, query failed');
}
In the database the datatype of the file is MEDIUMBLOB
Ok I found the Answers...! Just check with the variables...I have used other database and example (common sense)...
<?php
//This is the directory where images will be saved
$target = "images/";
if(!is_dir($target)) mkdir($target);
$target = $target . basename( $_FILES['photo']['name']);
//This gets all the other information from the form
$name=$_POST['username'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$fname=($_FILES['photo']['name']);
$tmpName = $_FILES['photo']['tmp_name'];
$fileSize = $_FILES['photo']['size'];
$fileType = $_FILES['photo']['type'];
//process the file
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc()){
$fname = addslashes($fname);}
// Connects to your Database
require_once 'login.php';
$db_server=mysql_connect($db_hostname,$db_username,$db_password);
if(!$db_server) die("Unable to connect to MySQL" .mysql_error());
mysql_select_db($db_database,$db_server)
or die("Unable to connect to database" .mysql_error());
//Writes the information to the database
mysql_query("INSERT INTO `employees` VALUES ('$name', '$email', '$phone', '$fname','$fileType','$fileSize','$content')") ;
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['photo']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
<form enctype="multipart/form-data" action="up.php" method="POST">
Name: <input type="text" name="username"><br>
E-mail: <input type="text" name = "email"><br>
Phone: <input type="text" name = "phone"><br>
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
Photo: <input type="file" name="photo"><br>
<input type="submit" value="Add">
</form>
I want to insert image path into database table so I can later display it on a different place but only thing that is getting inserted into the table is the folder name where pictures are uploaded into and the image name is missing.
Here is my code:
<?php
require "connect.php";
if(isset($_GET['id']))
{
$id = $_GET['id'];
}
$uploaddir = 'uploaded';
if(isset($_POST['submit']))
{
$filename = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
$filepath = $uploaddir . $filename;
move_uploaded_file($tmp,$filepath);
$filepath=addslashes($filepath);
mysqli_query($conn,"UPDATE vijesti SET imeslike='$filepath' WHERE id='$id'");
mysqli_close($conn);
}
?>
<div id="main">
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" value="upload"/>
</form>
</div>
Table column named imeslike is supposed to be updated with image path but it only shows uploaded/. It's like it does not accept variables when I put some random string in my query it gets updated and the string value shows up in the imeslike column.
The uploaded folder is in same directory so the relative path is OK and I also tried absolute path like:
$uploaddir="C:/wamp/www/admirovsajt/uploaded"
But same problem.
Verify that image was uploaded before looking for correct path in the database.
instead of:
$uploaddir = 'uploaded';
try
$uploaddir = 'uploaded/';
Try:
<?php
require "connect.php";
if(isset($_GET['id'])) {
echo $id = $_GET['id'];
}
$uploaddir = 'uploaded/';
if(isset($_POST['submit'])) {
$pid = $_POST['pid'];
$filename = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
$filepath = $uploaddir . $filename;
move_uploaded_file($tmp,$filepath);
$filepath=addslashes($filepath);
mysqli_query($conn,"UPDATE vijesti SET imeslike='$filepath' WHERE id='$pid'");
mysqli_close($conn);
}
?>
<div id="main">
<form action="" method="post" enctype="multipart/form-data">
<input type="text" name="pid" value="<?php echo $id;?>">
<input type="file" name="image"/>
<input name="submit" type="submit" value="upload"/>
</form>
</div>
would you help for my code , i need to do the multiple upload but i cant so will you help me please. i need so bad.
here's my code
i made multiple upload the form but it is not working. the output is "error array"
//HTML
<html>
<head>
<form name="Image" enctype="multipart/form-data" action="upload.php" method="POST">
<h1><font face="tahoma"> UPLOAD FILES</h1>
<label for="file">Filename:</label>
<input type="file" name="Photo[]" accept="image/*" multiple="multiple"/><br/><br/>
<input type="hidden" id="pageName" name="pageName">
<script type="text/javascript">
//get page name from parent
var value = window.opener.pageName
document.getElementById("pageName").value = value;
</script>
<INPUT type="submit" class="button" name="Submit" value=" Upload ">
<INPUT type="reset" class="button" value="Cancel"><br/><br/>
</form>
</head>
</html>
//PHP this is were upload is do.
<?php
include('global.php');
?>
<?
$uploadDir = 'directory/'; //Image Upload Folder
if(isset($_POST['Submit']))
{
$fileName = $_FILES['Photo']['name'][0];
$fileName1 = $_FILES['Photo']['name'][1];
$tmpName = $_FILES['Photo']['tmp_name'];
$fileSize = $_FILES['Photo']['size'];
$fileType = $_FILES['Photo']['type'];
$filePath = $uploadDir . $fileName . $fileName1;
//upload error
if ($_FILES["Photo"]["error"] > 0)
{
echo "Error: " . $_FILES["Photo"]["error"] . "<br />";
}
//photo already exixts
else
//insert image into DB
{
move_uploaded_file($tmpName, $filePath);
$filePath = addslashes($filePath);
$filePath = stripslashes($filePath);
$filePath = mysql_real_escape_string($filePath);
$query = "INSERT INTO images (image , category ) VALUES ('$filePath', '$pageName')";
mysql_query($query) or die('Error, query failed');
echo" Upload Successful. <br/> <br/>";
echo "Stored in: " . "directory/" . $_FILES["Photo"]["name"];
?>
<br/><br/>
<img width="300" height="400" src="directory /<?=$_FILES["Photo"]["name"]?>"><br/>
<?
}
}
?>
Error: Array is telling you that the error being returned is actually an Array object, not a string. If you want to see the actual error message, you need to view the full contents of the array. Something like print_r($_FILES["Photo"]["error"]); or looping through the array like so
foreach($_FILES["Photo"]["error"] as $err) {
echo "error: " . $err . "<br>";
}
Or you can just print the first error returned just as you have returned the first file in your name array echo $_FILES["Photo"]["error"][0];
I have a problem with some PHP/MySQL not working. I can upload files like .docx and .sql perfectly but when i try with .gif, .jpg .zip and .rar, it doesn't work.
Here is the upload form code:
<?php
if (isset($_GET['uploadError']))
{
echo '<div id="error">There was an error uploading the file. Please try again</div>';
}
elseif ((!isset($_SESSION['dbusername']))&&(!isset($_SESSION['dbpassword'])))
{
header('Location: ?page=login&uploadAttempt=true&attemptedSite=upload');
}
else
{
echo '
<center>
<form class="form" enctype="multipart/form-data" action="uploadaction.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="30720" />
<p class="uploadfile">
<input name="uploadedfile" type="file" />
</p>
<p class="submit">
<input type="hidden" name="upload" value="start" />
<input type="submit" value="Upload File" />
</p>
</form></center>';
}
?>
Here is the uploadaction.php code:
<?php
require('lib.php');
localhost_con('filehunt');
session_start();
if(isset($_POST['upload']) && $_FILES['uploadedfile']['size'] > 0)
{
$fileName = $_FILES['uploadedfile']['name'];
$tmpName = $_FILES['uploadedfile']['tmp_name'];
$fileSize = $_FILES['uploadedfile']['size'];
$fileType = $_FILES['uploadedfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
/*$fh = fopen($_FILES['uploadedfile']['tmp_name'], 'r');
$theData = fread($fh, filesize($_FILES['uploadedfile']['tmp_name']));
$theData = mysql_real_escape_string($theData);
fclose($fh); */
$date = date("y/m/d : H:i:s", time());
$sql = "INSERT INTO files (rowID, file, mimetype, data, uploaded_by, uploaded_date, size, times_downloaded)
VALUES (NULL, '$fileName', '$fileType', '$content', '$user', '$date', $fileSize, 0);";
if (mysql_query($sql,$con))
{
header('Location: index.php?page=search&uploadSucces=true');
}
else echo mysql_error();
}
else header('Location: index.php?page=upload&uploadError=true');
?>
It gets inserted in the database, but the mimetype and data column is empty.
Can anyone tell me why this is happening, and how to fix it?
Thank you in advance
Adam
I had the same problem with other type of files. The workaround is encoding the file with base64 that is safer to transmit (do not contain invalid characters that may truncate the streaming).
Not quite shure, but this:
$fileType = $_FILES['uploadedfile']['type'];
must be like this:
$finfo = new finfo();
$fileType = $finfo->file($_FILES['uploadedfile']['tmp_name'], FILEINFO_MIME);