I get this error everytime i hit the submit button. Everything else is submitted to the database, only the image isn't.
Warning: file_get_contents(): Filename cannot be empty
Any idea? Here is my code.
if(isset($_POST['consultationbutton'])){
$image = addslashes(file_get_contents($_FILES['selectedfile']['tmp_name'])); //SQL Injection defence!
$image_name = addslashes($_FILES['selectedfile']['name']);
$checkedcondition = implode(",",$_POST['skincondition']);
$checkedproduct = implode(",",$_POST['skincareinuse']);
$consultquery="INSERT INTO counsel(nric,dateconsulted,editableface,skincarecurrentlyinuse,skincondition,imagename) VALUES('132','$_POST[storedate]','{$image}','$checkedproduct','$checkedcondition','{$image_name}')";
mysqli_query($dbconn,$consultquery);
// mysqli_escape_string($dbconn,$image);
echo $checkedcondition;
echo $checkedproduct;
}
<form action="BAConsult.php" enctype="multipart/form-data" method='post'>
<img id="customerface" src="#" alt="your image" class ="consultimg"></img>
Select a file to upload: <input type="file" name="selectedfile" onchange="readURL(this);">
<input type='submit' name='consultationbutton' class='consultationbutton' value='Complete Consultation' onclick='submitclick();'>
</form>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#customerface')
.attr('src', e.target.result)
.width(400)
.height(400);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
In the $_FILES array, you've said you're getting [name]=>DSC_0770.JPG[type]=> [tmp_name]=>[error]=>1[size]=>0
If tmp_name is not given, that means the file was not uploaded.
The error you're given is 1, and according to the upload error messages explained page this means: that the uploaded file exceeds the upload_max_filesize directive in php.ini.
You can do the following to fix this.
Find your php.ini file and increase the size of upload_max_filesize.
Use ini_set('upload_max_filesize', '20M'); or whatever size you want at the start of your script.
Compress your images before uploading.
make sure you add enctype="multipart/form-data" attribute in your <form> tag. like
<form action="your_action_file" method="post" enctype="multipart/form-data">
Related
Is this possible to display an image on the currunt browser session without uploading it to the server?
I am trying to display an image on my php page when users enter the upload button ,the uploaded image will temprory appear on the target url.
Here is my html form
<form action="demo.php"method="post"enctype="multipart/form-data">
<input type="file"name="uf">
<input type="submit"value="upload">
</form>
And the target file :
<?php
$pic=$_FILES["uf"]["name"];
echo "<img src='$pic'>";
It doesnt display the image. So is this somehow possible to display the image the way I am doing it?
Any help is much appriciated!
THANKS!
Here you go: http://jsfiddle.net/LvsYc/
html:
<form method="post" enctype="multipart/form-data">
<input type="file" id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
js (requires jQuery):
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
You can convert the image into base64, see http://www.motobit.com/util/base64/css-images-to-base64.asp .
It will generate an <img /> like this: <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAA// lot more characters" />
It is, in my mind, a bad practice, since your browser cache the images in order to avoid to send lots of requests for an image he already has.
In php:
$path = 'myfolder/myimage.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
(taken from) How to convert an image to base64 encoding?
I am trying to limit the upload file size to 1MB using the following jQuery code :
<td><label> Upload image </label>
<input type="file" class="upload" name="image" value="<?php echo set_value('image'); ?>" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).on('change','.upload',function(){
files = this.files;
size = files[0].size;
//max size 50kb => 50*1000
if( size > 1000141) {
alert('Please upload less than 1mb file');
return false;
}
return true;
});
</script>
When I upload a file greater than 1MB, it displays the error message but the upload goes through successfully. What's causing this?
You can use a hidden field to set the max size.
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
The field must be before the input type=file.
But be careful its easy to bypass the MAX_FILE_SIZE.
You should also check the file size with php.
$size= $_FILES["myfile"]["size"];
if($size > 1000141)
{
//dont upload file
}
else {
//upload file
}
So I'm trying to set up an image upload from a form via php on my localhost and after running the code and connecting to the database okay, I'm getting the error for the upload. Since all of the other parts of the form are working after a section by section check, I'll just add the html for the upload input and its relevant php script.
<input type="file" name="image" id="image-select" />
And the portion of the php that has to deal with the image upload and verification after upload:
$image = $_FILES ['image']['name'];
$type = #getimagesize ($_FILES ['image']['tmp_name']);
//Never assume image will upload okay
if ($_FILES['image']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['image']['error']);
}
//Where the file will be placed
$target_path = "uploads/";
// Add the original filename to target path
$path= $target_path . basename($image);
// Check if the image is invalid before continuing
if($type === FALSE || !($type[2] === IMAGETYPE_TIFF || $type[2] === IMAGETYPE_JPEG || $type[2] === IMAGETYPE_PNG)) {
echo '<script "text/javascript">alert("This is not a valid image file!")</script>';
die("This is not a valid image file!");
} else {
move_uploaded_file($_FILES['image']['tmp_name'], $path);
}
So error appears once the code hits the upload process. I was attempting to upload a small PNG file The relevant code I added is also in their respective orders when they appear in the script.
can you please put error here. If error means that after submit page file is not being upload. then please check your form enctype. see below an example
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="image" id="image-select" />
<input type="submit" value="Submit">
</form>
Just a wild stab in the dark here as you haven't provided your form tag but you have remembered the enctype attribute haven't you?
Sorry I don't have 50 reputation otherwise I would ask this as a comment.
<form enctype='multipart/form-data' action=''>
<input type="file" name="image" id="image-select" />
</form>
Also you should check if the file uploaded OK before calling getimagesize() (not that this would be the source of your issue)
if you are using PHP5 and Imagick, then you can try to use something like the following:
$image->readImageFile($f);
I am using the following loop to send/attach multiple attachments to my email message.
foreach(array_keys($_FILES['attachment']['name']) as $key) {
$source = $_FILES['attachment']['tmp_name'][$key];
$filename = $_FILES['attachment']['name'][$key]; // original filename from the client
$mail->AddAttachment($source, $filename);
}
But only the first attachment i made is sended.
The form code is
<form method="POST" action="<?php $PHP_SELF ?>" enctype="multipart/form-data">
<input type="file" name="attachment[]" id="attachment" size="30"
onchange="document.getElementById('moreUploadsLink').style.display = 'block';" />
<div id="moreUploads"></div>
<div id="moreUploadsLink" style="display:none;">
Attach another File</div>
<input name="submit" type="submit" value="submit" />
</form>
When one click on Attach another file, another File Upload button is shown, through a JavaScript function:
<script type="text/javascript">
var upload_number = 1;
var attachmentlimit = 5;
function addFileInput() {
var d = document.createElement("div");
var file = document.createElement("input");
file.setAttribute("type", "file");
file.setAttribute("name", "attachment"+upload_number);
d.appendChild(file);
document.getElementById("moreUploads").appendChild(d);
upload_number++;
if(upload_number == attachmentlimit) {
document.getElementById('moreUploadsLink').style.display='none';
}
}
</script>
Only the file attached through the first FileUpload Button is attached and sended, not the others.
Help.
The problem is that you are setting the name attribute of your new input element to attachment1, attachment2, etc. You should be setting this name to attachment[], just like the original input you created.
If you still don't get all your attachments, you can try a var_dump($_FILES) in your PHP script to ensure that you are getting all the files the way you expect them.
Below is my code where the user can upload a file. What I want to know is that is there a way so that via server side is there a way to first of all restrict the file formats of the files to jpeg and png only and then when the user clicks on the submit button, if the file format is correct then display an alert on the same page stating "File is correct" else display an alert stating "File is incorrect".
Can somebody please provide coding if they know how to do this. Thank you and any help will be much appreciated :)
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
A code for a total check of file uploads, you'll have to change $allowedtypes though. (Copied instead of linking because it was from a non-English site)
<?php
if(isset($_POST["submit"])){
$allowedtypes=array("jpg"=>true,"png"=>true,"gif"=>true,"txt"=>true);
$filename = $_FILES['file1']['name'];
$source = $_FILES['file1']['tmp_name'];
$file_size=$_FILES['file1']['size'];
$saveloc = "uploads/" . $filename;
$maxfilesize=1024*1024*10;
$nameext=explode(".",$filename);
if(preg_match('/^[A-Za-z0-9\-\_]{1,}\.[a-zA-Z0-9]{0,4}$/',$filename)){
if(!empty($allowedtypes[strtolower($nameext[1])]) && $allowedtypes[strtolower($nameext[1])]===true){
if($file_size<=$maxfilesize){
if(!file_exists($saveloc)){
if(move_uploaded_file($source, $saveloc)) {
chmod($saveloc,644);
echo "Successful upload. <a href='".$saveloc."'>Fájl megtekintése</a>";
}
else echo "Cannot move";
}
else echo "Existing file";
}
else echo "Too big file";
}
else echo "Not allowed extension";
}
else echo "Only alphanumeric files allowed";
}
else echo "<form method='post' enctype='multipart/form-data' action='secureupload.php'> File: <input type='file' name='file1' /><br /><input
name='MAX_FILE_SIZE' type='hidden' value='10485760' /> <input type='submit' value='Upload' name='submit' /></form>";
?>
You are talking about server side handler and write 'alert'...khm...
If u want to do stuff via server-side, then use php handler
http://php.net/manual/en/features.file-upload.post-method.php
If u want to do stuff via client-side, use javascript events, e.g on change event
<script>
function check() {
var file = document.getElementById('file').value;
var temp = file.split(/\.+/).pop();
alert(temp);
}
</script>
<input type="file" name="file" id="file" onchange="check();" />
You have file extension in temp var.
There are PHP functions to do this. You want to look at mime_content_type and finfo_file. These are built-in PHP commands that allow you to interpret that actual file type of a file being uploaded. You can then filter the mime types to only .gif/.jpg/etc. You want to check the mime types over the file name because the file name can be changed to mask the actual file type. If you want code samples, there are plenty on those pages as well as some excellent user-provided alternatives.
Something like this at the top of your file should work:
<?php
foreach ($_FILES as $file)
{
$tmp = explode(".", $file["tmp_name"]);
if (!in_array($tmp[count($tmp)-1], array("jpeg", "png"), true))
die("<script>alert('File is incorrect');</script>");
}
echo "<script>alert('File is correct');</script>";
?>