I'm writing a fairly simple fileserver and was doing well with uploading a single file, moving it to a folder on the server and keeping info about it in a database. Now when I tried modifying it to accept multiple files from a single input field, I can't get it to progress past the first test for errors.
This is my index.php here:
<body>
<img src="style/images/sitename.gif" alt="sitename" align="absmiddle" class="displayed" />
<div id="sidediv">
<ul>
<li>Multiple files uploaded at once will return a link to a zip archive of those files.
</ul>
</div><!--close the sidediv-->
<div id="container">
<div id="content">
<!--form starts here-->
<form action="upload.php" id="group" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="startUpload();" >
<p id="f1_upload_process">Loading...<br/><img src="loader.gif" /><br/></p>
<p id="f1_upload_form" align="center"><br/>
<label>File:
<input name="myfile[]" type="file" size="30" multiple="multiple" />
</label>
<label>
<input type="submit" name="submitBtn" class="sbtn" value="Upload" multiple="multiple" />
</label>
</p>
<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>
<!--form ends here-->
</div>
<!--<div id="footer">sitename</div>-->
</div>
<div id="link"></div>
</body>
And my upload.php here:
<?php
//database
$username="";
$password="";
$database="";
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$message = array();
$result = array();
$fileName = array();
$ext = array();
$tmpName = array();
$path = array();
$target_path = array();
$count = count($_FILES['myfile']['name']);
for($i=0;$i<$count;$i++)
{
//file info
$fileName[$count] = $_FILES['myfile']['name'][$count]; // Get the name of the file (including file extension).
$ext[$count] = pathinfo($fileName[$count], PATHINFO_EXTENSION); // Get the extension from the filename.
$tmpName[$count] = $_FILES['myfile']['tmp_name'][$count];
$fileSize[$count] = $_FILES['myfile']['size'][$count];
$fileType[$count] = $_FILES['myfile']['type'][$count];
//file info
/* $fileName = $myfile['name']; // Get the name of the file (including file extension).
$ext = pathinfo($fileName, PATHINFO_EXTENSION); // Get the extension from the filename.
$tmpName = $myfile['tmp_name'];
$fileSize = $myfile['size'];
$fileType = $myfile['type'];*/
// Edit upload location here
$destination_path = './files/';
$allowed_filetypes = array('idx','sub','txt','srt');
$max_filesize = 5242880; //bytes
$prefix = substr(md5(time()),0,7); //new name of the file
$target_path[$count] = $destination_path . $prefix .".".$ext[$count];
// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext[$count],$allowed_filetypes)){
$result[$count] = 2;
$message[$count] = "The file you attempted to upload is not allowed.".$fileName[$count];}
// Now check the filesize, if it is too large then DIE and inform the user.
else if(filesize($_FILES['myfile']['tmp_name'][$count]) > $max_filesize){
$result[$count] = 3;
$message[$count] = "The file you attempted to upload is too large.";}
else if(!file_exists($destination_path)){
$result[$count] = 4;
$message[$count] = "The upload path does not exist";}
// Check if we can upload to the specified path, if not DIE and inform the user.
else if(!is_writable($destination_path)){
$result[$count] = 5;
$message[$count] = "You cannot upload to the specified directory, please CHMOD it to 777.";}
else
{
#move_uploaded_file($tmpName[$count], $target_path[$count]);
$file_info = pathinfo($fileName[$count]);
$sql = "INSERT INTO Files SET
uploader_ip = '".$_SERVER['REMOTE_ADDR']."',
File_Name = '".$fileName[$count]."',
File_Type = '".$fileType[$count]."',
File_Size = '".$fileSize[$count]."',
File_Hash = '".$prefix.".".$ext[$count]."',
File_Extension = '".$file_info['extension']."'";
$sqlresult = mysql_query($sql);
// If the query was successful, give success message
if(!$sqlresult){
$result[$count] = 6;
$message[$count] = "Could not add this file.";//not actually displayed
exit;
}
else{
$message[$count] = "New file successfully added.";//not actually displayed
$result[$count] = 1;
$path[$count] = 'Your file upload was successful, view the file here';
}
}//closes last else (all the writing to the db)
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(
<?php echo json_encode($result[$count]); ?>,
<?php echo json_encode($message[$count]); ?>,
<?php echo json_encode($path[$count]); ?>,
<?php echo json_encode($count); ?>,
<?php echo json_encode($fileName[$count]); ?>,
<?php echo json_encode($ext[$count]); ?>);
</script>
Every time I am getting the error "the file you uploaded is not allowed" when it should pass that test. Any help is greatly appreciated.
I think that everywhere that you are using $count in the arrays inside your for loop, you need to be using $i instead of $count.
$count is always the same (and is outside the bounds of the array).
Try that and see if you have any more luck.
Related
How to make so people can upload files to my website and display them, for example, I want people to be able to upload books like archive.org. FYI I do not know PHP. Heres my code
<html>
<head>
<title>Book Store</title>
<link rel="shortcut icon" href="logo2.ico" />
<link href = "style1.css" type = "text/css" rel = "stylesheet" />
</head>
<body>
<style>
</style>
</div>
<h1>Book Store</h1>
<input type="text" id="booksearch" onkeyup="search()" placeholder="Search for books.."size="40">
<ul id="myUL">
<li>A</li><br>
<li>Alice and Wonderland</li><br>
<li>B</li><br>
<li>Bible King James Version</li><br>
<li>H</li><br>
<li>Hunted Down by Charles Dickens</li><br>
<li>P</li><br>
<li>Pilgrim Progress</li>
<li>Pride and Prejudice epub</li><br>
<li>S</li><br>
<li>Sherlock Holmes complete book epub</li>
<li>Sherlock Holmes complete book pdf</li><br>
<li>T</li><br>
<li><a href="Holmes.pdf" download>The Adventures of Sherlock Holmes pdf</a><br></li>
<li>The Innocence of Father Brown book ep 1 epub</li>
<li>The Wisdom of Father Brown book ep 2 epub</li>
<li>The Incredulity Of Father Brown book ep 3 epub</li>
<li>The Scandal Of Father Brown ep 4 epub</li>
<li>The Secret Of Father Brown ep epub</li><br>
<li>N</li><br>
<li>Nontre Dam history</li><br>
<li>R</li><br>
<li>Romeo and Juliet</li>
</ul>
Get free epub reader for android<br>
<script>
function search() {
// Declare variables
var input, filter, ul, li, a, i, txtValue;
input = document.getElementById('booksearch');
filter = input.value.toUpperCase();
ul = document.getElementById("myUL");
li = ul.getElementsByTagName('li');
// Loop through all list items, and hide those who don't match the search query
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
</script>
<meta http-equiv="Refresh" content="600">
<button onclick="JavaScript:alert('You will love this book!')">
<img src="http://moziru.com/images/book-clipart-cartoon-14.jpg" alt="What We think of this Book" height = "100">
<br>What We think of this Book</button>
<br>
<a href="html.html" atnip construction>Atnip Construction</a><br>
</body>
</html>
Please tell me what I need to add to this code. I don't have any tried version of what I want. If any questions
please ask.
HTML
<html>
<head></head>
<body>
<h2>Please provide the following information:</h2>
<form enctype="multipart/form-data" method="post" action="upload.php">
<input type="hidden" name="MAX_FILE_SIZE" value="5000000" />
Host <br />
<input type="text" name="host" /><p />
Username <br />
<input type="text" name="user" /><p />
Password <br />
<input type="password" name="pass" /><p />
Destination directory <br />
<input type="text" name="dir" /><p />
File <br />
<input type="file" name="file" /><p />
<input type="submit" name="submit" value="Upload File" />
</form>
</body>
</html>
php
<?php
// get FTP access parameters
$host = $_POST['host'];
$user = $_POST['user'];
$pass = $_POST['pass'];
$destDir = $_POST['dir'];
$workDir = "/usr/local/temp"; // define this as per local system
// get temporary file name for the uploaded file
$tmpName = basename($_FILES['file']['tmp_name']);
// copy uploaded file into current directory
move_uploaded_file($_FILES['file']['tmp_name'], $workDir."/".$tmpName) or die("Cannot move uploaded file to working directory");
// open connection
$conn = ftp_connect($host) or die ("Cannot initiate connection to host");
// send access parameters
ftp_login($conn, $user, $pass) or die("Cannot login");
// perform file upload
$upload = ftp_put($conn, $destDir."/".$_FILES['file']['name'], $workDir."/".$tmpName, FTP_BINARY);
// check upload status
// display message
if (!$upload) {
echo "Cannot upload";
} else {
echo "Upload complete";
}
// close the FTP stream
ftp_close($conn);
// delete local copy of uploaded file
unlink($workDir."/".$tmpName) or die("Cannot delete uploaded file from working directory -- manual deletion recommended");
?>
A quick and easy solution:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Upload test</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
File: <input type="file" name="file"/>
<input type="submit" value="Upload" />
</form>
</body>
</html>
upload.php
<?php
if (isset($_FILES['file'])) {
$file = $_FILES['file'];
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$file_error = $file['error'];
$file_ext = explode(".", $file_name);
$file_ext = strtolower(end($file_ext));
$allowed = array("epub", "pdf", "html"); //The extensions you allow
if (in_array($file_ext, $allowed)) {
if ($file_error === 0) {
if ($file_size <= 2097152) {
$file_destination = ' '.$file_name; // If ' ', the file will be placed in this directory
if (move_uploaded_file($file_tmp, $file_destination)) {
echo $file_destination;
} else {
echo "An error has been encountered while moving your file!";
}
} else {
echo "Your file is too big!";
}
} else {
echo "An error has been encountered while uploading your file!";
}
} else {
echo "You can't upload files of this type!";
}
}
?>
Notes:
- $file_destination = ' '.$file_name; -> The ' ' represents in which directory after this one the file will be place in, so ' ' means that it will be placed in this directory, 'test/' means it will be placed in the test subdirectory of this directory, etc.
- If you want something more secure you could try this
- You could also look through one of these solutions
I've tried the script above and it seems to move the file but that file actually doesn't exist in that directory.
So here's an updated script that actually does work:
<?php
if (isset($_FILES['file'])) {
$host = "ftp.example.com";
$user = "username";
$pass = "password";
$destDir = "/public_html"; //The destination directory for the uploaded file (`/public_html` is the root directory for your website files, in some cases it could also be `/var/www`)
$workDir = " ";
$tmpName = basename($_FILES['file']['tmp_name']);
move_uploaded_file($_FILES['file']['tmp_name'], $workDir.$tmpName) or die("Cannot move uploaded file to working directory");
$conn = ftp_connect($host) or die ("Cannot initiate connection to host");
ftp_login($conn, $user, $pass) or die("Cannot login");
$upload = ftp_put($conn, $destDir."/".$_FILES['file']['name'], $workDir.$tmpName, FTP_BINARY);
if (!$upload) {
echo "Cannot upload\n";
} else {
echo "Upload complete\n";
}
ftp_close($conn);
unlink($workDir.$tmpName) or die("Cannot delete uploaded file from working directory -- manual deletion recommended");
}
?>
Im currently in the process of creating a simple PHP website which can display a list of NBA teams and the respective players. One of the things I'm currently working on right now is adding the ability to upload images from the page itself instead of going to PHPMyAdmin.
Here's what the page looks like right now:
I'm trying to figure out how to add the team logo the same way I can add a new team name. As you can see in the bottom part there is an Add Team option which allows the user to add a new team and that team will be registered in the database.
I've tried to write some PHP code which enables the process of uploading images but have failed to do so.
team_list.php
<?php
error_reporting(0);
require_once('../Model/database.php');
// Get all categories
$query = 'SELECT * FROM categories
ORDER BY categoryID';
$statement = $db->prepare($query);
$statement->execute();
$teams = $statement->fetchAll();
$statement->closeCursor();
// Initialize message variable
$msg = "";
// If upload button is clicked ...
if (isset($_POST['upload'])) {
// Get image name
$image = $_FILES['image'];
// image file directory
$target = "images/".basename($image);
$sql = "INSERT INTO categories (img) VALUES ('$image')";
// execute query
mysqli_query($db, $sql);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
}
$result = mysqli_query($db, "SELECT * FROM categories");
?>
<!DOCTYPE html>
<html>
<!-- the head section -->
<head>
<title>NBA</title>
<link rel="stylesheet" type="text/css" href="../css/index.css">
<link rel="shortcut icon" type="image/png" href="images/favicon.ico"/>
</head>
<!-- the body section -->
<body>
<main>
<h1 id="addCategoryh1">Teams</h1>
<table id="categoryListTable">
<tr>
<th>Name</th>
<th> </th>
</tr>
<?php foreach ($teams as $team) : ?>
<tr>
<td><?php echo $team['categoryName']; ?></td>
<td>
<form action="delete_team.php" method="post"
id="delete_product_form">
<input type="hidden" name="team_id"
value="<?php echo $team['categoryID']; ?>">
<input id="deleteCategoryList" type="submit" value="Delete">
</form>
</td>
</tr>
<?php endforeach; ?>
</table>
<br>
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<div id='img_div'>";
echo "<img src='images/".$row['image']."' >";
echo "<p>".$row['image_text']."</p>";
echo "</div>";
}
?>
<h2 id="add_category_h2">Add Team</h2>
<form action="add_team.php" method="post"
id="add_category_form">
<label>Name:</label>
<input type="input" name="name">
<input id="add_category_button" type="submit" value="Add">
</form>
<form method="POST" action="team_list.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<button type="submit" name="upload">POST</button>
</div>
</form>
<br>
<p>View Team List</p>
</main>
<footer id="categoryListFooter">
<p>© <?php echo date("Y"); ?> NBA</p>
</footer>
</body>
</html>
And this is the add_team.php file, which gets the data from database
<?php
// Get the team data
$name = filter_input(INPUT_POST, 'name');
// Validate inputs
if ($name == null) {
$error = "Invalid team data. Check all fields and try again.";
include('../Error/error.php');
} else {
require_once('../Model/database.php');
// Add the product to the database
$query = 'INSERT INTO categories (categoryName)
VALUES (:team_name)';
$query = "INSERT INTO categories (image) VALUES ('$fileName', '$content')";
$statement = $db->prepare($query);
$statement->bindValue(':team_name', $name);
$statement->execute();
$statement->closeCursor();
// Display the team List page
include('team_list.php');
}
?>
This is how the standing.php page looks like
updated add_team.php
// Get the team data
$name = filter_input(INPUT_POST, 'name');
// Validate inputs
if ($name == null) {
$error = "Invalid team data. Check all fields and try again.";
include('../Error/error.php');
} else {
require_once('../Model/database.php');
// Add the product to the database
$query = 'INSERT INTO categories (categoryName)
VALUES (:team_name)';
$query = "INSERT INTO categories (image) VALUES ('$fileName', '$content')";
$statement = $db->prepare($query);
$statement->bindValue(':team_name', $name);
$statement->execute();
$statement->closeCursor();
// Display the team List page
include('team_list.php');
// This is the directory where images will be saved
$target = "../images/";
$target = $target . basename( $_FILES['image']['name']);
// This gets all the other information from the form
$filename = basename( $_FILES['image']['name']);
$team_name = $_POST['team_name'];
// Write the file name to the server
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['image']['name']). " has been uploaded, and your information has been added to the directory";
// Connects to your Database
mysql_connect("renwid", "password") or die(mysql_error()) ;
mysql_select_db("nba") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO categories (img, team_name)
VALUES ('$filename', '$team_name')") ;
} else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
}
?>
You have to first upload successfully to the folder then you can add record in to your database
<?php
if(isset($_POST['submit'])) {
// This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['image']['name']);
// This gets all the other information from the form
$filename = basename( $_FILES['image']['name']);
$team_name = $_POST['team_name'];
// Write the file name to the server
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['image']['name']). " has been uploaded, and your information has been added to the directory";
// Connects to your Database
// mysql_connect("localhost", "root", "") or die(mysql_error()) ;
// mysql_select_db("your_db") or die(mysql_error()) ;
//Writes the information to the database
// mysql_query("INSERT INTO picture (image, team_name)
// VALUES ('$filename', '$team_name')") ;
} else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
}
?>
Your HTML should be
<form action="" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="image" id="image">
<input type="text" name="team_name" id="team_name">
<input type="submit" value="Submit" name="submit">
</form>
Refer https://github.com/aslamanver/nbaTest
You should create a uniqid when uploading the image, this way depending on how many people will upload images, if one were to upload the same image as another, it wouldn't be overwritten in the database
You can do this by using the explode and end function in PHP, also look into prepared statements when using SQL statements, this is to protect your DB against SQL injections, here's a good link:
https://www.w3schools.com/php/php_mysql_prepared_statements.asp
The $_FILES has a few attributes including $_FILES["name"]["error"] which checks for errors, ideally you would make an if statement in which you specify the error condition for the file to uploaded to your DB. Also remember that you must first specify the directory before inserting it into your DB and if the file containing the code is in another folder, you use ../ to go back a directory.
When you display the image on your site you use this:
<img src="directory/<?php echo $row["row"]; ?>">
I have a table where each row has an image and some text. Currently, when I update the content without selecting an image, the database field for the image gets cleared out. However, I want to keep the old image if there's no image selected.
How can I accomplish this?
As a note, I know that mysql_* functions are deprecated.
<?php
include("db/db.php");
$select_db = "select * from aboutus WHERE id=1";
$run_news = mysql_query($select_db);
while ($row = mysql_fetch_array($run_news)) {
$id = $row['id'];
$image = $row['image'];
$content = $row['content'];
}
?>
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Update About Content</h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<form role="form" method="post" action="aboutcontent.php?id=1" enctype="multipart/form-data">
<div class="box-body">
<div class="form-group">
<label for="exampleInputFile">Reselect Image *(H=530px, W=800px)</label>
<input type="file" name="user_image" id="exampleInputFile">
</div>
<div class="form-group">
<label >Content</label><br>
<textarea name="content" class="tinymce" class="form-control" rows="15"><?php echo $content; ?></textarea>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="update" class="btn btn-primary">Update</button>
</div>
</form>
</div>
<?php
include("db/db.php");
// Code for UPDATE button
if (isset($_POST['update'])) {
$content = $_POST['content'];
$imgFile = $_FILES['user_image']['name'];
$tmp_dir = $_FILES['user_image']['tmp_name'];
$imgSize = $_FILES['user_image']['size'];
if ($imgFile) {
$upload_dir = 'images/about/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile, PATHINFO_EXTENSION)); // get image extension
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$userpic = rand(1000, 1000000) . "." . $imgExt;
if (in_array($imgExt, $valid_extensions)) {
if ($imgSize < 5000000) {
unlink($upload_dir . $row['image']);
move_uploaded_file($tmp_dir, $upload_dir . $userpic);
}
else {
$errMSG = "Sorry, your file is too large it should be less then 5MB";
}
}
else {
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
}
else {
// if no image selected the old image remain as it is.
$userpic = $row['image']; // old image from database
}
// if no error occured, continue ....
$sql = "UPDATE aboutus SET image='$userpic', content='$content' WHERE id=1";
$query = mysql_query($sql);
if (!$query) {
die('Invalid query: ' . mysql_error());
}
else {
echo "<script>alert('Successfully Updated!!!'); window.location='index.php?aboutcontent'</script>";
}
}
?>
The problem can easily be solved by checking if a file was submitted or not:
if(!empty($userpic)){
// SQL update here
} else {
// No file submitted so don't update
}
The reason you were getting empty mysql fields is because you were updating the field with an empty variable.
Since I can't comment yet, when you submit without an image are you landing in the if or else statement (place a die('some content) in each part) to figure this out. If you are not making it to the else, try:
//initialize error message
$errMSG = '';
//this error means 'There is no error, the file uploaded with success'
if($_FILES['user_image']['error'] == 0){
//rest of logic to get the filename and move files stuff
}
else{
$userpic = $row['image'];
}
//you dont want to update database if there are errors
if(errMSG = ''{
$sql = "UPDATE aboutus SET image='$userpic', content='$content' WHERE id=1";
}
OR just make two different database calls, one for when you have an image and one for when you dont
if($_FILES['user_image']['error'] == 0){
//rest of logic to get the filename and move files stuff
//if everything else is true (has filename and correct file size)
//you dont want to update database if there are errors
if(errMSG = ''{
$sql = "UPDATE aboutus SET image='$userpic', content='$content' WHERE id=1";
}
$sql = "UPDATE aboutus SET image='$userpic', content='$content' WHERE id=1";
}
else{
$userpic = $row['image'];
$sql = "UPDATE aboutus SET content='$content' WHERE id=1";
}
http://php.net/manual/en/features.file-upload.errors.php
I am using $_FILES for multiple file upload the problem is it is not validating the null condition i have two multiple input files and I want to check whether an image has been uploaded to a specific input type file and on the basis of that I am validating if input 1 has no image uploaded then do nothing I went through dozens of examples on the internet but still it is running both blocks. Here's my code:
<form method="post" action="flyers_admin_process.php" enctype='multipart/form-data'>
<h4 style="margin-bottom: 8%;">Add flyers for Canada(You Can Choose multiple Files)</h4>
<div style="margin-top: 2%;margin-bottom: 6%" class="uk-width-large-1 uk-width-medium-1-1">
<input type="file" id="fileName" name="fileName[]" multiple>
</div>
<h4 style="margin-bottom: 8%;">Add flyers for USA(You Can Choose multiple Files)</h4>
<div style="margin-top: 2%;margin-bottom: 6%" class="uk-width-large-1 uk-width-medium-1-1">
<input type="file" id="fileName2" name="fileName2[]" multiple>
</div>
<input type="submit" />
</form>
flyers_admin_process.php file
<?php
include "db.php";
if($_SERVER['REQUEST_METHOD']=="POST") {
if(!empty($_FILES["fileName"]["name"])) {
echo "inside 1";
$path = "flyers_canada/"; // Upload directory
$count = 0;
foreach ($_FILES['fileName']['name'] as $f => $name) {
if(move_uploaded_file($_FILES["fileName"]["tmp_name"][$f], $path.$name))
$filetmp = $_FILES["fileName"]["tmp_name"][$f];
$filename = $_FILES["fileName"]["name"][$f];
$filepath = "flyers_canada"."/".$filename;
$query="INSERT INTO `flyers_canada`(`path`) VALUES (?)";
$stmt = $db->prepare($query);
if($stmt){
$stmt->bind_param("s",$filepath);
$stmt->execute();
$stmt->close();
}
$count++; // Number of successfully uploaded file
}
}
if(!empty($_FILES["fileName2"]["name"])) {
echo "inside 2";
$path = "flyers_usa/"; // Upload directory
$count = 0;
foreach ($_FILES['fileName2']['name'] as $f => $name) {
if(move_uploaded_file($_FILES["fileName2"]["tmp_name"][$f], $path.$name))
$filetmp = $_FILES["fileName2"]["tmp_name"][$f];
$filename = $_FILES["fileName2"]["name"][$f];
$filepath = "flyers_usa"."/".$filename;
$query="INSERT INTO `flyers_usa`(`path`) VALUES (?)";
$stmt = $db->prepare($query);
if($stmt){
$stmt->bind_param("s",$filepath);
$stmt->execute();
$stmt->close();
}
$count++; // Number of successfully uploaded file
}
}
?>
<script language="javascript">
// alert('Flyer has been added succesfully!');
// location.href = "flyers-admin.php";
</script>
<?php
}
?>
This question already has answers here:
Does page reload ever cause post?
(3 answers)
Closed 9 years ago.
I've been reading some on other question regarding this that i should use the header( 'Locaction: xxx.php' ); but i can't figure out how to implement it to my code. I'm sorry for bad explaination on this. Any help or guiding i would be most greatful! This is the index.php below:
<body>
<div id="container">
<div id="upload">
<div id="logo"><img src="images/logo.png"></div>
<form enctype="multipart/form-data" method="post" action="uploader.php">
<p class="uploadtxt">Choose your file below:</p>
<input type="file" name="image" class="button" />
<input type="submit" value="Upload It!" class="button" />
</form>
</div>
<?php include 'footer.php'; ?>
</div>
</body>
</html>
And this is the uploader.php code below:
<?php
// Set local PHP vars from the POST vars sent from our form using the array
// of data that the $_FILES global variable contains for this uploaded file
$fileName = $_FILES["image"]["name"]; // The file name
$fileTmpLoc = $_FILES["image"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["image"]["type"]; // The type of file it is
$fileSize = $_FILES["image"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["image"]["error"]; // 0 for false... and 1 for true
$url = "http://localhost/";
// Specific Error Handling if you need to run error checking
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
} else if($fileSize > 10000000) { // if file is larger than we want to allow
echo "ERROR: Your file was larger than 10000000kB in file size.";
unlink($fileTmpLoc);
exit();
} else if (!preg_match("/.(gif|jpg|jpeg|png)$/i", $fileName) ) {
// This condition is only if you wish to allow uploading of specific file types
echo "ERROR: Your image was not .gif, .jpg, .jpeg or .png.";
unlink($fileTmpLoc);
exit();
}
//-- GENERATE A RANDOM NAME --//
$newfilename = rand(0, 999);
$newerfilename = $newfilename .'-'. $fileName;
//-- MAKE UPLOADS FOLDER IN YEAR AND MONTHLY --//
$path = "uploads/";
$year_folder = $path . date("Y");
$month_folder = $year_folder . '/' . date("m");
!file_exists($year_folder) && mkdir($year_folder , 0777);
!file_exists($month_folder) && mkdir($month_folder, 0777);
$path = $month_folder . '/';
move_uploaded_file($_FILES["image"]["tmp_name"], $path . $newerfilename);
?>
<html>
<head>
<title>Localhost - Upload Completed!</title>
<?php include_once 'header.php'; ?>
<body>
<div id="container">
<div id="upload">
<div id="logo"><img src="images/logo.png"></div>
<p class="filenametxt"><?php echo "The image is now uploaded!"; ?></p>
<p class="uploadtxt">Get the link below:</p>
<pre><?php echo $url . $path . $newerfilename; ?></pre>
</div>
<?php include 'footer.php'; ?>
</div>
</body>
</html>
Try this:
<input type="hidden" name="key" value="<?php echo (isset($_POST['key']) ? $_POST['key'] : rand(1,150)); ?>" />
<?php if (isset($_POST['key']) { $_SESSION['key'] = $_POST['key']); } ?>
And in your submission PHP:
<?php if (isset($_SESSION['key'])) { if ($_POST['key']==$_SESSION['key']){ echo "You may not resubmit a form!"; } } ?>