Right now i'm using the below method to Upload a file to PHP
<form enctype="multipart/form-data" action="http://sserver.com/fileupload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="30000000" />
<input type="hidden" name="filename" value="file_uploaded.gif" />
<input type="hidden" name="username" value="foobar"/>
Please choose a file:
<input name="uploaded" type="file" /><br />
<input type="submit" value="Upload" />
</form>
I read the $_POST and $_FILE in php to complete upload like this.
$target = $_SERVER['DOCUMENT_ROOT']."/test/upload/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
echo $target;
$ok=1;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploaded']['name']). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
My questions is , can i change the above said code (HTML) to an Ajax XMLHttpRequest without changes in PHP.
You cannot send files to the server via AJAX alone. This is because Javascript (when run in a browser) does not have access to the host's file system.
There are ways to make AJAX-style upload boxes using iframes, where the whole page is not reloaded during an upload, but this is not a simple task in itself. jQuery provides a couple of libraries to make this easier.
EDIT As ThiefMaster rightly points out HTML5 provides mechanisms for doing this more neatly.
Related
I'm attempting to build my first form/file uploader (I'm a newb fyi).
I am testing on a local server on my mac, both the form, file handler, and the uploads folder are in the same file directory with one another.
When I select a file using the submit form (test file is 'testFilego.txt' and 3 bytes in size'), i get the following error: http://localhost/PhP_exercises/__tizag/280-php-fileupload-test.php?MAX_FILE_SIZE=2500000&uploadedfile=testFilego.txt. The submit form doesn't seem to connect to the handler (?). I thought the test file would appear in my uploads folder. Help.
This is the submit form:
<form>
<form enctype="multipart/form-data" action="280-php-uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="2500000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
</form>
This is the file hander the form ought to be contacting
<?php
280-php-uploader.php<?php
//This is '280-php-uploader.php'
// Where the file is going to be placed
$target_path = "uploads/";
// Add the original filename to our target path.
//Result is "uploads/filename.extension"
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
As Marco Acierno observed, i'd posted the form inside a form and that seems to have caused the problem.
I have a simple file upload function, but I can't get it to work!
I keep getting and "Error" when trying to use this!
My html-file:
<form enctype='multipart/form-data' action='upload.php'>
<input type='file' name='myfile' />
<input type='submit' value='Upload image' />
</form>
and my upload.php file:
$target = "upload_folder/";
$target = $target . basename( $_FILES['myfile']['name']) ;
if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target))
{
echo "The file was uploaded";
}
else {
echo "Error";
}
..this is one of the first times I use this, so I properly did something stupid..
Any suggestions?
You're missing the method attribute in your form. Try adding it:
<form enctype='multipart/form-data' action='upload.php' method="post">
<input type='file' name='myfile' />
<input type='submit' value='Upload image' />
</form>
There are two methods of uploading a file one is via the POST & other is a PUT request. The method your trying to use is POST. Add method="POST" in the form tag and it will work.
Default in forms is to use GET
<form enctype='multipart/form-data' method="POST" action='upload.php'>
<input type='file' name='myfile' />
<input type='submit' value='Upload image' />
</form>
a) File size is too big, you should change this from php.ini
b) Sometimes some servers require a more precise path for move_uploaded_file than "upload_folder/".
Let's say your php file is in the root and you want the files to go to root/upload_folder. Then do this:
$target = realpath(dirname(__FILE__))."/upload_folder";
$target = $target . "/" . basename( $_FILES['myfile']['name']) ;
$target = "upload_folder/";
you need Write permission for target Folder or Directory.
I want to view data stored in an uploading session but all I get is 'Null', am I going about this the wrong way?
session_start();
if(isset($_POST['submit'])){
$target = "test/";
$target = $target . basename('test') ;
$file = ($_FILES["uploaded"]["name"]);
$key = ini_get("session.upload_progress.prefix") . $_POST[ini_get("session.upload_progress.name")];
var_dump($_SESSION[$key]);
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)){echo "done";}else echo "error";
}
and the html:
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="test" />
<input type="file" name="uploaded" />
<input type="submit" name='submit' />
</form>
You're trying to get upload progress status when upload is already done.
If you want to make it working, then you can for example send your form to iframe and during the upload ask server, using ajax, what is the status.
I would suggest to use it rather as a fallback for older browsers cause currently browsers are supporting ajax upload and you can display upload progress without making additional requests to server and creating some strange hidden iframes ;)
I am trying to upload an image to a server, then get that image name and insert it into mysql database. Before I got to the database bit, the upload isn't working. I have narrowed it down to the fact there is no data in the $_FILES array, when I echo out $imageFileName is it blank.
Here is part of my form:
<form name="addItem" method="post" action="add-new-item.php">
<input name="name" placeholder="Portfolio Item Name" type="text" id="itemName"/><br />
<input type="file" name="imageName" id="imageName" /><br />
</form>
Script, which is part of the same page the form is on:
$target = "images/";
$target = $target . basename( $_FILES['imageName']['name']);
$imageFileName=($_FILES['imageName']['name']);
if(move_uploaded_file($_FILES['imageName']['tmp_name'], $target)){
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}else {
echo "Sorry, there was a problem uploading your file.";
}
$query1="INSERT INTO portfolio_items (item_name,full_size_image) VALUES('$itemName','$itemImage')";
You need to include the following in your <form> tag :
enctype="multipart/form-data"
So it would become :
<form name="addItem" method="post" action="add-new-item.php" enctype="multipart/form-data">
Documented very well here - see the note at the bottom of the first page ...
Below is my code where the user can upload a file. What I want to know is that is there a way so that via server side is there a way to first of all restrict the file formats of the files to jpeg and png only and then when the user clicks on the submit button, if the file format is correct then display an alert on the same page stating "File is correct" else display an alert stating "File is incorrect".
Can somebody please provide coding if they know how to do this. Thank you and any help will be much appreciated :)
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" 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>
A code for a total check of file uploads, you'll have to change $allowedtypes though. (Copied instead of linking because it was from a non-English site)
<?php
if(isset($_POST["submit"])){
$allowedtypes=array("jpg"=>true,"png"=>true,"gif"=>true,"txt"=>true);
$filename = $_FILES['file1']['name'];
$source = $_FILES['file1']['tmp_name'];
$file_size=$_FILES['file1']['size'];
$saveloc = "uploads/" . $filename;
$maxfilesize=1024*1024*10;
$nameext=explode(".",$filename);
if(preg_match('/^[A-Za-z0-9\-\_]{1,}\.[a-zA-Z0-9]{0,4}$/',$filename)){
if(!empty($allowedtypes[strtolower($nameext[1])]) && $allowedtypes[strtolower($nameext[1])]===true){
if($file_size<=$maxfilesize){
if(!file_exists($saveloc)){
if(move_uploaded_file($source, $saveloc)) {
chmod($saveloc,644);
echo "Successful upload. <a href='".$saveloc."'>Fájl megtekintése</a>";
}
else echo "Cannot move";
}
else echo "Existing file";
}
else echo "Too big file";
}
else echo "Not allowed extension";
}
else echo "Only alphanumeric files allowed";
}
else echo "<form method='post' enctype='multipart/form-data' action='secureupload.php'> File: <input type='file' name='file1' /><br /><input
name='MAX_FILE_SIZE' type='hidden' value='10485760' /> <input type='submit' value='Upload' name='submit' /></form>";
?>
You are talking about server side handler and write 'alert'...khm...
If u want to do stuff via server-side, then use php handler
http://php.net/manual/en/features.file-upload.post-method.php
If u want to do stuff via client-side, use javascript events, e.g on change event
<script>
function check() {
var file = document.getElementById('file').value;
var temp = file.split(/\.+/).pop();
alert(temp);
}
</script>
<input type="file" name="file" id="file" onchange="check();" />
You have file extension in temp var.
There are PHP functions to do this. You want to look at mime_content_type and finfo_file. These are built-in PHP commands that allow you to interpret that actual file type of a file being uploaded. You can then filter the mime types to only .gif/.jpg/etc. You want to check the mime types over the file name because the file name can be changed to mask the actual file type. If you want code samples, there are plenty on those pages as well as some excellent user-provided alternatives.
Something like this at the top of your file should work:
<?php
foreach ($_FILES as $file)
{
$tmp = explode(".", $file["tmp_name"]);
if (!in_array($tmp[count($tmp)-1], array("jpeg", "png"), true))
die("<script>alert('File is incorrect');</script>");
}
echo "<script>alert('File is correct');</script>";
?>