PHP - How can I insert the new filenames of uploading to MySQL - php

I'm doing the upload multimage files and rename it successfully.
However, I don't know, How to get the name of file that I rename it with function move_uploaded_file(). I want to get the newname to insert to mySQL
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/png"))
&& ($_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("images/location/".$_FILES["images"]["name"][$i] ))
{
echo "<b>".$_FILES["images"]["name"][$i] . " already exists. </b>";
}
else
{
move_uploaded_file($_FILES["images"]["tmp_name"][$i] ,"images/location/"."NEW_NAME!!!".$i.".jpg" );
// echo "Stored in: " . "images/location/" . $_FILES["images"]["name"][$i] ."<br />";
?>
<?php
}
}
}else
{
echo "Invalid file detail ::<br> file type ::".$_FILES["images"]["type"][$i] ." , file size::: ".$_FILES["images"]["size"][$i] ;
}
}
}
..
<form action = "" method="POST" enctype="multipart/form-data">
<input type="file" name="images[]" size="20" />
<input type="file" name="images[]" size="20" />
<input type="file" name="images[]" size="20" />
<input type="submit" name="submit"/>
</form>

I have used this in my project
$temp = explode(".", $_FILES['image']['name']);
$name = round(microtime(true)) . substr(md5(rand()), 0, 4) . '.' . end($temp);
move_uploaded_file($_FILES['image']['tmp_name'], $name);
//this is for single image upload
//Here $name is the new image name. You can then use your mysql_insert function to insert new image name to the database
//to upload multiple file just pass the file name as an array,tmp_name as an array
public function __attachments_upload($name, $tmp_name) {
foreach ($name as $key => $value) {
$temp = explode(".", $value);
$name = round(microtime(true)) . substr(md5(rand()), 0, 4) . '.' . end($temp);
move_uploaded_file($tmp_name[$key], $name);
//here you can use mysql_insert
}
}

Related

Uploading multiple files and giving the uploaded file a new name in PHP

