form POST erases the view - php

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");

Related

wordpress php post/redirect/get

I build some code to import csv file to MySQL database but run into form resubmission problem( refreshing the page, upload the file again). I am trying to use post/redirect/get pattern to solve this problem but in WordPress it gets kind of tricky since redirect is working correctly.
<?php
/***update csv file ***/
if(isset($_POST["submit"])) //if submit button is pressed
{
if($_FILES['file']['name']) //if file exists
{
$filename=explode('.', $_FILES['file']['name']);//seperate file into filename and csv
if($filename[1]=='csv'){ //if file format is csv
$handle= fopen($_FILES['file']['tmp_name'], "r");
while($data=fgetcsv($handle)){
$sql="INSERT INTO val_in (xxxx,xxxx,xxxx,xxxx,xxxx,xxxx) VALUES(?,?,?,?,?,?)";
//prepared statement
$stmt=mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt,$sql)){
echo "SQL prepared statement error";
}
else{
echo gettype($data[0]);
mysqli_stmt_bind_param($stmt,"issddi",$data[0],$data[1],$data[2],$data[3],$data[4],$data[5]);
mysqli_stmt_execute($stmt);
}
}
fclose($handle);
print "import done";
}
else{
echo "Incorrect file format. Please select a CSV file. ";
}
}
}
<form method='POST' enctype='multipart/form-data'>
<div align="center">
<label>Import CSV File:</label>
<input type="file" name="file" id="csvFile1" />
<input type="submit" name="submit" value="Import" class="btn btn-info" />
</div>
</form>
I tried a few ways to re-direct but haven't found a way to get things working:
wp_redirect( site_url(),303 );
header("Location: http://localhost:8888/dm_toolkit/wordpress/validation-data-input/?file=val_in_test.csv&submit=Import");
header("Location: xxx.php");
wp_redirect(get_permalink($post->ID) . '?success=true');
none of these are working.
In addition, if I put in a "exit" or "die()" in the end, it goes to a page that does not have any of my existing content.
you can attach a action to template redirect hook. There you can check if your post request is set and do your procession and then do redirection.
add_action('template_redirect', 'handle_post_csv_request');
function handle_post_csv_request()
{
if (isset($_POST["submit"])) { //if submit button is pressed
if ($_FILES['file']['name']) { //if file exists
//your code goes here
wp_redirect(site_url(), 303);
}
}
}

How to make only open your php file when refferred from a specific page or file

I want to make my page something like that: when I access my php file hrefferd through a button from my index file it should open successfully. But if I write the php file URL directly in the address bar it must not open. I am new in php.
You can use POST request
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
//Code
}
else
{
echo "Sorry you can't access this page directly";
}
And in your page with the button you can use
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'])?>" method="POST">
<input type="Submit" Value="View Page">
</form>

Change Page Content via jQuery after Uploading File - PHP

