New to this, but already I'm scratching my head. Vids aren't uploading/being created, but there's no error msg, and also the filenames/directory location's being recorded into MySQL.
HUH?!
Here's the code:
<?php
date_default_timezone_set("America/New_York");
include("functionpage.php");
session_start();
if (isset($_SESSION['firstname']))
{
if (isset($_POST["submit"]) && $_FILES["uploadfile"]["name"] != "")
{
if (!$connect = mysqli_connect($lh, $rt, $pw, $gj))
{
echo "<p>We're sorry, but the connection to the server is currently unavailable. <br /> Thank you for your patience.<br /><br />
exit();
}
$namefirst = $_SESSION['firstname'];
echo $namefirst."<br /><br />";
$sql = "SELECT * FROM cust_vids WHERE firstname = '$namefirst'";
$result = mysqli_query($connect,$sql);
if (mysqli_num_rows($result) > 0)
{
$rows = mysqli_fetch_assoc($result);
extract($rows);
$directory = "videos/".$username."/".$namefirst;
if(!is_dir($directory))
{
mkdir($directory);
}
$uploadfile = mysqli_real_escape_string($connect,$_FILES["uploadfile"]["name"]);
$uploadfile = strtolower(trim($uploadfile));
$vidtype = $_FILES["uploadfile"]["type"];
$vidsize = $_FILES["uploadfile"]["size"] / 1024;
$vidtmp = $_FILES["uploadfile"]["tmp_name"];
include("layout.php");
echo "Upload: " . $uploadfile . "<br />";
echo "Type: " . $vidtype . "<br />";
echo "Size: " . $vidsize . " Kb<br />";
echo "Stored in: " . $vidtmp."<br /><br />";
echo $username."<br />";
echo $firstname."<br />";
echo $namefirst."<br />";
$extension = explode(".",$uploadfile);
$ext = $extension[1];
$permloc = $directory.$uploadfile;
echo "<p>".$ext."<br />";
/*Will check to see if the file has an extension that isn't allowed*/
if ($ext != "swf" && $ext != "mov" && $ext != "wmv" && $ext != "avi" && $ext != "mpg" && $ext != "mpeg"
&& $ext != "mp4" && $ext != "flv")
{
echo "<p>We're sorry, but we do not support this type of file. <br />
Thank you for your patience.<br /><br />
Back to upload video form<br />
exit();
}
if (file_exists($permloc))
{
echo "<p>File already exists.<br /><br />
Back to Main Blog Page.</p>";
exit();
}
else
{
move_uploaded_file($vidtmp,$permloc);
echo "<br />New location: ".$permloc."<br /><br />";
$sql2 = "INSERT INTO cust_vids (username, firstname, uploadvids,videolocation)
VALUES (\"$username\",\"$firstname\", \"$uploadfile\", \"$permloc\")";
$result2 = mysqli_query($connect,$sql2);
if (!$result2)
{
echo "<p>Sorry, but your file was not uploaded into our records. Please try again.<br /><br />
Back to upload video form<br />
Back to Main Blog Page.</p>";
exit();
}
else
{
echo "<p>The file has been uploaded into your account successfully.<br /><br />
Back to Main Blog Page</p>";
exit();
}
}
}
else
{
include("layout.php");
echo "<p>We're sorry, but there is no user account under that username. Please try again. <br /><br />
Back to upload video form<br />
Back to Main Blog Page.</p>";
exit();
}
}
}
else
{
header("location:blog.php");
}
?>
<html>
<head>
<title>Test script</title>
</head>
<body>
<?php include("layout.php"); ?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<input type="hidden" name="MAXFILESIZE" value="2147483648" /><!--Equals to around 28 mb-->
ADD SCENE:
<input type="file" name='uploadfile' size="30" maxlength="100"/><br />
<input type= "submit" name="submit" value="UPLOAD"/>
</form>
</body>
</html>
/End of file/
Any help/insight would be appreciated. Thx!
It may be that your server has a size_limit for your server and you have to set that to the setting of your php upload script as well.
Check whether "file_uploads" is set to "On" and "upload_max_filesize" is more enough.
Related
I am trying to rotate image using php, image fail to create the jpeg rotated image.
first file 4a.php
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<?php include '4b.php';?>
<?php
function UploadOne($fname)
{
$uploaddir = 'upload/';
if (is_uploaded_file($fname['tmp_name']))
{
$filname = basename($fname['name']);
$uploadfile = $uploaddir . basename($fname['name']);
if (move_uploaded_file ($fname['tmp_name'], $uploadfile))
$res = "File " . $filname . " was successfully uploaded and stored.<br>";
else
$res = "Could not move ".$fname['tmp_name']." to ".$uploadfile."<br>";
}
else
$res = "File ".$fname['name']." failed to upload.";
return ($res);
}
?>
<body>
<?php
if ($_FILES['file']['name'] != "")
{
$file_exts = array("jpg", "bmp", "jpeg", "gif", "png");
$upload_exts = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 2000000)
&& in_array($upload_exts, $file_exts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
}
$res = UploadOne($_FILES['file']);
$filname = $_FILES['file']['name'];
echo ($res);
LoadJpeg($_FILES['file']);
//and save it on your server...
}} ?>
<form action="4a.php" 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>
<form action="imageup.php" method="post">
<input type="hidden" name="view" value="view">
<br><input type="submit" name="view" value="view"/>
</form>
</body>
</html>
<style>
.sucess{
color:#088A08;
}
.error{
color:red;
}
</style>
4b.php
<?php
function LoadJpeg($fname) {
$degrees=180;
//header('Content-type: image/jpeg');
$f= $fname['name'];
$source = imagecreatefromjpeg($f);
$rotate = imagerotate($source, $degrees, 0);
$j=imagejpeg($rotate,$fname['name'],100);
?>
<img src="upload/<?php echo $fname['name'];?>">
<img src="upload/<?php echo $j;?>">
<?php
// file_put_contents("upload/".$fname['name'],$j);
}
?>
it shows that
"failed to open stream: No such file or directory in E:\wamp\www\Gomal_FinalTask\4b.php on line 6"
The file name of the uploaded file on the server is in $fname['tmp_name']. $fname['name'] is just the file name as it was on the client-side
You need to use that entry when loading the image into an image resource, ie
$f= $fname['tmp_name'];
$source = imagecreatefromjpeg($f);
I am trying to upload an image to server using PHP and the save inside a dir, and then returning the image url.
HTML:
<input name="photo" type="file" />
PHP
save_string_to_database( upload_img($_POST['photo']));
I have not much idea of PHP, I got a code from SO, but it did not do anything. Kindly help me to fix this code, or give a simple code to perform an upload:
function upload_img($img){
if ((($_FILES[$img]["type"] == "image/gif")
|| ($_FILES[$img]["type"] == "image/jpeg")
|| ($_FILES[$img]["type"] == "image/pjpeg")
|| ($_FILES[$img]["type"] == "image/jpg")
|| ($_FILES[$img]["type"] == "image/png"))
&& ($_FILES[$img]["size"] < 20000)
&& (strlen($_FILES[$img]["name"]) < 51)){
if ($_FILES[$img]["error"] > 0){
echo "Return Code: " . $_FILES[$img]["error"];
}
else{
// echo "Upload: " . $_FILES["image"]["name"] . "<br />";
// echo "Type: " . $_FILES["image"]["type"] . "<br />";
// echo "Size: " . ($_FILES["image"]["size"] / 1024) . " Kb<br />";
// echo "Temp file: " . $_FILES["image"]["tmp_name"] . "<br />";
if (file_exists(THEME_DIR."/images/" . $_FILES[$img]["name"])){
echo $_FILES[$img]["name"] . " already exists. ";
}
else{
move_uploaded_file($_FILES[$img]["tmp_name"],THEME_DIR."/images/" . $_FILES[$img]["name"]);
return THEME_DIR."/images/" . $_FILES[$img]["name"];
}
}
}
}
Here's a simple one.
HTML form to upload image
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="512000" />
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
Your PHP file that does the Upload
<?php
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo "<p>";
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
Source
First you need a multipart/form-data form for uploading. This is a must :)
<form action="upload_file.php" 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>
The PHP part is fairly simple:
This would result your file stored in "upload/{filename}"
The main part you want to consider is how to get the filename and back to your write_string_to_database procedure, you could do a simple script after the upload page like
save_string_to_database("upload/" . $_FILES["file"]["name"]);
would do the trick.
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
}
}
for file upload try this
<?php if(isset($_POST['submit']))
{
$ImageName = $_FILES['photo']['name'];
$fileElementName = 'photo';
$path = 'images/';
$location = $path . $_FILES['photo']['name'];
move_uploaded_file($_FILES['photo']['tmp_name'], $location);
} ?>
<form name="form1" id="form1" method="post" action="" enctype="multipart/form-data">
<input type="file" name="photo">
<input type="submit" name="submit">
</form>
This my function, variable $ten_anh is name of file image in html.
function upload_anh($ten_anh){ //$ten_anh la ten tren html vi du "avatar"
if(isset($_FILES[$ten_anh])){
$errors= array();
$file_name = $_FILES[$ten_anh]['name'];
$file_size =$_FILES[$ten_anh]['size'];
$file_tmp =$_FILES[$ten_anh]['tmp_name'];
$file_type=$_FILES[$ten_anh]['type'];
$file_ext=strtolower(end(explode('.',$_FILES[$ten_anh]['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false){
$errors[]="Không chấp nhận định dạng ảnh có đuôi này, mời bạn chọn JPEG hoặc PNG.";
}
if($file_size > 2097152){
$errors[]='Kích cỡ file nên là 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"../images/".$file_name);
echo "Thành công!!!";
}
else{
print_r($errors);
}
}
}
Example:
- html code:
<input type="file" id="avatar" name="avatar"accept="image/png, image/jpeg" required/>
call function php: upload_anh('avatar');
<form method='post' action='' enctype='multipart/form-data'>
Name : <input type="text" name="name" required=""/><br><br>
Code : <input type="text" name="code" required=""/><br><br>
Price : <input type="text" name="price" required=""/><br><br>
Image : <input type="file" name="image" required=""/><br><br>
<button type='submit' class='buy' name="submit">Add Now</button>
</form>
<!--insert data -->
<?php
session_start();
include('db.php');
if(isset($_POST["submit"]));
{
/*echo "<pre>";
print_r($_POST);
print_r($_FILES);*/
$name = $_POST["name"];
$code = $_POST["code"];
$price = $_POST["price"];
$image = $_FILES["image"]["name"];
/* folder image save */
// $target_dir = "/var/www/html/shivam/new/upload/";
// $target_file = $target_dir.basename($_FILES["image"]["name"]);
// /*echo "1121".$target_file;*/
// $name = basename($_FILES["image"]["name"]);
// mysqli_query($con,$qry);
// /* move file */
// move_uploaded_file($_FILES['image']['tmp_name'],$target_dir.$name);
/* move_uploaded_file($tmp_name, "$target_dir/$name");*/
/* end */
$uploaddir = '/var/www/html/uploads/';
$uploadfile = $uploaddir . basename($_FILES['image']['name']);
echo '44'.$uploadfile;
echo "<p>";
if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';enter code here
print_r($_FILES);
print "</pre>";
}
?>
I'm a beginner in php and now doing a project in php. I want to upload images(maximum four image files only).I used the following code to upload images.
<script type="text/javascript">
count=1;
function add_file_field()
{
if(count<4)
{
var container=document.getElementById('file_container');
var file_field=document.createElement('input');
file_field.name='images[]';
file_field.type='file';
container.appendChild(file_field);
var br_field=document.createElement('br');
container.appendChild(br_field);
count++;
}
}
</script>
<div id="file_container">
<input name="images[]" type="file" id="file[]" />
<br />
</div>
<br>Add
I used the following code for single file upload.It's working
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 100000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "File Error : " . $_FILES["file"]["error"] . "<br />";
}else {
echo "Upload File Name: " . $_FILES["file"]["name"] . "<br />";
echo "File Type: " . $_FILES["file"]["type"] . "<br />";
echo "File Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "File Description:: ".$_POST['description']."<br />";
if (file_exists("images/".$_FILES["file"]["name"]))
{
echo "<b>".$_FILES["file"]["name"] . " already exists. </b>";
}else
{
$tmpname=$_FILES["file"]["tmp_name"];
$name=$_FILES["file"]["name"];
$new="jun.jpg";
rename($name,$new);
move_uploaded_file($_FILES["file"]["tmp_name"],"images/".$new);
echo "Stored in: " . "images/" .$new."<br />";
?>
Uploaded File:<br>
<img src="images/<?php echo $new; ?>" alt="Image path Invalid" >
<?php
}
}
}else
{
echo "Invalid file detail ::<br> file type ::".$_FILES["file"]["type"]." , file size::: ".$_FILES["file"]["size"];
}
?>
I need help to modify this code to upload maximum of 4 images.
Can rename function be used to rename a selected file for upload on moving to a specified folder?
but it was showing error
Please do help me
You should allow multiple file selection in your file input, so you do not have to add a new input over and over again:
<input id="file" type="file" name="images[]" multiple>
After submitting the form you can iterate over $_FILES array like that:
foreach($_FILES['images'] as $file) {
//your code here --> replace $_FILES['file'] with $file
}
I hope this helps.
<?php
if(isset($_POST['submit']))
{
$count=count($_FILES["images"]["name"]);
for($i=0;$i<$count;$i++)
{
if ((($_FILES["images"]["type"][$i] == "image/gif")
|| ($_FILES["images"]["type"][$i] == "image/jpeg")
|| ($_FILES["images"]["type"][$i] == "image/pjpeg"))
&& ($_FILES["images"]["size"][$i] < 100000))
{
if ($_FILES["images"]["error"][$i] > 0)
{
echo "File Error : " . $_FILES["images"]["error"][$i] . "<br />";
}
else
{
echo "Upload File Name: " . $_FILES["images"]["name"][$i] . "<br />";
echo "File Type: " . $_FILES["images"]["type"][$i] . "<br />";
echo "File Size: " . ($_FILES["images"]["size"][$i] / 1024) . " Kb<br />";
if (file_exists("public/images/".$_FILES["images"]["name"][$i] ))
{
echo "<b>".$_FILES["images"]["name"][$i] . " already exists. </b>";
}
else
{
move_uploaded_file($_FILES["images"]["tmp_name"][$i] ,"public/images/". $_FILES["images"]["name"][$i] );
echo "Stored in: " . "public/images/" . $_FILES["images"]["name"][$i] ."<br />";
?>
Uploaded File:<br>
<img src="public/images/<?php echo $_FILES["images"]["name"][$i] ; ?>" alt="Image path Invalid" >
<?php
}
}
}else
{
echo "Invalid file detail ::<br> file type ::".$_FILES["images"]["type"][$i] ." , file size::: ".$_FILES["images"]["size"][$i] ;
}
}
}?>
image uploaded using for loop..foreach was showing error
Here is an example of multi-file upload in PHP
https://github.com/hemantrai88/html5-php_multi-file-upload
I have one example which is working, I think this will help you
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="files[]" />
<input type="submit"/>
</form>
In php
if(isset($_FILES['files'])){
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
$query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$user_id','$file_name','$file_size','$file_type'); ";
$desired_dir="user_data";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==false){
move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
}else{ // rename the file if another one exist
$new_dir="$desired_dir/".$file_name.time();
rename($file_tmp,$new_dir) ;
}
mysql_query($query);
}else{
print_r($errors);
}
}
if(empty($error)){
echo "Success";
}
}
I have a form like this:
<form method="post" enctype="multipart/form-data">
<input type="text" id="title" placeholder="Project Title"/><br />
<input type="text" id="vurl" placeholder="If You have any video about project write your video url path here" style="width:435px;"/><br />
<textarea id="prjdesc" name="prjdesc" rows="20" cols="80" style="border-style:groove;box-shadow: 10px 10px 10px 10px #888888;"placeholder="Please describe Your Project"></textarea>
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /><br>
<input type="button" name="submit" value="Submit" id="update"/>
</form>
On click submit the data is storing in database and displaying using Ajax call
this is my js code:
$("#update").click(function(e) {
alert("update");
e.preventDefault();
var ttle = $("#title").val();
alert(ttle);
var text = $("#prjdesc").val();
var vurl = $("#vurl").val();
var img = $("#file").val();
alert(vurl);
var dataString = 'param='+text+'¶m1='+vurl+'¶m2='+ttle+'¶m3='+img;
$.ajax({
type:'POST',
data:dataString,
url:'insert.php',
success:function(id) {
alert(id);
window.location ="another.php?id="+id;;
}
});
});
here i am storing data using insert.php and displaying using another.php
but when coming to the image part i dont understand how to store image in folder and path in db, i mean i am bit confused to integrate code in insert.php
insert.php
$host="localhost";
$username="root";
$password="";
$db_name="geny";
$tbl_name="project_details";
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$name = $_POST['param'];
$video = $_POST['param1'];
$title = $_POST['param2'];
$sql="INSERT INTO $tbl_name (title, content, video_url) VALUES ('$title','$name','$video')";
if(mysql_query($sql)) {
echo mysql_insert_id();
} else {
echo "Cannot Insert";
}
if i do separate then the image is storing in folder..
if i do separate then the form code is:
<form action="upload_file.php" 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>
upload_file.php:
<?php
$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"] < 50000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("C:/wamp/www/WebsiteTemplate4/upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"C:/wamp/www/WebsiteTemplate4/upload/" . $_FILES["file"]["name"]);
// echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
$tmp = "C:/wamp/www/WebsiteTemplate4/upload/" . $_FILES["file"]["name"];
echo $tmp;
}
}
}
else
{
echo "Invalid file";
}
?>
this is working perfectly...
my question is how to integrate this code in insert.php...
please help me...
This code would work fine without the use of javascript. But make sure to change the directory and the table name and fields on line "2" and "66" resp.
We will create a hidden textarea which will create the datastring and we will get all the params using $_GET
<script>
$("#update").click(function(e) {
alert("update");
e.preventDefault();
var ttle = $("#title").val();
alert(ttle);
var text = $("#prjdesc").val();
var vurl = $("#vurl").val();
var img = $("#file").val();
alert(vurl);
var textareastring = $('#string').val();
var dataString = 'textareastring' = textareastring;
$.ajax({
type:'POST',
data:dataString,
url:'insert.php?param='+text+'¶m1='+vurl+'¶m2='+ttle+'¶m3='+img',
success:function(id) {
alert(id);
window.location ="another.php?id="+id;;
}
});
});
</script>
<textarea id="string" style="display:none;">aa</textarea>
<?php
$name = $_GET['param3'];
// The name.n ow replacing all the $file_name with $name
$url = $_GET['param1'];
$text = $_GET['param'];
$title = $_GET['param2'];
$upload_dir = $url;
$num_files = 1;
//the file size in bytes.
$size_bytes =104857600; //51200 bytes = 50KB.
//Extensions you want files uploaded limited to.
$limitedext = array(".tif",".gif",".png",".jpeg",".jpg");
//check if the directory exists or not.
if (!is_dir("$upload_dir")) {
die ("Error: The directory <b>($upload_dir)</b> doesn't exist. ");
}
//check if the directory is writable.
if (!is_writeable("$upload_dir")){
die ("Error: The directory <b>($upload_dir)</b> . ");
}
if (isset($_POST['upload_form'])){
echo "<h3>Upload results:</h3><br>";
//do a loop for uploading files based on ($num_files) number of files.
for ($i = 1; $i <= $num_files; $i++) {
//define variables to hold the values.
$new_file = $_FILES['file'.$i];
$name = $new_file['name'];
//to remove spaces from file name we have to replace it with "_".
$name = str_replace(' ', '_', $name);
$file_tmp = $new_file['tmp_name'];
$file_size = $new_file['size'];
#-----------------------------------------------------------#
# this code will check if the files was selected or not. #
#-----------------------------------------------------------#
if (!is_uploaded_file($file_tmp)) {
//print error message and file number.
echo "File: Not selected.<br><br>";
}else{
#-----------------------------------------------------------#
# this code will check file extension #
#-----------------------------------------------------------#
$ext = strrchr($name,'.');
if (!in_array(strtolower($ext),$limitedext)) {
echo "File $i: ($name) Wrong file extension. <br><br>";
}else{
#-----------------------------------------------------------#
# this code will check file size is correct #
#-----------------------------------------------------------#
if ($file_size > $size_bytes){
echo "File : ($name) Faild to upload. File must be no larger than <b>100 MB</b> in size.";
}else{
#-----------------------------------------------------------#
# this code check if file is Already EXISTS. #
#-----------------------------------------------------------#
if(file_exists($upload_dir.$name)){
echo "File: ($name) already exists. <br><br>";
}else{
#-------------------------------#
# this function will upload the files. #
#-------------------------------#
if (move_uploaded_file($file_tmp,$upload_dir.$name)) {
$sql = "INSERT INTO table_name(field1, field2) VALUES('$field1', '$field2');";
echo "File: ($name) has been uploaded successfully." . "<img src='uploads/$name'/>";
}else{
echo "File: Faild to upload. <br><br>";
}#end of (move_uploaded_file).
}#end of (file_exists).
}#end of (file_size).
}#end of (limitedext).
}#end of (!is_uploaded_file).
}#end of (for loop).
# print back button.
////////////////////////////////////////////////////////////////////////////////
//else if the form didn't submitted then show it.
}else{
echo "<form method=\"post\" action=\"$_SERVER[PHP_SELF]\" enctype=\"multipart/form- data\">";
// show the file input field based on($num_files).
for ($i = 1; $i <= $num_files; $i++) {
echo "<b>Image: </b><input type=\"file\" size=\"70\" name=\"file". $i ."\" style=\"width:45%\">";
}
echo " <input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"$size_bytes\">
<input type=\"submit\" name=\"upload_form\" value=\"Upload\">
</form>";
}
?>
If you mean how to call insert.php after submit button was clicked, in this line
<form method="post" enctype="multipart/form-data">
you have to add this
<form method="post" enctype="multipart/form-data" action="insert.php">
<?php
/*dont use path like this C:/wamp/www/WebsiteTemplate4/upload/ becuase you are working at localhost server*/
if (file_exists("upload/" . $_FILES["file"]["name"])){
echo $_FILES["file"]["name"] . " already exists. ";
}else{
$file = $_FILES["file"]["name"]
$filePath = "upload/" . $file;
if(move_uploaded_file($_FILES["file"]["tmp_name"], $filePath)){
/*prepare sql query here and insert*/
$sql = "INSERT INTO table_name(field1, field2) VALUES('$field1', '$field2');";
if(mysql_query($sql)){
echo "File saved in database successfully <strong>{$filePath}</strong>";
}else{
echo "File not uploaded there are an error <strong>{$filePath}</strong>";
}
}else{
echo "File not uploaded there are an error <strong>{$file}</strong>";
}
} ?>
try this code if you have any doubt or code not working fine then ask me again.
Thanks
This question already has answers here:
File not uploading PHP
(11 answers)
Closed 2 years ago.
I have written a simple file upload script but it gives me the error of undefined index file1.
<html>
<body>
<form method="post">
<label for="file">Filename:</label>
<input type="file" name="file1" id="file1" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
<?php
if(isset($_POST['submit'])) {
if ($_FILES["file1"]["error"] > 0) {
echo "Error: " . $_FILES["file1"]["error"] . "<br />";
} else {
echo "Upload: " . $_FILES["file1"]["name"] . "<br />";
echo "Type: " . $_FILES["file1"]["type"] . "<br />";
echo "Size: " . ($_FILES["file1"]["size"] / 1024) . " Kb<br />";
echo "Stored in: " . $_FILES["file1"]["tmp_name"];
}
}
?>
What is the problem in code?
You lack enctype="multipart/form-data" in your <form> element.
Another solution for simple php file upload script is here :
(make a yourfile.php and insert the below code. then put that yourfile.php on your website)
<?php
$pass = "YOUR_PASSWORD";
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1256" /></head><body>
<?php
if (!empty($_GET['action']) && $_GET['action'] == "logout") {session_destroy();unset ($_SESSION['pass']);}
$path_name = pathinfo($_SERVER['PHP_SELF']);
$this_script = $path_name['basename'];
if (empty($_SESSION['pass'])) {$_SESSION['pass']='';}
if (empty($_POST['pass'])) {$_POST['pass']='';}
if ( $_SESSION['pass']!== $pass)
{
if ($_POST['pass'] == $pass) {$_SESSION['pass'] = $pass; }
else
{
echo '<form action="'.$_SERVER['PHP_SELF'].'" method="post"><input name="pass" type="password"><input type="submit"></form>';
exit;
}
}
?>
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
Please choose a file: <input name="file" type="file" /><br />
<input type="submit" value="Upload" /></form>
<?php
if (!empty($_FILES["file"]))
{
if ($_FILES["file"]["error"] > 0)
{echo "Error: " . $_FILES["file"]["error"] . "<br>";}
else
{echo "Stored file:".$_FILES["file"]["name"]."<br/>Size:".($_FILES["file"]["size"]/1024)." kB<br/>";
move_uploaded_file($_FILES["file"]["tmp_name"],$_FILES["file"]["name"]);
}
}
// open this directory
$myDirectory = opendir(".");
// get each entry
while($entryName = readdir($myDirectory)) {$dirArray[] = $entryName;} closedir($myDirectory);
$indexCount = count($dirArray);
echo "$indexCount files<br/>";
sort($dirArray);
echo "<TABLE border=1 cellpadding=5 cellspacing=0 class=whitelinks><TR><TH>Filename</TH><th>Filetype</th><th>Filesize</th></TR>\n";
for($index=0; $index < $indexCount; $index++)
{
if (substr("$dirArray[$index]", 0, 1) != ".")
{
echo "<TR>
<td>$dirArray[$index]</td>
<td>".filetype($dirArray[$index])."</td>
<td>".filesize($dirArray[$index])."</td>
</TR>";
}
}
echo "</TABLE>";
?>
Make the following changes and try.
<form method="post" action="" enctype="multipart/form-data" >
Html
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Php
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
<html>
<body>
<form action="" method="post" ectype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"></br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if(isset($_POST['submit']))
{
$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"] < 20000000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}enter code here
}
?>
</body>
</html>
Primary issue is your form does not have option to send file content over http .
To send binary data along with the text data from input elements you need to add an extra attribute in form tag .
<form method="post" enctype="multipart/form-data">
Then in php code
try this line
<?php
print_r($_FILES);
?>
above code will display all information regarding file uploading from your form .