Upload script in php [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Unable to do File Upload in PHP
I am trying to learn to write file upload script in PHP. I don't know why this doesn't work. Please have a look
<?php
$name=$_FILES["file"]["name"];
if(isset($name)) {
if(!empty($name)) {
echo $name;
}
else {
echo 'Please choose a file';
}
}
?>
It gives an error message Notice: Undefined index: file in
The html part is
<form action="submissions.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<input type="submit" name="submit" value="Submit" /></form>
I am using wamp on Windows. What may be the cause for the error ?

You need to check if the form was submitted before executing your PHP code:
<?php
if (isset($_POST["submit"]) && $_POST["submit"] === "Submit") {
if (isset($_FILES["file"]["name"])) {
$name = $_FILES["file"]["name"];
if(!empty($name)) {
echo $name;
}
else {
echo 'Please choose a file';
}
}
}
?>

The clue is in the error message. The index 'file' doesn't exist in the FILES array. At a guess because you have this code before you've sumitted the form?

check if it exists first,
if(isset($_FILES['FormFieldNameForFile']) && $_FILES['FormFieldNameForFile']['size']>0){ # will be 0 if no file uploaded
then check your use of the field components.
$_FILES['userfile']['name'] # The original name of the file on the client machine.
$_FILES['userfile']['type'] # The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.
$_FILES['userfile']['size'] # The size, in bytes, of the uploaded file.
$_FILES['userfile']['tmp_name'] # The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES['userfile']['error'] # The error code associated with this file upload

Related

How do I validate an image file selection on php?

I have a file input selection as follows in a form which I send data from using the POST Method.
<input type="file" name="inputFile">
I would like to validate that the user has chosen a file and would like to check whether the file is an image file (png,jpg)
I am also getting stuck because a line in my code is generating an error. Why?
'Array key 'inputFile' is undefined'
if (isset($_POST['submit'])) {
$file = $_FILES['inputFile']; //THIS LINE IS GENERATING AN ERROR
}
see : https://www.php.net/manual/en/features.file-upload.post-method.php
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
// basename() may prevent filesystem traversal attacks;
// further validation/sanitation of the filename may be appropriate
$name = basename($_FILES["pictures"]["name"][$key]);
move_uploaded_file($tmp_name, "data/$name");
}
}
see also:
Undefined Array Key error when uploading image on php
it would appear you are looking for $_FILES["inputFile"]["name"] - goodluck
You can use something like:
<input type="file" name="myImage" accept="image/png, image/gif, image/jpeg" />
And specify the formats you want without PHP

PHP uploaded file is not saved and no error is shown

I don't know if my code it's correct, but everything indicates success when sending..
My Form
<form action="upload.php" method="POST" enctype="multipart/form-data">
File: <input type="file" name="file" />
<input type="submit" name="submit" value="Go" />
</form>
My Upload File
<?php
if($_FILES['file']['name'])
{
if(!$_FILES['file']['error'])
{
$valid_file = true;
if($_FILES['file']['size'] > (1024000)) //can't be larger than 1 MB
{
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
}
if($valid_file)
{
/
if(move_uploaded_file($_FILES['file']['tmp_name'],'/files')){
echo "Sent";
}else{
echo "~Error~";
}
}
}
//if there is an error...
else
{
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['file']['error'];
}
}
?>
The message that I get is "Sent", but when I go to check, the folder files is empty :s
My folder structure is:
/files - Here is directory where the files will come
index.php - My form
upload.php - My Logic
One of the issues that I see in your code is that you do not specify a name for your "moved" file:
This line:
move_uploaded_file($_FILES['file']['tmp_name'],'/files')
Should be changed to:
move_uploaded_file($_FILES['file']['tmp_name'],'/files/'.'sampleName'.$extension);// extension is the extension of the file.
I still assume your '/files' path is correct and does not have permission problem.
Same issue arises if your target folder has no write permission.
Use this command to change that:
chmod 775 [folder-name]

Video Uploads in PHP, can't find upload directory?