I don't know if something like this has already been asked and answered, but since no matter what search query I make, nothing seems to be close to what I am looking to do. I am working on a project where the user will upload a file. Once the file has been uploaded it will show the user a success message as well as some file info. I am trying to keep this all within one page, if possible, but can't seem to get it to work. File gets uploaded, but the info does not show.
Here is something like what I am working with:
<?php
if(isset($_POST['uploadFile']) && isset($_FILES['file'])) {
move_uploaded_file($_FILES['file']['tmp_name'], "files/" . $_FILES['file']['name']);
$message = "\"" . $_FILES['file']['name'] . "\" uploaded successfully...";
}
?>
<html>
<head>
<title>Upload File</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(".uploaded-file-info").hide();
$(".uploadForm").submit(function() {
$(".upload-form").hide();
$(".uploaded-file-info").show();
});
});
</script>
</head>
<body>
<div class="upload-form">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" class="uploadForm" >
<input type="file" name="file" /><br />
<input type="submit" name="uploadFile" value="Upload File" />
</form>
</div>
<div class="uploaded-file-info">
<p><?php echo $message; ?></p>
</div>
</body>
</html>
Like I said, the file gets uploaded, but the form doesn't hide and the file info ($message) doesn't show. Any suggestions?
The problem is the JQuery part :
$(".uploadForm").submit(function() {
$(".upload-form").show();
$(".uploaded-file-info").show();
});
coupled with this line :
<form method="post"
The JQuery part is saying : As soon as the form on the page is submitted, Show the information DIV.
The "Form" part just say : Submit the form.
So, when you click the button, the form is submitted and at the same time, the JQuery is executed. But then the form that you just posted needs to "refresh" the page to get the response back from the server. Basically, the JQuery you wrote display your div while you submit it. Meaning that it will work for a fraction of a second but will display an empty div because the response of the server is not there yet.
What you probably want to do is something like :
When the page loads
And there is content in the uploaded-file-info
Show the info and hide the form.
Add a Style tag with the following :
<style>
.uploaded-file-info {
display: none;
}
</style>
It will always hide the uploaded-file-info when the page loads.
Then, change your JavaScript code with :
<script>
$(document).ready(function() {
if ($('.uploaded-file-info > p').html() != "") {
$(".uploaded-file-info").show();
}
});
</script>
It says that when the page loads, if something is present inside the children of the element "uploaded-file-info", then show it. Otherwise, do nothing.
An easier solution would be to display the block, with php (so on the server side), only if a file was uploaded. No need for JQuery (client side) code.
Remove all the JQuery code and code within "<style>" tags and replace surround your "div class="uploaded-file-info" with an IF like this :
<?php if ($message != '') { ?>
<div class="uploaded-file-info">
<p><?php echo $message; ?></p>
</div>
<?php } ?>
Here's what will happen then:
you post (from your browser) the form
the server receives your post
if there is a file uploaded, it will initiate your "message" variable
and if the message variable exists, the server will put the "div uploaded-file-info" into the response. If not, everything surrounded by the "if" won't be put into the response.
your browser will receive the response and display it on screen.

Form not passing file/picture through submit

I'm working with php/html5 and i'm attempting to upload a file, but $_FILES['picture'] never seems to contain anything. I've been through a lot of posts and looked for common fixes, but none of them seem to work, firstly, the code;
Form;
<form enctype="multipart/form-data" action="decodeQR.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="30000000" />
<input type="file" name="picture" id="picture" value="picture" accept="picture/*" capture>
<input type="submit" value="Upload">
</form>
decodeQR.php;
<?php
include 'header.php';
$upload_status = FALSE;
if(isset($_FILES['picture']))
{
echo 'picture set <br>';
}
else
{
echo 'picture not set <br>';
}
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
if (isset($_FILES['picture']) && file_exists($_FILES['picture']['tmp_name']))
{
$image = $_FILES['picture']['tmp_name'];
//~ Check if image is an image
if (#getimagesize($image))
{
$upload_status = TRUE;
//~ from here you can use yours image as $_FILES['picture']['name'], for example to copy it
move_uploaded_file($image, realpath(dirname(__FILE__)).'/images/'.$_FILES['picture']['name']);
//~ Also be noticed that the image curently is in OS tmp folder and if you dont copy it, it will be deleted after script execution.
}
}
if ($upload_status)
{
echo 'Image successfully uploaded. <br> <img src="images/'.$_FILES['picture']['name'].'">';
}
else
{
echo 'nope.jpg';
}
?>
The output is always;
picture not set
nope.jpg
This means that $_Files['picture'] is not set, and there are no errors in the files array.
As you can see from the code above i have already tried the following fixes;
Added the markup for form enctype; enctype="multipart/form-data"
Added a hidden MAX_FILE_SIZE attribute
Not show in the code, i have tried adding size='30000000' in the file tag
I've checked that the value / name are the same when setting and getting file
I've also checked php.ini to ensure that file_upload is allowed
What could I possibly be missing?
Edit; I've tried this on my desktop and mobile browsers.
I found the solution to actually be a problem between the obvious (Not being able to file upload using ajax), and jquerymobile framework, which uses ajax on it's forms by default.
To fix the problem I added data-ajax='false'
<form enctype="multipart/form-data" action="decodeQR.php" method="post" data-ajax='false'>
The file upload works fine, so i'm posting this answer for anyone who's using jquerymobile and comes across this problem! : )
Have you checked if the request sent by the browser contains the file?
BTW. I'm new here. How do you guys add these "comments" to questions?

Attach file in php and inserting in a database

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

Categories