Getting an issue with the upload image part from the client.
We have a php form called entry where the client will enter some information that we needs to upload an image. After submitting, the information will be saved into an xml file called data.xml and it will be shown on an html file called display.html
The image have to be saved into a folder called upload. We have this code but I think somewhere we are doing it wrong because it's not working.
This is the part for the image:
PHP Code:
$_FILES['file'];
$_FILES["file"]["name"];
$_FILES["file"]["type"];
$_FILES["file"]["size"];
$_FILES["file"]["tmp_name"];
$_FILES["file"]["error"];
if(isset($_POST["file"]['submit'])) {
if ($_FILES["file"]["error"] > 0) {
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else {
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
echo "<br>Stored in: " . "upload/" . $_FILES["file"]["name"];
}
} echo $doc->save($file); } ?>
And in the body html we have this:
<label for="file">Image:</label>
<input type="file" name="file" id="file" action:"entry.php" method:"post" entype:"multipart/form-data"><br>
And also it doesn't save anything in the data.xml file. If I remove this code and leave it as it is, the information are saved in the xml form and the display is working.
Can anyone help please?
Thank you
firstly you need to use form and input type submit.
<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>
also You have a spelling mistake in enctype:"multipart/form-data" you missed c..
Important parts of the code are missing.
Assuming that you've done everything else correctly, and your problem is that it doesn't save anything in the xml file,you should add the below code just after your second echo:
//foreach takes keys and values from all file input types
foreach($_FILES as $item => $val){
$val=$_FILES["$item"]["name"]; //save each file's name to $val
$fileNode=$doc->createElement($item, $val); //create a new file element(file is an image in your case)
$entry->appendChild($fileNode); //add the file element as a child of another element - $entry must be initialized from before
}
Related
I have two PHP files.
index.php allows users to upload an image. The uploaded data is sent to another page i.e. upload.php, where I check certain conditions for example if the uploaded image is really an image and not some other file and if the image already exists on the server etc;
I want to see that my upload.php page redirects back to the index.php page in false conditions. I have seen many of the posts on redirecting, e.g., by using header, which I did. Well, It does redirect. However, there is some part of javascript code, which does not execute. I want to see that alert box on my upload.php page, which upon user interaction redirects to index.php.
Alert box does not appear at the moment, but the page does redirect
My question might be very trivial, but I am a PHP newbie.
index.php
<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>
upload.php
$target_dir = "uploads/";
$file_name=basename($_FILES["fileToUpload"]["name"]);
$target_file = $target_dir . $file_name;
$uploadOk = 1;
if (file_exists($target_file)) {
$uploadOk = 0;
echo "<script language='javascript'>
alert('Sorry, file already exists.Consider Renaming or upload new file');
</script>";
header("Location: http://xx.yyy.zz");
exit;
}
You can replace the 'HTTP header redirect' with a redirection done in javascript.
Remove the code
header("Location: http://xx.yyy.zz");
And replace the echo command with
echo "<script language='javascript'>
alert('Sorry, file already exists.Consider Renaming or upload new file');
window.location = "http://xx.yyy.zz";
</script>";
I want to download text from HTML form to .txt file on my PC. I have tried many ways but nothing works well:
require(fs) doesn't work with the browser, as far as I understand
require(browserify-fs) saves file in VIRTUAL MEMORY (as far as I understand), so it useless for me
last way I found - using PHP script(I found it in net), but it doesn't work, idk why. I have tried to fix it - nothing, I know nothing about PHP
program.php
<?PHP
$title = $_POST["channel0Title"];
$gain = $_POST["channel0Gain"];
$offset = $_POST["channel0Offset"];
$file = fopen('1.txt', 'w');
ftruncate($file, 0);
$content = $title. PHP_EOL .$gain. PHP_EOL .$offset;
fwrite($file , $content);
fclose($file );
die(header("Location: ".$_SERVER["HTTP_REFERER"]));
?>
main.html
<form action="public\scripts\program.php" method="post">
Channel 8 Title:<br><input type="text" name="channel0Title" value="Channel 7"><br>
Gain:<br><input type="text" name="channel0Gain" value="4.000"><br>
Offset:<br><input type="text" name="channel0Offset" value= "6.000"><br>
<input type="submit" id ="submitButton" value="Submit">
</form>
I have a error Cannot POST /public/scripts/program.php
Could you help me please why such a script doesn't work
Or maybe give advice on what language or framework should I use to simplify data transfer between client and server
Thank you in advance!
P.S. I use Node.js, so load program.php as a static file
i'm going to create a gallery website and it will contain a lot of
alboums and photos, videos. now what the right thing: 1-insert the photos and videos in database (if it right tell me how) 2-make an html page for each alboum. thanks in advance.
Configure The "php.ini" File
First, ensure that PHP is configured to allow file uploads.
In your "php.ini" file, search for the file_uploads directive, and set it to On:
file_uploads = On
Create The HTML Form
Next, create an HTML form that allow users to choose the image file they want to upload:
<!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>
Some rules to follow for the HTML form above:
Make sure that the form uses method="post". The form also needs the following attribute: enctype="multipart/form-data". It specifies which content-type to use when submitting the form
Without the requirements above, the file upload will not work.
Other things to notice:
The type="file" attribute of the <input> tag shows the input field as a file-select control, with a "Browse" button next to the input control
The form above sends data to a file called "upload.php", which we will create next.
Create The Upload File PHP Script
The "upload.php" file contains the code for uploading a file:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(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;
}
}
?>
more info :
https://www.w3schools.com/php/php_file_upload.asp
https://sites.google.com/site/prgimr/how-to-upload-image-or-files-into-database-using-php-and-mysql
https://www.youtube.com/watch?v=3OUTgnaezNY
Third option probably is the best. Store them in a cloud storage like AWS S3, Azure Blob Storage or Google Cloud Storage and many other options. They are much cheaper than a database and more versatile then storing as html.
I have uploaded a file in my database below row named 'file_name'. Now when I open my edit form in view mode, the file name does not show (is empty) and when I save the form, the file_name goes blank from the database. I want to save the file in edit form so each time I save the form, the already uploaded file should show in database. I know that value cannot be used for files for security reasons and I also know how to just echo the name of file, but I need to keep the already uploaded file in edit form.
This is my code in edit form in view mode:
<div class="form-group">
<label for="example-text"><?php echo get_phrase('Browse File');?></label>
<input type="file" name="file_name" id = "file_name" class="form-control-file"/><span name="old" id = "old"><?php echo $row['file_name'];?></span>
</div>
This is my code in model:
$page_data['file_name'] = $_FILES["file_name"]["name"];
$oldfile = $_POST['old'];
$file = $_FILES["file_name"]["name"];
if($file != "") {
move_uploaded_file($_FILES["file_name"]["tmp_name"], "uploads/parents_image/" . $_FILES["file_name"]["name"]);
} else {
$file = $oldfile;
$page_data['file_name'] = $this->input->post('file_name');
}
Any advice would be very helpful.
Many thanks. enter image description here
Add
if(isset($_FILES['file_name']) && !empty($_FILES['file_name']){
// your code here
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Trying to allow file upload along with a form that is otherwise working. I cut out the relevant form/input/processing rules. Hopefully someone who is more than ankle-deep in PHP (as I am) can point me in the right direction?
<form name="form-quote" id="form-quote" enctype="multipart/form-data" action="<?php echo $_SERVER['../WPTheme/REQUEST_URI' . '#form-quote'] ?>" method="POST">
<div class="form_labels">
<p><label for="fileupload">Upload File (optional):</label></p>
</div>
<div class="form_inputs">
<input type="hidden" name="MAX_FILE_SIZE" value="5242880" />
<p><input type="file" name="fileupload" id="fileupload" accept=".pdf, .txt, .rtf, .doc, .docx, .xls, .xlsx" style="margin-bottom:2px;"/>
<span style="color:#777;">(pdf, txt, rtf, doc, docx, xls, xlsx, <5MB)</span></p>
</div>
<input type="hidden" name="formtype" id="formtype-quote" value="quote">
<div class="form_labels submit">
<p> </p>
</div>
<div class="form_inputs">
<input type="submit" value="Submit" name="action" class="btn-red" >
</div>
</form>
<?php
//$formerrors is set to false unless one of the validation rules for the OTHER fields fails - no validation on the file upload, although I would like to trim & sanitize it if possible.
if (!($formerrors) && isset($_POST['fileupload'])):
$tmp_name = $_FILES["fileupload"]["temp_name"];
$uploadfilename = $_FILES["fileupload"]["name"];
$savedate = date("mdy-Hms");
$newfilename = "/wp-content/uploads_forms/" . $savedate . "_" . $uploadfilename;
$uploadurl = 'http://' . $_SERVER['SERVER_NAME'] . $newfilename;
if (move_uploaded_file($tmp_name, $newfilename)):
$msg = "File uploaded.";
else:
$msg = "Sorry, your file could not be uploaded." . $_FILES['file']['error'];
$formerrors = true;
endif; //move uploaded file
endif;
?>
Thanks to Alexander's answer below, I was able to modify my validator to work and to achieve my original goals (check for null, and give files unique names before uploading). Here's my "final draft," which is working now.
//Check form errors, check file name not null, rename file with unique identifier to avoid overwriting existing files with same name
if (!($formerrors)) {
$tmp_file = $_FILES["fileupload"]["tmp_name"];
if ($tmp_file != "") {
$savedate = date("mdy-Hms");
$target_dir = "wp-content/uploads/";
$target_file = $target_dir . $savedate . '_' . $_FILES["fileupload"]["name"];
if (move_uploaded_file($tmp_file, $target_file)) {
$msg = "File uploaded.";
} else {
$msg = "Sorry, your file could not be uploaded.";
$formerrors = true;
}//move successful
}//end null check
}//end form errors check
The code you are using above is Javascript. In case you depend on that please change the tags of the post. If not here is a possibility for a PHP-Uploadscript:
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileupload"]["name"]);
if (move_uploaded_file($_FILES["fileupload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileupload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
SOURCE: http://www.w3schools.com/php/php_file_upload.asp
EDIT: The script above has be placed in the file receiving the POST from the form.
The code you posted is a big mess!
Let's try to clarify some basic points...
File-upload mechanism
For file-upload to work you must have a <form> with action attribute addressing the script where you'll check and use the uploaded file.
This script may be the same as the one where the <form> is generated, assumed you take care of the pitfalls that come with this situation.
At a first general glance your current code seems to correspond to the latter case.
But your form action looks weird:
action="<?php echo $_SERVER['../WPTheme/REQUEST_URI' . '#form-quote'] ?>"
As a first intent, if you want to address the same page where you already are, you can simply omit action attribute.
Here you seem to explicitely try the same, adding the precision of #form-quote, but:
This #form-quote has no effect here, since such a hash is made to target a <a>, while it's currently affected to your <form>.
The other part of the url you build is a non-sense mixing REQUEST_URI (which is the name of one of the $_SERVER members) with the hard-core expression of a path in your context.
Anyway all the above doesn't matter, because this end with $_SERVER[...something which is not a known $_SERVER member...], so it actually returns NULL, and somewhat ironically it has the same effect as if you didn't specify action at all!
PHP in a SO snippet
So ou put your code in a snippet, but SO snippets work only with HTML, CSS, and Javascript, so you can't expect it allows to demonstrate how your code is working or not.
Note that at this step, despite the errors mentioned above, we didn't point something which would make your code to fail.
And in your question you didn't mention how it fails!
Uploaded file processing
So looking at your PHP code part, I first note this statement:
$tmp_name = $_FILES["fileupload"]["temp_name"];
where you're looking for temp_name, while the true involved key is tmp_name. This alone is enough to make your code to fail.
Furthermore looking at these two statements:
$uploadurl = 'http://' . $_SERVER['SERVER_NAME'] . $newfilename;
if (move_uploaded_file($tmp_name, $newfilename))
In the 1st one you use $newfilename as the complement of the url you're building, so obviously $newfilename can't target an absolute physical path.
It means that in the 2nd one you try to move_uploaded_file() to a wrong place!
Last point, you currently don't take care of possible errors before trying to use the uploaded file.
You should complete your primary condition like this:
if (!($formerrors) && isset($_POST['fileupload'])) && !$_FILES["fileupload"]["error"])
And if you effectively get some errors and have trouble to understand why, you should also look at this interesting PHP manual page.