wordpress php post/redirect/get - php

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

Related

My photo upload script is not working in php

<?php include('header.php');
include ('config.php');
if(isset($_POST['submit_image'])){
$imgname=$_FILES["myimage"]["name"] ;
$target="ProfileImages/";
$filetarget=$target.$imgname;
$tempname=$_FILES["myimage"]["tmp_name"];
$result = move_uploaded_file($tempname,$filetarget);
if($result){
$id=$_SESSION['id'];
$caption=$_POST['caption'];
$q="INSERT into `images` (id,path,caption) VALUES ('$id','$filetarget','$caption')";
$res=mysqli_query($con,$q);
if($res)
{
$msg="Photo Uploaded Sucessfully..";
$_SESSION['msg']=$msg;
header('location:profile.php');
}
}
else{
$msg="Error Not Uploaded...Try Again";
$_SESSION['msg']=$msg;
header('location:profile.php');
}
}
?>
<form method="POST" enctype="multipart/form-data">
<h2><u>Select Image</u></h2><br><input type="file" name="myimage"><br>
<h2><u>Caption</u></h2><br>
<textarea rows="4" cols="25" name="caption"></textarea>
<input type="submit" name="submit_image" value="Upload">
</form>
Heading
I was trying to upload pictures through this code, but after some time I checked it was not working...Can any of you help me how to fix this?
Turn on the PHP Error Reporting!
Isolate the working script and try to find out where the issue is. Make sure if:
the parser enters the first if
is the $filetarget valid file name
was the file move successful
was the query successful
is the redirection to valid page
If you do not have debugger, disable the header('location:profile.php'); to stay on the page and see errors and/or print testing messages such as echo "I am here on line ".__LINE__; to make sure the parser is in.

PHP submission not working with either $_POST or $_REQUEST

I have been trying to get the PHP code to submit an email to a mysqlDB, but for some reason it is not working:
This is the form code in the HTML
<form class="header-signup" action="registration.php" method="post">
<input name="email" class="input-side" type="email" placeholder="Sign up now">
<input type="submit" value="Go" class="btn-side">
<p class="hs-disclaimer">No spam, ever. That's a pinky promise.</p>
</form>
For the PHP, I did the following (DB connection infos set to xxxxx):
<?php //start php tag
//include connect.php page for database connection
$hostname="xxxxxx";
$username="xxxxxx";
$password="xxxxxx";
$dbname="xxxxxx";
mysql_connect($hostname,$username, $password) or die ("<html><script language='JavaScript'>alert('Unable to connect to database! Please try again later.'),history.go(-1)</script></html>");
mysql_select_db($dbname);
//Include('connect.php');
//if submit is not blanked i.e. it is clicked.
If(isset($_POST['submit'])!='')
{
If($_POST['email']=='')
{
Echo "please fill the empty field.";
}
Else
{
$sql="INSERT INTO MailingList (MAIL) VALUES('".$_POST['email']."')";
$res=mysql_query($sql);
If($res)
{
Echo "Record successfully inserted";
}
Else
{
Echo "There is some problem in inserting record";
}
}
}
?>
Do you know what might be the problem?
The php file is in the same folder than the webpage.
Thanks for your time
Regards
$_POST['submit']
does not exist, you have to specify the name for the submit button
<input type="submit" name="submit"........>
Please try this
You could also use this conditional for a POST request
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
And check the input with a var_dump($_POST); to see if the value exists in the array.
This is only if you're expecting one form. If you want multiple forms on the page you could make use of naming your submit button in the HTML code
<form class="header-signup" action="registration.php" method="post">
<input type="submit" name="action1" value="Go" class="btn-side">
</form>
You could also use this if you set an name on the submit button
if(isset($_POST['action1']))
{
var_dump("hit");
}

Two PHP pages to pass form data to the same target file

I have a Customer Details PHP page. To get to this page, the user either signs up with new details on signup.php or they log in on login.php.
Ive been told the best way to submit data and be redirected to the correct page is to use action="details.php" in the form, and then at the start of the details.php file use the values from the $_POST array to populate my SQL database.
However, I need to do the same sort of thing with the login.php code, so at the top of details.php there will be the code to enter the form data from signup.php and the verifying code from login.php.
Surely there is a way of doing the data submission directly from signup.php so there isnt two sets of PHP in the details.php file? If not how do i differentiate so that login only uses the login code and signup uses the submit code?
Common practice is to have PHP check for form data+possible redirect and after that form print
Example: (my common usage)(i merged login&signup into one file)
<?php
$error = "";
if( !empty($_POST['signup']) ){
//do signup
//$signup = assign true/false whether sign up was successfull or not
if( !$signup ){ //if signup wasnt successfull generate error
$error = "Sign up error.";
}
}
if( !empty($_POST['login']) ){
//do login
//$login = assign true/false whether login was successfull or not
if( !$login ){ //if login wasnt successfull generate error
$error = "Log in error.";
}
}
if( empty($error) ){
//there were no errors
header("Location: details.php"); //redirect to details.php
exit(); //send nothing else!
}
?>
<div class="error"><?php if(!empty($error)){ echo htmlspecialchars($error); /*escape*/ } ?></div>
<form action="#" method="POST">
<input type="hidden" name="signup" value="yes">
<!-- ...some other input fields... -->
<button type="submit">Sign Up</button>
</form>
<br>
<form action="#" method="POST">
<input type="hidden" name="login" value="yes">
<!-- ...some other input fields... -->
<button type="submit">Log In</button>
</form>
You could set a hidden field on each page as below:
<input type=hidden name='referrerpage' value='signup'>
AND
<input type=hidden name='referrerpage' value='login'>
and do:
if ($_POST['referrerpage']=='signup'){
//do this
} else{
//do this
}

php showing error even after the data has been inserted to the database

In Php I am doing a file upload with some data insert
My form looks like this
<form id="formID1" method="post" action="'.$_SERVER['REQUEST_URI'].'" enctype="multipart/form-data">
<label for="">'.$this->l('Add Store Type').'</label>
<input type="text" name="store_type" />
<label for="">'.$this->l('Upload Your Custom Icon').'</label>
<input type="FILE" name="custom_icon" id="custom_icon" />
<input type="submit" name="store_config" value="'.$this->l('Add Store Configuration').'" class="button" />
<form>
For uploading images I am doing a folder with 777 permission on it.
$uploaddir=dirname(__FILE__)."/storeconfig";
if(!file_exists($uploaddir)) {
mkdir($uploaddir, 777, true);
}
$tmpName=$uploaddir."/";
Now for inserting values I am doing this code.
if(isset($_POST['store_config'])) {
global $uploaddir;
$custom_icon_name = time().$_FILES['custom_icon']['name'];
$allowed_extensions = array('gif','jpg','png');
$path_info = pathinfo($custom_icon_name);
if( !in_array($path_info['extension'], $allowed_extensions)) {
echo "Incorrent file extension, Please Use png,jpg or gif files only";
} else {
if(mysql_query('INSERT INTO `'._DB_PREFIX_.'store_config` (`store_config_id`,`store_type`,`custom_icon`) VALUES ("","'.$store_type.'","'.$custom_icon_name.'") ')) {
if(move_uploaded_file($_FILES['custom_pin']['tmp_name'],$tmpName.$custom_icon_name)) {
echo "Settings updated successfully";
} else {
echo "You Have Some Errors";
}
}
}
}
Here the values are storing into the database successfully after doing click on button Add Store Configuration but still I am getting the error You Have Some Errors which I have set in my form.It should show Settings updated successfully. Can someone tell me how this is error is coming?

form POST erases the view

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

Categories