I have a weird problem, I have a php upload code that I have implemented long ago, today I try to reuse it but it didn't work, the surprise was big when I started my Windows on VirtualBox and the exact same file that I was unable to upload from linux was uploaded for windows. I mean, the only thing that changes is the OS of client machine. Any way, I think is related to the file type restriction, because if I take out these restrictions I can upload the file from my ubuntu....
Codes are next:
form.php file:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input name="file" type="file" size="50" /><br>
<p><input name="upload" type="submit" value="upload" />
<input name="action" type="hidden" value="upload" /></p></form>
upload.php file:
<?php
$status = "";
if ($_POST["action"] == "upload") {
// data from file
$size = $_FILES["file"]['size'];
$type = $_FILES["file"]['type'];
$file = $_FILES["file"]['name'];
$pos = strpos($file, "_timetable.csv");
if ($file != "") {
if ($type == "text/csv" || $type == "application/vnd.ms-excel") {
if ($pos == false) {
$status = "Error: only files with extension <b>_timetable.csv</b> are allowed
<p><form action=\"form.php\"><input type=\"submit\" value=\" Select a different file \"></p>";
}else {
$destination = "filess/".$fitxer;
if (copy($_FILES['file']['tmp_name'],$destination)) {
$status = "<p>Uploaded: ".$file."</p>
}
else {
$status = "Error when uploading file<p><form action=\"form.php\"><input type=\"submit\"
value=\" Try again \"></p>";
}
}} else {
$status = "Error: only files with extension <b>_timetable.csv</b> are allowed
<p><form action=\"form.php\"><input type=\"submit\" value=\" Select a different file \"></p>";
}
} else {
$status = "Error when uploading file<p><form action=\"form.php\"><input type=\"submit\"
value=\" Try again \"></p>";
}
}
echo $status;
?>
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>";
}
}
Hi I'm new to php and keep getting this error: "Warning: Invalid argument supplied for foreach() in /home/site/folder/upload.php on line 61."
I'm trying to build a form in which users can upload one or more photos automatically to a directory to then be displayed else where.
Whenever I use this form I created it functions properly on my website but unfortunately it keeps printing that error out and would like it to go away. Here is my code I'm working with:
<div>
<form action="upload.php" enctype="multipart/form-data" method="POST">
<input type="file" name="images[]" multiple="multiple"/>
<input type="submit" name="submit" value="upload images"/>
<form/>
<?php
// check if uploads directory exists
$dir = "images/";
if(!is_dir($dir))
{
echo "Directory not found, let's create the folder.";
mkdir($dir,"0777", true);
}
$countimg = 0;
$allimg = 0;
foreach($_FILES["images"]["name"] as $k=>$name)
{
$allimg++;
$imgname = $_FILES["images"]["name"][$k];
$sizeimg = $_FILES["images"]["size"][$k];
$tmpname = $_FILES["images"]["tmp_name"][$k];
//2.
$extension = strtolower(pathinfo($dir.$imgname, PATHINFO_EXTENSION));
if($extension=='png' || $extension=='jpg' ||$extension=='jpeg' ||$extension=='gif')
{
if($sizeimg < 2097152){
if(!file_exists($dir.$imgname)){
//1.
if(move_uploaded_file($tmpname,$dir.$imgname))
{
$countimg++;
}
}
}
}
}
echo "You are trying to upload $allimg images".'<br>';
echo "From $allimg image(s) - $countimg was/were uploaded with success".'<br>';
$z = $allimg - $countimg;
echo "$z image(s) were not uploaded: Not an image, over 2MB, or already uploaded.";
?>
</div>
Try
if (count($_FILES)) {
foreach($_FILES["images"]["name"] as $k=>$name) {
....
}
}
I tested your script, it works fine. The error message appears because you are not checking that a file got uploaded before starting the foreach. If I land on the page, the PHP code will still be triggered. To fix this, you may use the below:
<div>
<form action="upload.php" enctype="multipart/form-data" method="POST">
<input type="file" name="images[]" multiple="multiple"/>
<input type="submit" name="submit" value="upload images"/>
<form/>
<?php
if( $_POST['submit'] ) {
$dir = "images/";
if(!is_dir($dir))
{
echo "Directory not found, let's create the folder.";
mkdir($dir,"0777", true);
}
$countimg = 0;
$allimg = 0;
foreach($_FILES["images"]["name"] as $k=>$name)
{
$allimg++;
$imgname = $_FILES["images"]["name"][$k];
$sizeimg = $_FILES["images"]["size"][$k];
$tmpname = $_FILES["images"]["tmp_name"][$k];
//2.
$extension = strtolower(pathinfo($dir.$imgname, PATHINFO_EXTENSION));
if($extension=='png' || $extension=='jpg' ||$extension=='jpeg' ||$extension=='gif')
{
if($sizeimg < 2097152){
if(!file_exists($dir.$imgname)){
//1.
if(move_uploaded_file($tmpname,$dir.$imgname))
{
$countimg++;
}
}
}
}
}
echo "You are trying to upload $allimg images".'<br>';
echo "From $allimg image(s) - $countimg was/were uploaded with success".'<br>';
$z = $allimg - $countimg;
echo "$z image(s) were not uploaded: Not an image, over 2MB, or already uploaded.";
}
?>
</div>
if( $_POST['submit'] ) will ensure that the form is submitted prior to running the rest of the PHP code.
I'm doing php upload multiple files and rename them. So I use array input field name and use for loop to rename each file into date + ordinal number suffix.
I do validate the file type too, It can prevent upload other file-type to directory successfully. But it still insert filename to database. what's wrong with my code?
<form action="upload.php" method="post" enctype="multipart/form-data">
Username :
<input type="text" name="username" />
Image 1 :
<input type="file" name="images[]" />
<br>
image 2 :
<input type="file" name="images[]" />
</form>
in upload.php page
if(isset($_POST['submit']))
{
$count=count($_FILES["images"]["name"]);
$arr_newname = array();
for($i=1; $i <= $count; $i++)
{
if ((($_FILES["images"]["type"][$i-1] == "image/gif")
|| ($_FILES["images"]["type"][$i-1] == "image/jpeg")
|| ($_FILES["images"]["type"][$i-1] == "image/png"))
&& ($_FILES["images"]["size"][$i-1] < 2000000)) //2 MB
{
if ($_FILES["images"]["error"][$i-1] > 0)
{
echo "File Error : " . $_FILES["images"]["error"][$i] . "<br />";
}
else
{
if (file_exists("path/to/".$_FILES["images"]["name"][$i-1] ))
{
echo "<b>".$_FILES["images"]["name"][$i-1] . " already exists. </b>";
}
else
{
$newname = date('Y-m-d')."_".$i.".jpg";
$arr_newname[$i-1] = $newname;
move_uploaded_file($_FILES["images"]["tmp_name"][$i-1] , "path/to/".$newname);
$data = array(
'username' => $_POST['username'],
'my_pic'.$i => $arr_newname[$i-1],
);
$this->db->insert('oav_album', $data);
}
}
}
else
{
echo "Invalid file" ;
exit();
}
}
}
I want to upload video files in php for that i am using following code
PHP
$newUploadDir = "c://video";
$idx = "file";
if (isset($_FILES[$idx]) && is_array($_FILES[$idx])) {
echo "file set";
foreach ($_FILES[$idx]["error"] as $key => $error) {
echo "loop";
if ($error == UPLOAD_ERR_OK) {
echo "<br/>dd2";
$tmp_name = $_FILES[$idx]["tmp_name"][$key];
$name = $_FILES[$idx]["name"][$key];
$ext1 = explode(".", $name);
$extension = end($ext1);
$newfilename = "test".".".$extension;
$video_types = array('mp4', 'avi','webm');
if (in_array($extension, $video_types)) {
if (move_uploaded_file($tmp_name, $newUploadDir.$newfilename)) {
echo "uploaded to folder";
} else {
echo "Not uploaded to folder";
}
}
} else {
echo "not uploaded $error";
}
}
}
echo "ok";
HTML
<form action="http://localhost/fileupload/video.php" enctype="multipart/form-data" method="post">
<input id="file1" name="file[]" type="file"/>
<input name="userId" type="text" value="2"/>
<input id="Submit" name="submit" type="submit" value="Submit" />
</form>
Output
file setloopnot uploaded 1ok
Video file is not uploading. How to resolve this?
Actually, if you try to upload very large (video) files, probably the upload file size limit will not let you do that. Instead of regular file upload, there are other possibities. For the begining, look at this, this or this.
An other aproach would be to use third party services like Amazon S3, Microsoft Azure, etc.
Here is my file-upload script, and i am getting the following error
Notice: Undefined index: fupload in C:\Users\Tuskar\Desktop\Projekt\htdocs\Project IT-Space\Profile\edit_profile_parse.php on line 8
But according there should not error, because i identified the index. It seems i don't have access to the $_FILES array, because before i got this error ive been getting other similar errors or the programm completely passes the if and goes directly to the else (file not chosen)
I know the script is primitive and includes almost no security, but i just want it to work first before i add other features like max file size or file restriction ... :(
Here is the code i am using.
Upload Picture
<form action="edit_profile_parse.php" method="get" enctype="multipart/form-data" >
<input type="hidden" name="MAX_FILE_SIZE" value="999999999"> </input>
<input type="file" name="fupload"> </input>
<input type="submit" name="submit" value="Upload"> </input>
</form>
Here is the php that handles the form
if (isset( $_GET['submit'] ))
{
if (isset($_FILES['fupload'] ))
{
echo "name: ".$_FILES['fupload']['name']." <br> ";
echo "size: ".$_FILES['fupload']['sizw']." <br> ";
echo "type: ".$_FILES['fupload']['type']." <br> ";
if ($_FILES['fupload']['type'] == "image/gif")
{
$source = $_FILES['fupload']['tmp_name'];
$target = "images/" .$_FILES['fupload']['name'];
move_uploaded_file($source, $target) or die ("Error: " .mysql_error());
$size = getImageSize($target);
$imgstr = "<img src=\" '".$target."' \">";
echo $imgstr;
}
else
{
echo "Problem uploading the file ... ";
}
}
else
{
echo "No file chosen !! ";
}
}
else
{
echo "Button not clicked ";
}
You should use form method to POST instead of get.
<form action="edit_profile_parse.php" method="post" enctype="multipart/form-data" >
Make sure your FORM tag has method="POST". GET requests do not support multipart/form-data uploads.
I hope this works:
the form:
<form action="edit_profile_parse.php" method="post" enctype="multipart/form-data" >
<input type="hidden" name="MAX_FILE_SIZE" value="999999999"> </input>
<input type="file" name="fupload"> </input>
<input type="submit" name="submit" value="Upload"> </input>
</form>
the php file:
<?php
if($_POST) {
$max_size = mysql_real_escape_string(strip_tags($_POST['MAX_FILE_SIZE']));
$file = $_FILES['fupload']['name'];
if(isset($max_size) && !empty($max_size) && !empty($file)) {
$file_type = $_FILES['fupload']['type'];
$tmp = $_FILES['fupload']['tmp_name'];
$file_size = $_FILES['fupload']['size'];
$allowed_type = array('image/png', 'image/jpg', 'image/jpeg', 'image/gif');
if(in_array($file_type, $allowed_type)) {
if($file_size < $max_size) {
$path = 'images/'.$file;
move_uploaded_file($tmp, $path);
//if you want to store the file in a db use the $path in the query
} else {
echo 'File size: '.$file_size.' is too big';
}
} else {
echo 'File type: '.$file_type.' is not allowed';
}
} else {
echo 'There are empty fields';
}
}
?>
Upload Picture
<form action="edit_profile_parse.php" method="POST" enctype="multipart/form-data" >
<input type="hidden" name="MAX_FILE_SIZE" value="999999999"> </input>
<input type="file" name="fupload"> </input>
<input type="submit" name="submit" value="Upload"> </input>
</form>
PHP file
<?php
if (isset( $_POST['submit'] ))
{
if (isset($_FILES['fupload'] ))
{
echo "name: ".$_FILES['fupload']['name']." <br> ";
echo "size: ".$_FILES['fupload']['size']." <br> ";
echo "type: ".$_FILES['fupload']['type']." <br> ";
if ($_FILES['fupload']['type'] == "image/gif")
{
$source = $_FILES['fupload']['tmp_name'];
$target = "images/" .$_FILES['fupload']['name'];
move_uploaded_file($source, $target) or die ("Error: " .mysql_error());
$size = getImageSize($target);
$imgstr = "<img src=\" '".$target."' \">";
echo $imgstr;
}
else
{
echo "Problem uploading the file ... ";
}
}
else
{
echo "No file chosen !! ";
}
}
else
{
echo "Button not clicked ";
}
?>