im using this php video upload script. i have set my directory path to a folder called video which i have created with the same directory as the php file. But i can not find the video being uploaded.
It is not going to the directory i have asked it to? Why is this can someone please help me.
I am not receiving any errors.
Thanks.
HTML:
<form action="upload_videos_process.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="uploadFile" id="uploadFile" />
<br />
<input type="submit" name="submit" value="Upload File" />
</form>
php file:
<?php
//This handles the maximum size for the video file in kbs
define ("MAX_SIZE","500");
//This function reads the extension of the file to ensure that it is an video file
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
//This variable handles an error and won't upload the file if there is a problem with it
$errors=0;
//checks if the form has been submitted
if(isset($_POST['Submit']))
{
//reads the name of the file the user submitted for uploading
$video=$_FILES['video']['name'];
//if it is not empty
if ($video)
{
//get the original name of the file from the clients machine
$video_filename = stripslashes($_FILES['video']['name']);
$video_extension = getExtension($filename);
$video_extension = strtolower($extension);
//if it is not a known extension, we will suppose it is an error and will not upload the file, otherwise we will do more tests
if (($video_extension != "mpeg") && ($video_extension != "avi") && ($video_extension != "flv") && ($video_extension != "mov"))
{
echo '<h1>Unknown extension!</h1>';
$errors=1;
}
else
{
//get the size of the video
$size=filesize($_FILES['video']['tmp_name']);
//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*1024)
{
echo '<h1>You have exceeded the size limit!</h1>';
$errors=1;
}
//give the video a unique name in case a video already exists with the name on the server
$video_name=time().'.'.$extension;
//assign a folder to save the video to on your server
$newname="video/".$video_name;
//verify that the video has been loaded
$copied = copy($_FILES['video']['tmp_name'], $newname);
if (!$copied)
{
echo '<h1>Copy unsuccessful!</h1>';
$errors=1;
}}}}
//If no errors registered, print the success message
if(isset($_POST['Submit']) && !$errors)
{
echo "<h1>File Uploaded Successfully! Try again!</h1>";
}
?>
You've blindly assumed everything's working perfectly. Things fail. First step: check if the upload actually did anything:
if ($_FILES['video']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['video']['error']);
}
The error codes are defined here: http://php.net/manual/en/features.file-upload.errors.php
As well, don't use copy() on the upload file, once you've verified the upload succeeded. There's move_uploaded_file() for a reason - it has extra security checks to ensure that the file hasn't been tampered with on the server, and it actually MOVES the file. copy() can kill performance, especially on large files, since you're duplicating the file, instead of just doing some filesystem housekeeping.
You're also trusting the user to not tamper with the filename. There is NOTHING to prevent a malicious user from doing ren nastyvirus.exe cutekittens.avi before uploading, and your script will happily accept that .exe, because its filename has simply been changed. Use server-side mime-detection (e.g http://www.php.net/manual/en/book.fileinfo.phpenter link description here) to get around this. NEVER trust ANYTHING from a user.
It might be because your php configuration does not allow to upload big files. Try setting
upload_max_filesize = 500M
or even larger than 500M in php.ini & also as ppl mention here in comments, enable the errors
ini_set('display_errors', 1);
ini_set('error_reporting', 8191);

Running php in JavaScript

I am making an application on my server, where the user uploads an image through some HTML combined with javascript.
The user finds an image on the computer through
<form action="uploadimage.php" method="post"
enctype="multipart/form-data">
<label for="file">Filnavn:</label>
<input type="file" name="file" id="file" value="100000" />
Then the point behind the javascript, is to validate on the users image
if(picture_headline.value == "" || picture_uploaded.value == "" || !ischecked)
{
// Don't execute, stay on same site
}
else
{
// execute php and upload image
}
the php is an upload image php script
<?php
// The file is being uploaded into the folder "upload"
$target = "/navnesutten.eu/facebook/uploads/";
// add the original filename of our target path
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
// Moves the uploaded file into correct folder
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
?>
I must say I am a bit confused here, since I have only been working with html, php and javascript for a few days now.
Am I totally off or what?
I found some "simple" examples online, which I put on my server through cuteFTP, but everytime i press upload, the website just sends me to the .php file and says the site doesn't exist.
Like Boann points out you're trying to access a non-existent file in your PHP code ("uploaded" and "uploadedfile" rather than "file" (which is what you named the field in your HTML form)).
But regarding "running PHP from JavaScript": You don't have to. The JavaScript should only return false if the form is invalid. If it's valid you don't need to do anything and the form will submit, in turn running your PHP script:
form.onsubmit = function () {
if (!formIsValid()) {
return false;
}
};
If the form is invalid it won't submit (the return false bit (you could use event.preventDefault() instead)), if it is valid nothing will happen and the form will do what it does (ie submit the data to the server).
Each array key in $_FILES corresponds with the name attribute of a file field in the form, so to match your form it should be 'file' rather than 'uploaded' or 'uploadedfile':
<?php
// The file is being uploaded into the folder "upload"
$target = "/navnesutten.eu/facebook/uploads/";
// add the original filename of our target path
$target = $target . basename( $_FILES['file']['name'] ) ;
$ok=1;
// Moves the uploaded file into correct folder
if(move_uploaded_file($_FILES['file']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['file']['name']). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}

