Reputation: 23
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.
Upvotes: 0
Views: 913
Reputation: 196
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);
}
}
}
Upvotes: 1