I am trying to make a script that allows users to change their profile picture for a website that I am making. Here is the HTML code for the form:
<form action="upload_prof_pic.php" method="POST" enctype="multipart/form-data">
<input type="file" class="btn btn-default" name="file" id="file" /><br /><br />
<input type="submit" class="btn btn-default" value="Upload Profile Picture" />
</form>
Here is the PHP code for upload_prof_pic.php:
<?php
session_start();
require("includes/connect.php");
$results = $db->query("SELECT * FROM users WHERE username='".$_SESSION["logged_in"]."'");
$rows = $results->fetch();
$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"] < 20000)
&& in_array($extension, $allowedExts)
) {
if ($_FILES["file"]["error"] > 0) {
//error: uploading
header("Location: account.php?err=upload");
} else {
//success
move_uploaded_file($_FILES["file"]["tmp_name"],
"prof_pic/users/".$rows["username"]."/" . $_FILES["file"]["name"]);
$db->query("UPDATE users SET prof_pic='".$_FILES['file']['name']."' WHERE username='".$_SESSION["logged_in"]."'");
header("Location: account.php");
}
} else {
//error: invalid file
header("Location: account.php?err=invalid");
}
?>
It always runs the '//error: invalid file' part of the script. Can anyone help? It worked once, then I changed something in the '//success' part. This shouldn't have had any effect, but apparently it did.
i got that same error so i used following javascript coding.
<script type="text/javascript" src="js/jquery-func.js"></script>
<SCRIPT type="text/javascript">
function ValidateFileUpload() {
var fuData = document.getElementById('filename');
var FileUploadPath = fuData.value;
//To check if user upload any file
if (FileUploadPath == '') {
alert("Please upload an image");
} else {
var Extension = FileUploadPath.substring(
FileUploadPath.lastIndexOf('.') + 1).toLowerCase();
//The file uploaded is an image
if (Extension == "gif" || Extension == "png" || Extension == "bmp"
|| Extension == "jpeg" || Extension == "jpg")
{
<?php
move_uploaded_file($_FILES["file"]["tmp_name"],
"prof_pic/users/".$rows["username"]."/" . $_FILES["file"]["name"]);
$db->query("UPDATE users SET prof_pic='".$_FILES['file']['name']."' WHERE username='".$_SESSION["logged_in"]."'");
header("Location: account.php");
?>
}
//The file upload is NOT an image
else {
alert("Photo only allows file types of GIF, PNG, JPG, JPEG and BMP. ");
}
}
}
html part
<input onchange="ValidateFileUpload(this);" type="file" name="file" id="filename"/>
Related
I've looked around and have struggled to find out how to upload multiple images (.jpg/.png/etc).
For my task I was looking to upload 5 pictures to the database record. So far I'm struggling to even upload 5 together in one record. I've used PHP from the Ws3 website and it works successfully but this code is for one image alone.
PHP Code -
$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/png"))
&& ($_FILES["file"]["size"] < 2000000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . uniqid() . "_" . $_FILES["file"]["name"]);
}
}
}
else
{
$error = "Invalid file";
}
My HTML is as follows,
<label for="file">Filename:</label>
<input type="file" name="file" id="file">
<input type="file" name="file" id="file">
<input type="file" name="file" id="file">
<input type="file" name="file" id="file">
<input type="file" name="file" id="file">
Any advice is greatly appreciated guys! Cheers
First, add enctype="multipart/form-data" to your form. Then change the names of the file fields to:
<input type="file" name="file[]" id="file" >
<input type="file" name="file[]" id="file" >
<input type="file" name="file[]" id="file" >
This will create an array of the files submitted. Now you'll be able to do a foreach on the files. Quick example:
foreach ($_FILES['file']['name'] as $f => $name) {
}
Around your existing code, then add [$f] to every $_FILES["file"] variable. So $_FILES["file"]["size"] has to be changed to $_FILES["file"]["size"][$f] and so on. In the foreach I referring $name to $_FILES["file"]["name"][$f], so you can use $name instead.
Full php code based on your script:
foreach ($_FILES['file']['name'] as $f => $name) {
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $name);
$extension = end($temp);
if ((($_FILES["file"]["type"][$f] == "image/gif")
|| ($_FILES["file"]["type"][$f] == "image/jpeg")
|| ($_FILES["file"]["type"][$f] == "image/jpg")
|| ($_FILES["file"]["type"][$f] == "image/png"))
&& ($_FILES["file"]["size"][$f] < 2000000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"][$f] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"][$f] . "<br>";
}
else
{
if (file_exists("upload/" . $name))
{
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"][$f], "upload/" . uniqid() . "_" . $name);
}
}
}
else
{
$error = "Invalid file";
}
}
At the end, I would suggest you to go learn more about PHP on different sites. W3schools is easy, but also not your best option. As an example, you are checking this:
if ((($_FILES["file"]["type"][$f] == "image/gif")
|| ($_FILES["file"]["type"][$f] == "image/jpeg")
|| ($_FILES["file"]["type"][$f] == "image/jpg")
|| ($_FILES["file"]["type"][$f] == "image/png"))
&& ($_FILES["file"]["size"][$f] < 2000000)
&& in_array($extension, $allowedExts))
But only the array will be enough, like this:
if ($_FILES["file"]["size"][$f] < 2000000 && in_array($extension, $allowedExts))
$_FILES["file"]["type"] not always returns the type as expected.. We see it many times in audio and video files. Another post on SO about MIME types referring to the W3schools script: PHP: $_FILES["file"]["type"] is useless
Before asking new questions on StackOverflow, please do a search. I just wrote a long answer just for you, but the same thing has been done MANY times for this kind of question already. https://stackoverflow.com/search?q=multiple+upload+php
Hope it answers your question, and good luck learning PHP.
I think the problem is in your HTML... instead of five of these:
<input type="file" name="file" id="file">
Try doing it like this:
<input type="file" name="file[]">
That will submit an array of files, rather than trying to submit multiple files under the same input name.
As a side note, you shouldn't use the same id attribute on more than one element. Perhaps you meant to use a class?
if (isset($_POST["kirim"])) {
$jumlah = count($_FILES['gambar']['size']); // cari jml gambar
$size = $_FILES['gambar']['size']; //cek ukuran file
$ext = $_FILES['gambar']['type']; // cek extensi file
$max_size = 1000000;
$htg = implode(" ",$size);
if ($htg < 1){
echo "<script>alert('pilih file yang akan di upload !');
location.href='index.php';</script>";
}
elseif(max($size) > $max_size){
echo "<script>alert('ukuran file terlalu besar');
location.href='index.php';</script>";
}elseif (in_array("application/octet-stream", $ext) || in_array("application/pdf",$ext) || in_array("text/plain", $ext)) {
echo "<script>alert('file harus jpg atau png semua !');
location.href='index.php';</script>";
}else{
for ($i=0; $i < $jumlah; $i++) {
$file_name = $_FILES['gambar']['name'][$i];
$tmp_name = $_FILES['gambar']['tmp_name'][$i];
move_uploaded_file($tmp_name, "uploads/".$file_name);
mysqli_query($conn,"INSERT INTO images VALUES
('','$file_name','$tmp_name')");
}
echo "<script>alert('Upload Berhasil');location.href='index.php';</script>";
}
}
why resubmit after refresh php page?
try it, go to: http://qass.im/message-envelope/
and upload any image
now try click F5, after refresh page "resubmit"
Why?
I don't want resubmit after refresh page
What is the solution?
See this is my form code:
<form id="uploadedfile" name="uploadedfile" enctype="multipart/form-data" action="upload.php" method="POST">
<input name="uploadedfile" type="file" />
<input type="submit" value="upload" />
</form>
See this is php code upload.php file:
<?php
$allowedExts = array("gif", "jpeg", "jpg", "png", "zip", "pdf", "docx", "rar", "txt", "doc");
$temp = explode(".", $_FILES["uploadedfile"]["name"]);
$extension = end($temp);
$newname = $extension.'_'.substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 7)), 4, 7);
$imglink = 'attachment/attachment_file_';
$uploaded = $imglink .$newname.'.'.$extension;
if ((($_FILES["uploadedfile"]["type"] == "image/jpeg")
|| ($_FILES["uploadedfile"]["type"] == "image/jpeg")
|| ($_FILES["uploadedfile"]["type"] == "image/jpg")
|| ($_FILES["uploadedfile"]["type"] == "image/pjpeg")
|| ($_FILES["uploadedfile"]["type"] == "image/x-png")
|| ($_FILES["uploadedfile"]["type"] == "image/gif")
|| ($_FILES["uploadedfile"]["type"] == "image/png")
|| ($_FILES["uploadedfile"]["type"] == "application/msword")
|| ($_FILES["uploadedfile"]["type"] == "text/plain")
|| ($_FILES["uploadedfile"]["type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
|| ($_FILES["uploadedfile"]["type"] == "application/pdf")
|| ($_FILES["uploadedfile"]["type"] == "application/x-rar-compressed")
|| ($_FILES["uploadedfile"]["type"] == "application/x-zip-compressed")
|| ($_FILES["uploadedfile"]["type"] == "application/zip")
|| ($_FILES["uploadedfile"]["type"] == "multipart/x-zip")
|| ($_FILES["uploadedfile"]["type"] == "application/x-compressed")
|| ($_FILES["uploadedfile"]["type"] == "application/octet-stream"))
&& ($_FILES["uploadedfile"]["size"] < 5242880) // Max size is 5MB
&& in_array($extension, $allowedExts))
{
move_uploaded_file($_FILES["uploadedfile"]["tmp_name"],
$uploaded );
echo '<a target="_blank" href="'.$uploaded.'">click</a>'; // If has been uploaded file
echo '<h3>'.$uploaded.'</h3>';
}
if($_FILES["uploadedfile"]["error"] > 0){
echo '<h3>Please choose file to upload it!</h3>'; // If you don't choose file
}
elseif(!in_array($extension, $allowedExts)){
echo '<h3>This extension is not allowed!</h3>'; // If you choose file not allowed
}
elseif($_FILES["uploadedfile"]["size"] > 5242880){
echo "Big size!"; // If you choose big file
}
?>
if you have solution, please edit my php code and paste your solution code!
I've had several upload forms working before, however, even after almost copying my previous code this on doesn't seem to work, I prefer doing it all in one php script file and so it is all generated in this single file.
My form:
<form action="" method="post" enctype="multipart/form-data">
<ul>
<li>
<label for="file">File : </label>
<input type="file" id="file" name="file" required="required" />
</li>
<li>
<input type="submit" value="Upload" />
</li>
</ul>
</form>
My php upload:
if(!empty($_POST['file']))
{
echo "Found.";
$exts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$ext = 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"] < 20000)
&& in_array($ext, $exts))
{
if($_FILES["file"]["error"] > 0)
{
$result = "Error Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
$scandir = scandir("/images/news/");
$newname = (count($scandir-2)) . $ext;
move_uploaded_file($_FILES["file"]["tmp_name"],"/images/news/" . $newname);
$ulink = "/images/news/" . $newname;
$result = "Success, please copy your link below";
}
}
else
{
$result = "Error.";
}
}
When I upload a .png image, the page simply seems to refresh, I've placed the echo "Found."; in there to check if it even has anything in $_POST["file"] but it doesn't seem to have anything.
I don't understand why the page isn't submitting correctly. I've changed action="" to action="upload.php" to make sure it points to the same page but still nothing.
Use $_FILES['file'] instead of $_POST['file'].
Read more about $_FILES at http://www.php.net/manual/en/features.file-upload.post-method.php
replace $_POST['file'] by $_FILES['file'] and set action="".
Try this.... because $_POST not work with files, for files we use $_FILES..
if(!empty($_FILES['file']))
{
echo "Found.";
$exts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$ext = 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"] < 20000)
&& in_array($ext, $exts))
{
if($_FILES["file"]["error"] > 0)
{
$result = "Error Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
$scandir = scandir("/images/news/");
$newname = (count($scandir-2)) . $ext;
move_uploaded_file($_FILES["file"]["tmp_name"],"/images/news/" . $newname);
$ulink = "/images/news/" . $newname;
$result = "Success, please copy your link below";
}
}
else
{
$result = "Error.";
}
}
I wouldn't just check the $_FILES variable. I would name the submit input and check if the submit input was submitted. This way you can check if the button was pressed with no files selected and prompt the user as such.
Like So:
<form action="" method="post" enctype="multipart/form-data">
<ul>
<li>
<label for="file">File : </label>
<input type="file" id="file" name="file" required="required" />
</li>
<li>
<input type="submit" value="Upload" name="upload"/>
</li>
</ul>
</form>
Then you can check the post variable for that value.
Like So:
if(!empty($_POST['upload']))
{
echo "Found.";
$exts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$ext = 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"] < 20000)
&& in_array($ext, $exts))
{
if($_FILES["file"]["error"] > 0)
{
$result = "Error Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
$scandir = scandir("/images/news/");
$newname = (count($scandir-2)) . $ext;
move_uploaded_file($_FILES["file"]["tmp_name"],"/images/news/" . $newname);
$ulink = "/images/news/" . $newname;
$result = "Success, please copy your link below";
}
}
else
{
$result = "Error.";
}
}
OK so I want to be able to upload a image to my webserver via PHP for the admin control panel.
Now, I want to be able to upload the image by using a file uploader, and use a textbox for the filename the image will be called. Cheers :D
use a standard form in html
<form enctype="multipart/form-data" action="uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Filename: <input name="name" type="text" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
then the uploader.php file:
//get the data from the form
$target_path = "uploads/";
$name= $_POST['name'];
$target_path = $target_path . $name;
//this is the script which uploads the file
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded as" . $name;
} else{
echo "There was an error uploading the file, please try again!";
}
you might want to check the file is an image .. to do so:
$max_size=20000; //in kb
$allowedExts = array("gif", "jpeg", "jpg", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
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"] < $max_size)
&& in_array($extension, $allowedExts))
{
//here goes the script to upload the file!!
}else{
echo"The file is not supported";}
I have two files iframe.php, iframe.html. iframe.php contains a file's uploading form which i want to display in iframe.html as an iframe (only for IE < 10 otherwise i can upload using ajax without any problems).
it's working fine in IE.10, but in IE.9 i need to click twice on the submit button to upload, where in IE.8 it doesn't work at all and the $output always return Error: invalid file and also need to be clicked twice, i'm not sure what the problem is! any help would be great.
iframe.php
<div id="uploadImage">
<form method='POST' enctype='multipart/form-data' action='<?php echo $_SERVER['PHP_SELF'] ?>'>
<input type="text" disabled placeholder="Choose an Image to upload" id="file_input" name="file_input" />
<input type="button" id="file_btn" value="" onClick="document.getElementById('file').click()" />
<input type="submit" id="upload" value="" />
<div style="width: 0; height: 0; overflow: hidden;">
<input type="file" id="file" name="file" />
</div>
</form>
<div id="properties" class="texxt">
<p>Name: <br/>
Size: max 2 MB or 2000 KB<br/>
Type: (jpg, jpeg, png, gif)
</p>
</div>
<div id="results">
<?php
$status = "Close";
$source = "";
if( isset($_FILES['file']))
{
$allowedExts = array("gif", "jpeg", "jpg", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
$size = (int) $_SERVER['CONTENT_LENGTH'];
if ( (($_FILES["file"]["type"] == "image/gif") ||
($_FILES["file"]["type"] == "image/jpeg") ||
($_FILES["file"]["type"] == "image/jpg") ||
($_FILES["file"]["type"] == "image/png")) &&
in_array($extension, $allowedExts) &&
($size < (2 * 1024 * 1024)) )
{
if ($_FILES["file"]["error"] > 0)
{
$output = "Return Code: " . $_FILES["file"]["error"];
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
$output = "Error: File already exists. Please rename your file or chose a different one";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
$status = "Add Image";
$output = "Uploaded Successfully";
$source = sprintf(" !img! %s !*img! ", $_FILES["file"]["name"]);
}
}
}
else
{
if (!in_array($extension, $allowedExts))
{
$output = "Error: Please select an image.";
}
elseif ( ($size > (2 * 1024 * 1024)) && in_array($extension, $allowedExts) )
{
$output = "Error: File size(" . $size . ") exceeds the limit of 2 mb.";
}
else
{
$output = "Error: Invalid file";
}
}
echo $output;
}
?>
</div>
<p align="center">
<input type="hidden" name="source" id="source" class="source" value="<?php echo $source ?>" />
<input type="button" id="close" class="close" value="<?php echo $status ?>" />
</p>
</div>
<script>
document.getElementById('file').onchange = function(){
var path = this.value.replace(/C:\\fakepath\\/, ''),
props = document.getElementById('properties');
props.innerHTML = props.innerHTML.replace('Name: ', 'Name: ' + path);
document.getElementById('file_input').value = path;
document.getElementById('results').innerHTML = "";
};
</script>
iframe.html
<div id="iframe" style="height: 296px; width: 481px">
</div>
<script>
var iframe = document.createElement('iframe');
iframe.src = "iframe.php";
iframe.frameBorder = "no";
iframe.allowTransparency = "true";
document.getElementById('iframe').appendChild(iframe);
</script>
IE doesn't allow manipulation of the type="file" input element from javascript due to security reasons. Setting the filename or invoking a click event to show the browser dialog will result in an "Access is denied" error on the form submit, user has to click on the file input manually.
as for the invalid file error in IE.8, the proplem is with the $_FILES['file']['type'], i had this problem myself before. when using var_dump($_FILES['file']['type']) you can see that it shows file types as following:
jpeg -> pjpeg
jpg -> pjpeg
png -> x-png
gif -> gif
to fix the problem add x-png and pjpeg to the allowed file types:
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/png") ||
($_FILES["file"]["type"] == "image/x-png")) &&
in_array($extension, $allowedExts) &&
($size < (2 * 1024 * 1024)) )
{