Attach file in php and inserting in a database - php

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

Related

I'm using FormSubmit and File upload. is it possible to upload multiple attachment at a time in formsubmit

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.

Open/Browse Dialog box in php/javascript?

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

upload image form in ajax doesn't work

Hello I would like to upload some images to my server. It works when I'm not loading the page with ajax.load into another page. So with a direct link to it it works fine. But I would like to click on a link, open the upload form and upload the picture (all in one window). Is this because the page is refreshing before uploading or is it another problem? don't know how to solve this.
code:
<?php
include('includes/connect.php');
if(isset($_POST['uploadImg'])){
$extension = end(explode(".", $_FILES["file"]["name"]));
$name = $_FILES["file"]["name"];
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
mysql_query("INSERT INTO images (itemID,imgPath,imgName,imgExtension,imgAlt) VALUES (".$_POST['itemNumber'].",'upload','".$name."','".$extension."','".$name."')")or die('kan niet uploaden'.mysql_error());
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Uw afbeelding is toegevoegd aan item".$_POST['itemNumber'];
echo "<a id='uploadNew' href='#'>Nog een item uploaden</a>";
}
mysql_query("INSERT INTO images (itemID,imgPath,imgName,imgExtension,imgAlt) VALUES (".$_POST['itemNumber'].",'upload','".$name."','".$extension."','".$name."')")or die('kan niet uploaden'.mysql_error());
}
?>
<form method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
Toevoegen aan:
<select name="itemNumber">
<?
$result = mysql_query("SELECT * FROM items");
while($row = mysql_fetch_array($result))
{
echo '<option name="itemVal" value="'.$row['itemID'].'">'.$row['itemTitle'].'</option>';
echo "<br />";
}
?>
</select>
<input type="submit" name="uploadImg" value="submit" />
</form>
The problem comes from the fact that the form is sent to the parent page before the AJAX is loaded. The Partial page that you posted is retrieved through a second HTTP request and doesn't have any POST parameters set.
Your best bet would be to add the php script in the parent page from which the AJAX is loaded. Also specify a "target" attribute in your form element so you keep track of which server page is handling the request.
ajax not directly upload your image, you should have to use some plugin to upload the image,
Previous i have used this plugin (ajax.form) to instant image upload.
follow the link, in this link a simple example that how to use this plugin and upload an image.. http://blog.webtech11.com/2012/03/18/ajax-based-instant-image-upload.html

How to php upload a image with a predefined custom name/

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>

form POST erases the view

How do I get my very simple view's html items to re-appear after a form's POST?
I lay out the html controls below, then when the user selects the
'Upload' submit button, a file is uploaded (successfully) but all
the previously-laid-out view elements disappear. Again, the upload
of the file works fine. It's just that the html controls I displayed
on index.php vanish when the form gets uploaded and the browser window
is blank.
How do I get my very simple view back after a form's POST?
THIS IS index.php:
<body>
<img src="/theWebsite/images/banner2.jpg" /img>
<br />
<input type="button" value="Play" onclick="showAnAlert(){}" />
// other buttons and text field html elements not shown
<form enctype="multipart/form-data" action="file-upload.php" method="POST">
Please choose a file: <input name="uploaded" type="file" /><br />
<input type="submit" value="Upload" />
</form>
</body>
Here is file-upload.php:
<?php
$target = "upload/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$uploadingFile = $_FILES['uploaded']['tmp_name'] ;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
// I thought the problem was this 'echo' but the main view still goes blank after
// I commented this out here....
//echo "The file ". basename( $_FILES['uploaded']['name']). " has been uploaded";
}
else {
// echo "errmsg"
}
?>
After posting your form to file-upload.php, you do not redirect it back to index.php where the HTML resides. You need to call a redirect after doing your form processing:
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
// I thought the problem was this 'echo' but the main view still goes blank after
// I commented this out here....
//echo "The file ". basename( $_FILES['uploaded']['name']). " has been uploaded";
// Redirect back....
header("Location: http://www.example.com/index.php");
// Always call exit() right after a redirection header to prevent further script execution.
exit();
}
else {
// echo "errmsg"
}
You may also need to redirect in your error condition. In that case, put the header() call at the very end.
The file-upload.php file needs to either redirect the user back to your index.php once the upload is complete OR needs to include the original index.php file at the bottom.
I vote that you either do a redirect back OR simply remove the file-upload.php file altogether and handle it in your index.php file.
For your form's action, specify the $_SERVER['PHP_SELF'] variable:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
Then be sure to add the logic to handle processing the form in the same .php file that outputs the html for your form. Another method is to have a header() call that redirects to your form again:
<form action="process_form.php" method="POST">
then, in process_form.php:
header("Location: http://mydomain.com/form_page.html");

Categories