I am working on a PHP project, in which I need to store a path of an image when user select an image from open dialog box from a specified directory. How can I do this? I don't know how to open the Open/Browse dialog box and how to get that path in PHP/javascript. And I want that my other form data don't flush when I open the Open/Browse Dialog.(I want to put image file's path that user has selected in my database, so I can reduce my database size.)
You can use file uploading forms with html and send the form to your PHP file to handle the file contents. When a file is sent to the server it is stored in a temporary location.
W3Schools has a good tutorial on this, the HTML becomes:
<html>
<body>
<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>
</body>
</html>
and the PHP:
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_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 "Stored in: " . $_FILES["file"]["tmp_name"];
}
?>
http://www.w3schools.com/php/php_file_upload.asp
You can put a form element by using <input type="file">
If you only want the path without uploading the file. You can use javascript.
If you post the data to the server file's info will be available to PHP but also the file will be sent to server as well.
Check the Javascript File Api examples here if you want more ..
http://www.html5rocks.com/en/tutorials/file/dndfiles/
<input type="file">
no? or i'm something missing?
For dotNetAddict (if they are still interested) and any others similarly interested, try the following link for a good explanation of how to obtain the path to a file....
http://www.w3schools.com/jsref/prop_fileupload_value.asp
Related
I'm using Form-Submit(website for sent message to gmail without back-end) and File upload. is it possible to upload multiple attachment at a time in form-submit
Please help me i am using html form....And I want to know...It's working or not if yes ...How can I upload or send multiple attachment through form-submit cause single file already working....And I am also use the files attribute in file attribute place....But it's only select the multiple times file not sent in my mail ...Only sent one attachment at a time....Hlp me
The following code is a very basic mechanism of uploading files. Nowadays there are more advanced libraries that you have to search for.
<?php
if(isset($_POST['upload'])){
$numberOfFiles = sizeof($_FILES["song"]["name"]);
echo "<br>Number of selected files: ".$numberOfFiles.'<br>';
for($i=0; $i<$numberOfFiles; $i++){
$tempName = $_FILES['song']['tmp_name'][$i];
$desPath = realpath(dirname(__FILE__))."/" . $_FILES['song']['name'][$i];
if (file_exists(realpath(dirname(__FILE__))."/" . $_FILES['song']['name'][$i]))
{
echo $_FILES['file']['name'] . " already exists. ";
}
if(!move_uploaded_file($tempName, $desPath))
{
echo "File can't be uploaded";
}
}
}
?>
<form method="post" action="<?php echo 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>" enctype="multipart/form-data">
<input type="file" multiple="multiple" name="song[]" accept="audio/mpeg3"><br></br>
<div class="uploadbtn" align="center">
<input type="submit" name="upload" value="Upload"></div>
</form>
I hope it helps.
I had been stuck on this problem for about 3 days straight.
When i upload an image to php it gives me an error Undefined index: file.
I read many other questions i made sure i have enctype="multipart/form-data" in my form tag, i made sure each image name has name="file[]" but no luck, But when i try doing the html and php within 1 single file, everything works perfectly. But when i split the php from the html then it stops working.
There should not be any problem on the php side, because i can get it working if html is within the php.
Html
<form enctype="multipart/form-data" id="submitform" class="form-horizontal" action="submitlisting.php" method='post' >
<p id="result"></p>
<span class="btn btn-file"><input type="file" name="file[]" id="file[]"></span>
Remove
<button id="submit" type="submit" value="Submit" name="submit" class="btn btn-success" style="width:100px;">Submit</button>
</div>
</div>
</form>
Php:
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
ob_start();
session_start();
include 'connect.php';
$username=$_SESSION['username'];
$userid=$_SESSION['id'];
for($i=0;$i<count($_FILES["file"]["name"]);$i++)
{
$supported_image = array(
'gif',
'jpg',
'jpeg',
'png');
$path = $_FILES["file"]["name"][$i];
$ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
if ((!in_array($ext, $supported_image) )&&($_FILES["file"]["size"][$i] > 1000000))
echo "Picture[$i]". "either empty or File format incorrect, You can change the pictures later<br>";
else{
if ($_FILES["file"]["error"][$i] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"][$i] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"][$i] . "<br>";
echo "Size: " . ($_FILES["file"]["size"][$i] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"][$i] . "<br>";
echo "<br>";
if (file_exists("rentaid.info/Bootstraptest/rent" . $_FILES["file"]["name"][$i]))
{
die($_FILES["file"]["name"][$i] . " already exists please add another file, or change the name ");
}
else
{
$photo=$_FILES["file"]["name"][$i];
move_uploaded_file($_FILES["file"]["tmp_name"][$i],
"Bootstraptest/rent/$photo");
echo $photo."  added</br>";
mysqli_query($con,"INSERT INTO listingpic (pic,listingid,userid) VALUES
('$photo','$form_insert_id','$userid');") or die(mysqli_error());
echo"Listing added";
}
}
}}
}
?>
Its calling the error right at the first time the $File enters the php, in the for loop condition for($i=0;$i<count($_FILES["file"]["name"]);$i++)
Debugging the problem usually makes it go away.
In your php file input following lines:
echo '<pre>';
print_r($_FILES);
echo '</pre>';
This will output whatever comes in from your form.
Also, a good programming practice is to first check the values you get from your form. What if someone doesn't load a file to the form? Then, trying to loop through files will cause error.
So,
if(isset($_FILES['file'])) {
// do whatever
}
And, lastly, change the following to real path, relative the root - /
action="submitlisting.php"
action="/submitlisting.php"
You are most likely openning the form in the browser. Assuming some local virtual host like 'mytest.com' or maybe 'localhost' is used - your form is open at 'mytest.com/myform.php' and form handler at 'mytest.com/submitlisting.php' the action attribute of the form should be '/submitlisting.php'. If the scrpit is somewhere else - put that path there, relative from the root of the site.
EDITED:
Try adding MAX_FILE_SIZE to your form as a hidden input.
To do that edit your HTML part:
<form ...>
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
...
<input type="file" ..>
Hidden input before any actual file input fields.
this is a normal HTML method of attaching a file.
form enctype=<"multipart/form-data" action="savefile.php" method="POST" name="myform">
Send this file:
input name="myfile" type="file" onchange="document.forms['myform'].submit() ;"
</form>
savefile.php
move_uploaded_file($_FILES["myfile"]["tmp_name"],
"upload/" . $_FILES["myfile"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["myfile"]["name"];
it works perfectly, my difficulty is that when I attach a file and it sends when I refresh the page, the file I attached still remains in the attachment, how can I clear it so it shows "No chosen file"
You need to redirect the user with
header("Location: yourpage.php");
Also, submitting your form that way might not work on every browser.
<input name="myfile" type="file" onchange="document.forms['myform'].submit() ;" />
And JAVASCRIPT
var myInput = $("#input[name='myfile']");
function resetInput(){
myInput.replaceWith( myInput.val('').clone( true ) );
};
Call resetInput() after the upload.
Ripped and adapted From this thread
So I am trying to do a basic upload via an HTML form and a simple php script, but the move_uploaded_file function always returns false. I have run "chmod 777" on the directory (I will deal with safety more when I actually get this to work) and the "upload" directory is in the htdocs folder (actually /var/www in Ubuntu Server and Linux Mint).
Here is the form:
<html>
<body>
<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>
</body>
</html>
...and upload_file.php...
<?php
if ($_FILES["file"]["error"] == 0){
if (file_exists("upload/" . $_FILES["file"]["name"])){
echo $_FILES["file"]["name"] . " already exists. ";
}else{
if(move_uploaded_file($_FILES["file"]["tmp_name"],"/var/www/upload/" . $_FILES["file"]["name"])){
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}else{
echo "Failed to move uploaded file";
}
}
}else{
echo "Return Code: " . $_FILES["file"]["error"];
}
?>
When I try to upload a small JPEG, I get "Failed to move file". Any thoughts?
Your script needs to be able to write to the destination directory, which in this case would be /var/www/upload/ (is that the directory where you changed the permissions?). Also you are using the client's local name which could be a possible problem and security issue (not necessarily the reason here though).
When i found out that my OS was the problem i wanted to destroy my pc.
chmod ugo+rwx yourfoldername
With this way you give permission to everyone to write/read/delete to your folder.
Let me explain what i am hope to acomplish:
I want to allow my users to upload a image as avatar.
I found many php upload tutorials but i don't know hoy to upload the avatars as user_id.ext in /avatars folder.
I hope i was clear, thanks.
In any upload script, you go through a few basic steps. First, you get data from $_FILES telling you where the temporary upload file is. You validate the file based on something to make sure it's not evil/malicious/wrong. Then you rename it and move it somewhere useful. In your last step, when you move the image to where it's going, take that opportunity to name the file as you like. If you're dealing with a user's account it should be trivial to get the username, id, middle name, etc and use that to set the file's name.
This script gets the uploaded file and save it as /avatars/$user_id.ext, $user_id retrieved from POST:
<?php
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"], "/avatar/{$_POST['user_id']}.ext");
echo "Stored in: " . "/avatar/{$_POST['user_id']}.ext";
}
?>
And this is the form:
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="hidden" name="user_id" value="<?php echo $user_id ?>">
<input type="submit" value="submit"></form>