save image in folder and path in mysql database - php

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+'&param1='+vurl+'&param2='+ttle+'&param3='+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+'&param1='+vurl+'&param2='+ttle+'&param3='+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

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).

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

send an image (optional) with message subject and body?

I've created a simple php messaging system for users to send and receive messages to each other. What i want to try and do is add in an optional image input field so the user can choose an image and send this as part of their message?
The photo would need to store in a directory folder on my server and the name of the image will need to be stored in mysql table along with the rest of the message fields i.e. content, subject, image_name.
Can someone show me how i could adapt my code to upload an image with the form please?
<?php ob_start(); ?>
<?php
// CONNECT TO THE DATABASE
require('includes/_config/connection.php');
// LOAD FUNCTIONS
require('includes/functions.php');
// GET IP ADDRESS
$ip_address = $_SERVER['REMOTE_ADDR'];
?>
<?php require_once("includes/sessionframe.php");
?>
<?php
confirm_logged_in();
if (isset ($_GET['to'])) {
$user_to_id = $_GET['to'];
}
?>
<?php
//We check if the form has been sent
if(isset($_POST['subject'], $_POST['message_content']))
{
$subject = $_POST['subject'];
$content = $_POST['message_content'];
$image = $POST ['image'];
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$subject = stripslashes($subject);
$content = stripslashes($content);
$image = stripslashes($image);
}
//We check if all the fields are filled
if($_POST['subject']!='' and $_POST['message_content']!='')
{
$sql = "INSERT INTO ptb_messages (id, from_user_id, to_user_id, subject, content, image) VALUES (NULL, '".$_SESSION['user_id']."', '".$user_to_id."', '".$subject."', '".$content."', '".$image."');";
mysql_query($sql, $connection);
echo "<div class=\"infobox2\">The message has successfully been sent.</div>";
}
}
if(!isset($_POST['subject'], $_POST['message_content']))
if (empty($_POST['subject'])){
$errors[] = 'The subject cannot be empty.';
if (empty($_POST['body'])){
$errors[] = 'The body cannot be empty.';
}
}
{
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<div class="subject">
<input name="subject" type="text" id="subject" placeholder="Subject">
<input type="file" name="image" id="image">
<textarea name="message_content" id="message_content" cols="50" placeholder="Message" rows="8" style="resize:none; height: 100px;"></textarea>
<input type="image" src="assets/img/icons/loginarrow1.png" name="send_button" id="send_button" value="Send">
</form>
<?php } ?>
<?php ob_end_flush() ?>
I just did some digging on Google and found this code. I think this should do what you want, but of course you will have to adapt it for your instance.
<?php
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = 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"] < 20000)
&& 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";
}
?>

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