Hi so I have this upload script, that can upload one file at the time but I need to upload more than one file at the same time and then name every uploaded file as 1 and the next file as 2 and the next one as 3 and so on.
<?php
$allowedExts = array("gif", "jpeg", "jpg", "png","JPG");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if (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"] / 1032) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("i/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"], "i/" . $_FILES["file"]["name"]);
echo "Stored in: " . "i/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
Just use several inputs on your html:
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<input name="userfile[]" type="file" /><br />
<input name="userfile[]" type="file" /><br />
<input type="submit" value="Send files" />
</form>
And in your PHP
<?php
for ($i=0; $i < count($_FILES['name']); $i++) {
$new_file = $_FILES['name'][$i] . '.' . $i+1;
}
?>
The later will create the filenames appending the index +1 so you'll have:
myfile1.txt.1
myfile1.txt.2
Adjust as needed.
Edit: Check this link.
You should be able to do like this:
$files = array();
$allowed_filetypes = array('jpg','jpeg','gif','bmp','png','tif','pdf');
$max_filesize = 15242880;
$upload_path = 'images/image_uploads/';
for ($i = 0; $i < count($_FILES['files']['name']); $i++){
if($_FILES['files']['name'][$i] != "") {
$filename = $_FILES['files']['name'][$i];
$file_info = pathinfo($_FILES['files']['name'][$i]);
$ext = strtolower($file_info['extension']);
//echo "<span style='font-size: 20px; color: #ff3333;'>".$ext."</span>";
if(!in_array($ext,$allowed_filetypes))
die("The file you attempted to upload ($filename) is not allowed.");
if(filesize($_FILES['files']['tmp_name'][$i]) > $max_filesize)
die("The file you attempted to upload ($filename) is too large.");
if(!is_writable($upload_path))
die("You cannot upload to the specified directory, please CHMOD it to 777.");
$filename = ($i+1).".".$ext;
if(move_uploaded_file($_FILES['files']['tmp_name'][$i],$upload_path.$filename)) {
$result = mysql_query("Insert Into image_uploads_images (upload_id, image, original_name) Values ('$id', '$filename', '".$_FILES['files']['name'][$i]."');");
if($result){
array_push($files, "http://www.site.com/images/image_uploads/$filename => ".$_FILES['files']['name'][$i]);
}else{
echo "<p style=\"color:#cc3333;\">Unable to upload ".$_FILES['files']['name'][$i]."</p>";
}
}else{
echo "<p style=\"color:#cc3333;\">Unable to upload ".$_FILES['files']['name'][$i]."</p>";
}
}
}
Edit
Just as a brief explanation, all file inputs would have the same name, in this case files. But when you do that, you need to add [] behind the name in the form element, like <input type="file" name="files[]" /> so that it comes through as an array.
Once you have the $_FILES array you can go through it recursively for each file uploaded and do with it what you need.

Image isn't appearing on image upload

I am using xampp on Windows 7. My problem is that the image isn't appearing when I clicked the submit button.
Here's my php code:
<?php
$fileLocation = 'C:\xampp\htdocs\images';
$name = $_FILES["file"]["name"];
$tempName = $_FILES["file"]["tmp_name"];
$size = $_FILES["file"]["size"];
$fileType = $_FILES["file"]["type"];
if ($fileType == "images/jpeg" && $size < 2000000)
{
if ($_FILES['file']['error'] > 0)
{
echo "File error! : " . $_FILES['file']['error']. "</br>";
}
else
{
echo "File Name: " . $name . "</br>";
echo "File Type: " . $fileType . "</br>";
echo "File Size: " . $size . "</br>";
}
if (file_exists($file_location, $name))
{
echo "File already exists!" . $name . "</br>";
}
else
{
move_uploaded_file($tempname, $fileLocation.$name);
echo "Stored in: " . $fileLocation . "</br>";
}
}
?>
HTML CODE:
<form enctype="multipart/form-data" action="uploadFile.php" method="POST">
Send this file: <input name="file" type="file" id='file'/>
<input type="submit" value="Send File" name="submit"/>
</form>
Thank you for your response.
Also, check if Your HTML form has enctype='multipart/form-data' attribute set. It's easy to forget about it (at least I do almost every time).

How do i upload multiple images to remote server in this circumstances?Looping or repeat upload procedure?

I am new to php,trying to do a form, which allows me to upload a few text fields and then upload 3 images, the images are then uploaded into a remote server, and the name of the images are saved into database, so then it can be pulled out and displayed later.
(p.s. Ignore the SQL injection issue, i just havent got time around that yet. Thanks)
At the moment i am testing this on localhost.
My question is should i loop it, or should i just do the upload process 3 times?
Below is what i tried. But the looping trial isnt uploading the files, it just goes straight to invalid file. Also i would like to make sure all 3 files are valid files before uploading them, would i have to loop the verifying first then loop the uploading again?
Please give me some advice, thanks for your time.
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
ob_start();
session_start();
include 'connect.php';
if ($_POST)
{
//get form data
$Listingname = addslashes(strip_tags($_POST['Listingname']));
$Location = addslashes(strip_tags($_POST['Location']));
$nobed = addslashes(strip_tags($_POST['nobed']));
$zip = addslashes(strip_tags($_POST['zip']));
$price = addslashes(strip_tags($_POST['price']));
$username=addslashes(strip_tags($_POST[$_SESSION['username']]));
if (!$Listingname||!$nobed||!$nobed||!$zip||!$price)
echo "Please fill out all fields";
else
for($i=0;$i<count($_FILES["image"]["name"]);$i++)
{$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"][$i]);
$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"] < 400000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"][$i] . "<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"][$i] . " already exists please add another file, or change the. ";
}
else
{
$photo=$_FILES["file"]["name"][$i];
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/$photo");
echo "Stored in: " . "upload/" . $_FILES["file"]["name"][$i];
}
}
}
else
{
echo "Invalid file";
}
{
$username=$_SESSION['username'];
//register into database
mysqli_query($con,"INSERT INTO Listing (username,Listingname,Location,nobed,zip,price,pic1) VALUES
('$username','$Listingname','$Location','$nobed','$zip','$price','$photo');") or die(mysqli_error());
echo "Listing Added";
}
}
}
else
{
?>
<form action="Submitlisting2.php" method="post"
enctype="multipart/form-data">
Listing Name:<br />
<input type='text' name='Listingname'><p />
Location:<br />
<input type='text' name='Location'><p />
Number of Beds:<br />
<input type='test' name='nobed'><p />
Zip:<br />
<input type='text' name='zip'><p />
Price:<br />
<input type='text' name='price'><p />
<label for="file">Pic1(File must be exceed 4mb):</label>
<input type="file" name="file[]" id="file"><br>
<label for="file">Pic2(File must be exceed 4mb):</label>
<input type="file" name="file[]" id="file"><br>
<br>
<input type='submit' name='submit' value='Submit'>
</form>
<?php
}
?>
Attempt without looping(this get very very long, the attempt is only with 2 images upload, which is 1 reason why i am thinking to loop)
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
ob_start();
session_start();
include 'connect.php';
if ($_POST)
{
//get form data
$Listingname = addslashes(strip_tags($_POST['Listingname']));
$Location = addslashes(strip_tags($_POST['Location']));
$nobed = addslashes(strip_tags($_POST['nobed']));
$zip = addslashes(strip_tags($_POST['zip']));
$price = addslashes(strip_tags($_POST['price']));
$username=addslashes(strip_tags($_POST[$_SESSION['username']]));
if (!$Listingname||!$nobed||!$nobed||!$zip||!$price)
echo "Please fill out all fields";
else
{$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"] < 400000)
&& 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 please add another file, or change the. ";
}
}
}
}
else
{$allowedExts1 = array("gif", "jpeg", "jpg", "png");
$temp1 = explode(".", $_FILES1["file1"]["name1"]);
$extension1 = end($temp1);
if ((($_FILES1["file"]["type"] == "image/gif")
|| ($_FILES1["file"]["type"] == "image/jpeg")
|| ($_FILES1["file"]["type"] == "image/jpg")
|| ($_FILES1["file"]["type"] == "image/pjpeg")
|| ($_FILES1["file"]["type"] == "image/x-png")
|| ($_FILES1["file"]["type"] == "image/png"))
&& ($_FILES1["file"]["size"] < 400000)
&& in_array($extension1, $allowedExts1))
{
if ($_FILES1["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES1["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES1["file"]["name"] . "<br>";
echo "Type: " . $_FILES1["file"]["type"] . "<br>";
echo "Size: " . ($_FILES1["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES1["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES1["file"]["name"]))
{
echo $_FILES1["file"]["name"] . " already exists please add another file, or change the. ";
}
}
}
else
{ $photo=$_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/$photo");
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
else
{
echo "Pic 1 Invalid file" and die("Unable to upload pic1");
}
}
{
$photo1=$_FILES1["file"]["name"];
move_uploaded_file($_FILES1["file"]["tmp_name"],
"upload/$photo1");
echo "Stored in: " . "upload/" . $_FILES1["file"]["name"];
}
else
{
echo "Pic 2 Invalid file" and die("Unable to upload Pic2");
}
{
$username=$_SESSION['username'];
//register into database
mysqli_query($con,"INSERT INTO Listing (username,Listingname,Location,nobed,zip,price,pic1) VALUES
('$username','$Listingname','$Location','$nobed','$zip','$price','$photo');") or die(mysqli_error());
echo "Listing Added";
}
else
{
?>
<form action="Submitlisting2.php" method="post"
enctype="multipart/form-data">
Listing Name:<br />
<input type='text' name='Listingname'><p />
Location:<br />
<input type='text' name='Location'><p />
Number of Beds:<br />
<input type='test' name='nobed'><p />
Zip:<br />
<input type='text' name='zip'><p />
Price:<br />
<input type='text' name='price'><p />
<label for="file">Filename(File must be exceed 4mb):</label>
<input type="file" name="file" id="file"><br>
<label for="file">Filename(File must be exceed 4mb):</label>
<input type="file" name="file1" id="file1"><br>
<br>
<input type='submit' name='submit' value='Submit'>
</form>
<?php
}
?>
If i am talking about a better User Experience then Looping is much better then repeat upload and for repeat upload you can/should use ajax upload.

Multiple file upload in PHP - rename files

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";
}
}

simple file upload script [duplicate]

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 .

Categories