Im having problems with my uploading form using php I have created pages like this in the past but for some reason this one seems to be playing up I'm hoping i have just missed something so simple. Im trying to create and upload form to upload Wav, rar, zip and txt files and returning error on everything else.
If i try and upload a file which is not related to these it shows an error but if i try to upload a wav or a zip file it doesn't work i don't get any kind of error report but if i was to upload a .txt file it seems to work fine.
my html code is;
<form action="<?php echo $site_url; ?>upload.php" enctype="multipart/form-data" method="post">
<input type="hidden" name="upload" id="upload" value="upload" />
<label for="invoice"><strong>Select Invoice Number</strong></label>
<select name="invoice" <?php if (array_key_exists('invoice', $add_product_errors)) echo ' class="error"'; ?>>
<?php while($row = mysqli_fetch_array($r)){ ?>
<option value="<?php echo $row[0] ; ?>"
<?php if (isset($_POST['invoice']) && ($_POST['invoice'] == $row[0]) ) echo ' selected="selected"';
echo ">" .$row[0]. "</option>\n"; ?>
<?php } ?>
</select><?php if (array_key_exists('invoice', $add_product_errors)) echo ' <span class="error">' .$add_product_errors['invoice']. '</span>'; ?>
<label for="track"><strong>Upload File</strong></label>
<input type="hidden" name="MAX_FILE_SIZE" value="5120000" />
<input type="file" name="song" id="song" <?php if (array_key_exists('song', $add_product_errors)){ echo " class=\"error\" /> <span class=\"error\">" .$add_product_errors['song']. "</span>"; }else{ echo ' />'; if (isset($_SESSION['song'])){ echo " CURRENTLY '{$_SESSION['song']['file_name']}'"; } } ?>
<input type="submit" name="upload_files" id="upload_files" value="Upload Files" />
</form>
and my php script;
if(isset( $_POST['upload'])){
if(is_uploaded_file($_FILES['song']['tmp_name']) && ($_FILES['song']['error'] == UPLOAD_ERR_OK)){
$file = $_FILES['song'];
$size = ROUND($file['size']/1024);
if($size > 5120000){
$add_product_errors['song'] = 'The File Size is too Big';
}// END FILE SIZE
$allowed_mime = array('audio/wav', 'audio/x-wav', 'application/x-compressed', 'application/x-zip-compressed', 'application/zip', 'multipart/x-zip', 'text/plain');
$allowed_extensions = array('.wav', '.zip', '.rar', '.txt');
$ext = substr($file['name'], -4);
if((!in_array($file['type'], $allowed_mime))
|| (!in_array($ext, $allowed_extensions))
){
$add_product_errors['song'] = "We Only accept .wav and .zip files please do not send .mp3 files";
}// END IF WRONG EXT
if (!array_key_exists('song', $add_product_errors)){
$dest = "clients/" . $username[0] . "/" . $_POST['invoice'] . "/" . $file['name'];
if(move_uploaded_file($file['tmp_name'], $dest)){
// $_SESSION['image']['new_name'] = $new_name;
$_SESSION['song']['file_name'] = $file['name'];
$add_product['text'] = "Files has successfully been moved\n";
}else{
trigger_error('the file could not be moved.');
unlink($file['tmp_name']);
}// END if file is moved
}// END if file can be moved
}elseif (!isset($_SESSION['song'])){
switch ($_FILES['song']['error']){
case 1:
case 2:
$add_product_errors['song'] = "File is too big 5GB Max";
break;
case 3:
$add_product_errors['song'] = "the file was partially uploaded";
break;
case 6:
case 7:
case 8:
$add_product_errors['song'] = "Couldn't upload due to a system error";
break;
case 4:
default:
$add_product_errors['song'] = "No file was uploaded";
break;
}//END OF SWITCH
}
if(empty($add_product_errors)){
echo 'yes';
$body = $username[0] . " has uploaded files in to " . $_POST['invoice'] . " Ready to start downloading and working on";
//mail($site_email, 'file has been loaded',$body,'from:' .$site_email);
//$_POST = array();
//$files = array();
unset($file,$_SESSION['song']);
}
}//END IF $_POST UPLOAD
any help would be so much appreciated thank you
Try removing the check for mime types and see what it gives first
Related
I'm uploading PDFs to a directory and my script works fine for one directory but I'm having troubles coming up with a way to write the script efficiently when I have more then one directory to upload PDFs on a page. I know of a few ways I can do it, like write another function like below but there must be a better way so I dont have to write out the whole script for every directory I want to upload PDFs to. Code below.
if(is_post_request()) {
$targetdirectory = "../../pathofdirectory/pdf/";
$targetdirectory = $targetdirectory . basename( $_FILES['file']['name']) ;
$file_type=$_FILES['file']['type'];
if ($file_type=="application/pdf") {
if(move_uploaded_file($_FILES['file']['tmp_name'], $targetdirectory))
{
$message = "The file ". basename( $_FILES['file']['name']). " is uploaded";
}
else {
$message = "Problem uploading file";
}
}
else {
$message = "You may only upload PDFs.<br>";
}
}
And of course the simple form
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<input class="button common" type="submit" value="Submit" />
</form>
Thanks in advance for any suggestions.
If you're okay with allowing users choosing which directory to upload to, you can give them the option.
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<select name="folderOption">
<option value="1">First Folder</option>
<option value="2">Second Folder</option>
<option value="3">Third Folder</option>
</select>
<input class="button common" type="submit" value="Submit" />
</form>
Obviously, you would need to validate server-side for bad data.
if (is_post_request()) {
$targetdirectory = "../../pathofdirectory/pdf/";
$targetdirectory = $targetdirectory . basename( $_FILES['file']['name']) ;
$file_type = $_FILES['file']['type'];
$folderOption = $_POST['folderOption'];
if ($folderOption == 1 || $folderOption == 2 || $folderOption == 3) {
switch ($folderOption) {
case 1:
$targetdirectory = "../../pathofdirectory/pdf/";
break;
case 2:
$targetdirectory = "../../pathofdirectory2/pdf/";
break;
case 3:
$targetdirectory = "../../pathofdirectory3/pdf/";
break;
default:
$targetdirectory = "../../pathofdirectory/pdf/";
}
if ($file_type == "application/pdf") {
if(move_uploaded_file($_FILES['file']['tmp_name'], $targetdirectory)) {
$message = "The file ". basename( $_FILES['file']['name']). " is uploaded";
} else {
$message = "Problem uploading file";
}
} else {
$message = "You may only upload PDFs.<br>";
}
} else {
$message = "Bad data received for directory choice.<br>";
}
}
Im doing a webpage and have a problem with file upload, that changes the file name umlauts into a weird name.
For example when i upload a file called "töö.docx" and look at the name in the uploaded folder, it shows me this "tƶƶ.docx".
When i call out the name of the file in index.php it shows me the correct name "töö.docx".
But after i go into the upload folder and change the name "tƶƶ.docx" manually into "töö.docx" and than call out the name of the file in index.php, it shows me "t��.docx" which is wrong.
Here is the code for upload in index.php:
<form method="post" enctype="multipart/form-data">
<strong>File upload:</strong>
<small>(max 8 Mb)</small>
<input type="file" name="fileToUpload" required>
<input type="submit" value="Upload" name="submit">
</form>
And here is the upload controller code:
$doc_list = array();
foreach (new DirectoryIterator('uploads/') as $file)
{
if ($file->isDot() || !$file->isFile()) continue;
$doc_list[] = $file->getFilename();
}
$target_dir = "uploads/";
$target_file = $target_dir . basename( isset($_FILES["fileToUpload"]["name"]) ? $_FILES["fileToUpload"]["name"] : "");
$file = isset($_FILES["fileToUpload"]) ? $_FILES["fileToUpload"] : "";
$up_this = isset($_FILES["fileToUpload"]["tmp_name"]) ? $_FILES["fileToUpload"]["tmp_name"] : "";
$file_name = isset($_FILES["fileToUpload"]["name"]) ? $_FILES["fileToUpload"]["name"] : "";
if (!empty($file)) {
if(isset($_POST["submit"])) {
if (file_exists($file_name)) {
echo "File already exists.";
exit;
} else {
$upload = move_uploaded_file($up_this, $target_file);
if ($upload) {
echo "File ". '"' . basename($file_name). '"' . " has been uploaded";
} else if (!$upload) {
echo "Could not upload file";
exit;
}
}
}
}
I use the variable $doc_list to call out the names of the documents in folder in index.php:
<div>
<?php if (!empty($doc_list)) foreach ($doc_list as $doc_name) { ?>
<tr>
<td><?= $doc_name ?></td>
</tr>
<?php } ?>
</div>
I've set the website charset into utf-8. and i still don't know why it's not displaying the correct file name with umlauts.
Try to add accept-charset="UTF-8" like this:
<form method="post" enctype="multipart/form-data" accept-charset="UTF-8">
I need help in writing this code to upload and save uploaded image in data base.
File 1:
<?php
<form action="upload.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="startUpload();" >
<label>File:
<input name="myfile" type="file" size="30" />
</label>
<input type="submit" name="submitBtn" class="sbtn" value="Upload" />
<iframeid="upload_target"name="upload_target"src="#"style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>
</div>
File 2:
<?php
// Edit upload location here
$destination_path = getcwd().DIRECTORY_SEPARATOR;
$target_path="my/";
$result = 0;
$name=$_FILES['myfile']['name'];
$target_path = $target_path . basename( $_FILES['myfile']['name']);
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
list($width, $height, $type, $attr) = getimagesize($target_path);
echo "Image width " .$width;
echo "<BR>";
echo "Image height " .$height;
echo "<BR>";
echo "Image type " .$type;
echo "<BR>";
echo "Attribute " .$attr;
$result = 1;
}
// sleep(1);
$link=mysql_connect('localhost','root','');
if(!$link)
{die('you cannot connect to database...');}
$db=mysql_select_db('final');
if(!$db)die('smile');
if (isset($_FILES['myfile']) && $_FILES['myfile']['size'] > 0) {
// define the posted file into variables
$name = $_FILES['myfile']['name'];
$tmp_name = $_FILES['myfile']['tmp_name'];
$type = $_FILES['myfile']['type'];
$size = $_FILES['myfile']['size'];
// if your server has magic quotes turned off, add slashes manually
//if(!get_magic_quotes_gpc()){
//$name = addslashes($name);
//}
// open up the file and extract the data/content from it
$extract = fopen($tmp_name, 'r');
$content = fread($extract, filesize($tmp_name));
$content = addslashes($content);
fclose($extract);
// connect to the database
// the query that will add this to the database
$s=mysql_query("SET NAMES 'utf8'");
$sql = "INSERT INTO `final`.`products` (`Productcode`, `Productname`, `Price`,`Descriptionofgood`, `image`) VALUES ('','','','','".$target_path."') WHERE `products`.`Productcode`='1371' ";
$results = mysql_query($sql);
if(!$result)die('not');
}
?>
Technically, if it is a small project.
You should not store images files in "Database" ; rather only their link (you may not even need that). Image or any media files are stored on server along with your other files (html,css,php). Of course, you need to put them on a dedicated folder for it.
The reason for not storing on database : because they are meant for data retrieval only and more importantly they are of smaller size (bigger sizes do exist, i am speaking in case of a small project which requires least possible resources. Storing media files on database is just not efficient.
Looking at your code, i can tell you are trying to store the files on your server.
They have used a very simple script for uploading here . Try it on your localhost before trying on a server.
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) is incorrect.
It should be if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path))
Remove the #.
I have created three page for it
index.php (Form for uplad image)
upload.php (Save the image in upload folder and its path in database)
3.showimage.php (Show the images from database)
Database Structure
id int(4) auto increment - image varchar(100) - image_name varchar(50)
here is the code:
index.php
<form method="post" action="upload.php" enctype="multipart/form-data">
<label>Choose File to Upload:</label><br />
<input type="hidden" name="id" />
<input type="file" name="uploadimage" /><br />
<input type="submit" value="upload" />
</form>
uplad.php
<?php
$target_Folder = "upload/";
$uid = $_POST['id'];
$target_Path = $target_Folder.basename( $_FILES['uploadimage']['name'] );
$savepath = $target_Path.basename( $_FILES['uploadimage']['name'] );
$file_name = $_FILES['uploadimage']['name'];
if(file_exists('upload/'.$file_name))
{
echo "That File Already Exisit";
}
else
{
// Database
con=mysqli_connect("localhost","user_name","password","database_name"); //Change it if required
//Check Connection
if(mysqli_connect_errno())
{
echo "Failed to connect to database" . mysqli_connect_errno();
}
$sql = "INSERT INTO image (id,image, image_name)
VALUES ('','$target_Folder$file_name','$file_name') ";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added successfully in the database";
echo '<br />';
mysqli_close($con);
// Move the file into UPLOAD folder
move_uploaded_file( $_FILES['uploadimage']['tmp_name'], $target_Path );
echo "File Uploaded <br />";
echo 'File Successfully Uploaded to: ' . $target_Path;
echo '<br />';
echo 'File Name: ' . $_FILES['uploadimage']['name'];
echo'<br />';
echo 'File Type: ' . $_FILES['uploadimage']['type'];
echo'<br />';
echo 'File Size: ' . $_FILES['uploadimage']['size'];
}
?>
Show Image
showimage.php
<?php
$con=mysqli_connect("localhost","user_name","password","test"); //Change it if required
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM image " );
while($row = mysqli_fetch_array($result))
{
echo '<img src="' . $row['image'] . '" width="200" />';
echo'<br /><br />';
}
mysqli_close($con);
?>
I use the Following code to upload a single file .With This code I can Upload a single file to the database .I want to make multiple files uploaded by selecting multiple files in a single input type file.What Changes should i make in the code to make it upload multiple files?
<?PHP
INCLUDE ("DB_Config.php");
$id=$_POST['id'];
$fileTypes = array('txt','doc','docx','ppt','pptx','pdf');
$fileParts = pathinfo($_FILES['uploaded_file']['name']);
if(in_array($fileParts['extension'],$fileTypes))
{
$filename = $_FILES["uploaded_file"]["name"];
$location = "E:\\test_TrainingMaterial/";
$file_size = $_FILES["uploaded_file"]["size"];
$path = $location . basename( $_FILES['uploaded_file']['name']);
if(file_exists($path))
{
echo "File Already Exists.<br/>";
echo "Please Rename and Try Again";
}
else
{
if($file_size < 209715200)
{
$move = move_uploaded_file( $_FILES["uploaded_file"]["tmp_name"], $location . $_FILES['uploaded_file']['name']);
$result = $mysqli->multi_query("call sp_upload_file('".$id."','" . $filename . "','".$path."')");
if ($result)
{
do {
if ($temp_resource = $mysqli->use_result())
{
while ($row = $temp_resource->fetch_array(MYSQLI_ASSOC)) {
array_push($rows, $row);
}
$temp_resource->free_result();
}
} while ($mysqli->next_result());
}
if($move)
{
echo "Successfully Uploaded";
}
else
{
echo "File not Moved";
}
}
else
{
echo "File Size Exceeded";
}
}
}
else
{
echo " Invalid File Type";
}
?>
The Html That is used is
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file" id="uploaded_file" style="color:black" /><br/>
</form>
Basically you need to add to input name [] brackets and attribute "multiple"
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file[]" multiple="true" id="uploaded_file" style="color:black" /><br/>
</form>
Now all uploaded file will be available via
$_FILES['uploaded_file']['name'][0]
$_FILES['uploaded_file']['name'][1]
and so on
More info at
http://www.php.net/manual/en/features.file-upload.multiple.php
How can I save an image safely from a file input field using PHP & MySQL?
Here is the input file field.
<input type="file" name="pic" id="pic" size="25" />
This is a simple example, it should work.
Although you probably want to add checking for image types, file sizes, etc.
<?php
$image = $_POST['pic'];
//Stores the filename as it was on the client computer.
$imagename = $_FILES['pic']['name'];
//Stores the filetype e.g image/jpeg
$imagetype = $_FILES['pic']['type'];
//Stores any error codes from the upload.
$imageerror = $_FILES['pic']['error'];
//Stores the tempname as it is given by the host when uploaded.
$imagetemp = $_FILES['pic']['tmp_name'];
//The path you wish to upload the image to
$imagePath = "images/";
if(is_uploaded_file($imagetemp)) {
if(move_uploaded_file($imagetemp, $imagePath . $imagename)) {
echo "Sussecfully uploaded your image.";
}
else {
echo "Failed to move your image.";
}
}
else {
echo "Failed to upload your image.";
}
?>
http://php.net/file_upload covers just about everything you need to know.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$tmpFile = $_FILES['pic']['tmp_name'];
$newFile = '/new_location/to/file/'.$_FILES['pic']['name'];
$result = move_uploaded_file($tmpFile, $newFile);
echo $_FILES['pic']['name'];
if ($result) {
echo ' was uploaded<br />';
} else {
echo ' failed to upload<br />';
}
}
?>
<form action="" enctype="multipart/form-data" method="POST>
<input type="file" name="pic" />
<input type="submit" value="Upload" />
</form>