PHP Upload Script not Functioning Properly with New Host

I have set up a php script which creates a directory and uploads a file to that directory. My issue is that when I use the script to create the directory, the file will not upload entirely. I ran the exact same script on a different host and the upload process works just fine. Plus, if I manually create the upload directory and apply chmod 777 via ftp then the transfer works just fine. Could there be some sort of a setting with the hosting provider that needs to be altered to allow the function to work just right?
Here is the upload form:
<form action="/uploadFile.php" method="post"
enctype="multipart/form-data">
<label for="img_preview">Preview Image:</label>
<input type="file" name="img_preview" id="img_preview" />
<br />
<input type="hidden" name="id" value="newDirectory" />
<input type="submit" name="submit" value="Upload Flyer" />
</form>
Here is my PHP script (uploadFile.php):
$thisdir = getcwd();
$new_dir = $_POST['id'];
$full_dir = $thisdir . "/upload/" . $new_dir;
function chk_dir($full_dir) {
if(is_dir($full_dir)) {
echo 'welcome back';
} else {
return mkdir($full_dir);
}
}
chk_dir($full_dir);
chmod($full_dir, 0777);
?>
<?php
//upload image
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["img_preview"]["error"] . "<br />";
}
else
{
}
//set image restrictions
?>
<?php
if ((($_FILES["img_preview"]["type"] == "image/gif")
|| ($_FILES["img_preview"]["type"] == "image/jpeg")
|| ($_FILES["img_preview"]["type"] == "image/pjpeg"))
&& ($_FILES["img_preview"]["size"] < 80000))
{
if ($_FILES["img_preview"]["error"] > 0)
{
echo "Please only upload an image for previewing (jpg or gif)...<br>
Also, check to make sure the filesize is less than 8MB" . $_FILES["img_preview"]["error"] . "<br />";
}
else
{
//check the image into new directory
if (file_exists("upload/". $new_dir ."/". $_FILES["img_preview"]["name"]))
{
echo "It seems that " . $_FILES["img_preview"]["name"] . " already exists.";
}
else
{
move_uploaded_file($_FILES["img_preview"]["tmp_name"],
"upload/" . $_POST['id'] . "/" . $_FILES["img_preview"]["name"]);
echo "image file has transferred successfully!";
}
}
}
else
{
echo "Invalid file please contact for assistance.";
}
?>
Also, when I run the script no errors are produced and the file echos "image file has transferred successfully!" but then when I check for the file in the new location it is completely void. Thank you for your time in this issue.
First of all, your script has a security hole. Never use passed $_POST data to create system directories. And never use 0777 for anything.
The move_uploaded_file() returns false on a failure and you would still get your success message even if it failed (in your code)
Turn on display_errors and error logging and try again.
Looks like your question already contains the answer(the upload works when you create the directory via FTP).
I guess the new server has safe_mode enabled, so it will check the UID of the fileowners on file-operations.
What happens:
your script creates a directory, owner will be the webserver
your script(owner of the script usually is the ftp-user) tries to chmod the directory
the script(owner:ftp) cannot chmod the directory(owner:webserver) , because the UIDs are different.
solution: use ftp_mkdir() for creation of directories.
you have used move_uploaded_file() independently. If it returns false then also sucsess message will be printed.
Try
if ( move_uploaded_file($_FILES["img_preview"]["tmp_name"],
"upload/" . $_POST['id'] . "/" . $_FILES["img_preview"]["name"])) {
echo "sucess";
}else{
echo "fail";
}
After that you will get what is the main problem. Also use debugging point by
print_r($_FILES) before move_uploaded_file().
This may not be the answer to your question, but still it's worth your attention, I hope. Don't rely on the type of the file sent via $_FILES, this is just the mime-type sent by the browser as far as I remember, it can be easily compromized. Use getimagesize() function to get true image type as well as height/width.
Same goes for the source file name, but that shouldn't pose a security hole.

Categories