POST Data is not sent - php

I'm having some weird issues with this code block, it's a little school project, going well so far but the form at the bottom is not returning any post data. the var_dump($_POST); never shows any post data being submitted from this particular form.
I just cannot understand why, been struggling with it for so long.
Here's the code, i couldn't understand to format it on this page, adding 4 indents for every line seemed a bit tedious.
<?php session_start();
require_once'user.class.php';
require_once 'posts.class.php';
require_once'comments.class.php';
$posts = new Posts($user->getID(), $db);
$comment = new Comments($user->getID(), $db);
include_once'includes/header.php';
include_once'includes/nav.php';
?>
<h2><br></h2>
<?php
include_once'includes/intro.php';
// CONTENT
$post = $posts->showPost($_GET['id']);
$title = $post['title'];
$content = $post['content'];
$created = $post['timestamp'];
echo "<section> <article class='blogPost'> <header> " . " <h2>$title</h2> " . "<p> Posted on $created <a href ='#comments'> X comments</a></p></header>" . "<p>$content</p>" . "</article> </section>";
var_dump($_POST);
if (isset($_POST['submit_comment']) && isset($_POST['id_comment'])) {
echo "Kom seg inn i ifen";
$pid = $_GET['id'];
$comment->newComment ($db, $user->getID(), $pid, $_POST['id_comment']);
header ("location: showPost.php?id=$pid");
exit ();
}
?>
<form name='commentform' action='showPost.php?id=<?php echo $_GET['id'];?>' method='POST'>
<h3>Post a comment</h3>
<p>
<label for='id_comment'>Comment</label>
<textarea name='id_comment' id='id_comment' required></textarea>
</p>
<p><input style='width: 100%;' type='submit' name='submit_comment' value='Legg til kommentar' /></p>
</form>
<?php
include_once'includes/asidefooter.php';
?>
Thanks for all help!

It looks like if post is data present, the user is redirected. You will only see the post data at the time the form is submitted, and the redirect will cause another page load and the data won't be present anymore.
Can you see the post data if you comment out the redirect, with:
//header ("location: showPost.php?id=$pid");
//exit ();

Something is causing a redirect, which is turning the request into a GET. If you're trying to submit to a index.php then don't forget the ending slash.

Related

PHP Myqsli Form automatically returning to previous page in Chrome but not in Edge?

I have a form that submits fields to a database using mysqli that was working perfectly; however, I pulled up the form page in Chrome and tried to submit a new row to the db, only for the page to go back to the previous page when I tried to click on the form's text-areas. I tried clearing all of my browser history (cache, cookies, etc.) and asked a friend to try it on their Chrome browser, with the same result.
The kicker? It works in Edge. Makes no sense.
I've gone through the code and can't find any missing <'s or quotes, etc. Everything was working fine and I can't imagine why it would suddenly start doing this in Chrome.
(Note: I know this code is clunky and vulnerable to SQL injection, but I don't have any users/sensitive data to protect, for the moment. Also, I made no changes to head.php or any code (that I can recall), just confused as to why it would suddenly start redirecting me back to notebook.php as soon as I click on a text area in Chrome but not in Edge.)
Notebook_add.php
$con = #mysqli_connect('localhost', 'root', 'pass', 'db');
if (!$con) {
echo "Error: " . mysqli_connect_error();
exit();
}
?>
<body>
<div class="wrapper">
<h1>Post Comments</h1>
<?php
include ('navbar.php');
?>
<br>
<form name="noteworthy" METHOD=POST action=<?php echo $_SERVER['PHP_SELF']; ?>>
<br>
Title: <input type="text" name="title" id="$title" size="50"> <br>
Link: <input type="text" name="link" id="$link" size="50"><br>
Description: <TEXTAREA NAME="description" id="$description" ROWS="5" COLS="30"></TEXTAREA><br>
<Input type="submit" name="enter" id="$enter" value="enter">
</form>
<?
echo $submitted = date("Y-m-d");
?>
<?
$title = $_REQUEST['title'];
$link = $_REQUEST['link'];
$description = $_REQUEST['description'];
$enter = $_REQUEST['enter'];
if(isset($_REQUEST['enter'])){
$submitted = date("Y-m-d");
$sql = "INSERT INTO notes (title, link, description, submitted) VALUES ('$title','$link','$description','$submitted')";
}
if(mysqli_query($con, $sql)){
echo "Records inserted successfully.";
print "<meta http-equiv='refresh' content='0; url=http:notebook.php' />";
}
// Close connection
mysqli_close($con);
?>
<div class="push"> </div>
</div>
<?php
include 'footer.php';
?>
</body>
So what happened was that I had added a new menu item in my navbar.php and forgot to close the link tag (e.g., " New menu item "). This made the entire php form into a link, so whenever I anywhere on it under my navbar I was returned to the previous page.
It is interesting that this didn't happen in Edge; perhaps there is some feature in Edge that automatically closes rogue tags.
Anyway, thanks for responding. #Smith, thanks for the tip, I'm using the php head featured/location function instead of meta-refresh now.

How to stay on HTML form page and not navigate to php form action page

I am working on a html form which will connect to a database using a php script to add records.
I have it currently working however when I submit the form and the record is added , the page navigates to a blank php script whereas I would prefer if it when submitted , a message appears to notify the user the record is added but the page remains the same. My code is below if anyone could advise me how to make this change.
Html Form :
<html>
<form class="form" id="form1" action="test.php" method="POST">
<p>Name:
<input type="Name" name="Name" placeholder="Name">
</p>
<p>Age:
<input type="Number" name="Age" placeholder="Age">
</p>
<p>Address
<input type="text" name="Address" placeholder="Address">
</p>
<p>City
<input type="text" name="City" placeholder="City">
</p>
</form>
<button form="form1" type="submit">Create Profile</button>
</html>
PHP Database Connection Code :
<html>
<?php
$serverName = "xxxxxxxxxxxxxxxxxxxxxxxx";
$options = array( "UID" => "xxxxxxxxx", "PWD" => "xxxxxxxx",
"Database" => "xxxxxxxxxx");
$conn = sqlsrv_connect($serverName, $options);
if( $conn === false )
{
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
$Name = $_POST['Name'];
$Age = $_POST['Age'];
$Address = $_POST['Address'];
$City = $_POST['City'];
$query = "INSERT INTO [SalesLT].[Test]
(Name,Age,Address,City) Values
('$Name','$Age','$Address','$City');";
$params1 = array($Name,$Age,$Address,$City);
$result = sqlsrv_query($conn,$query,$params1);
sqlsrv_close($conn);
?>
</html>
Typically your action file would be something like thankyou.php where you'd put whatever message to the user and then maybe call back some data that was submitted over. Example:
Thank you, [NAME] for your oder of [ITEM]. We will ship this out to you very soon.
Or this file can be the the same page that your form resides on and you can still show a thank you message with some javascript if your page is HTML. Something like:
<form class="form" id="form1" action="test.php" method="POST onSubmit="alert('Thank you for your order.');" >
I am taking into consideration that your PHP Database Connection Code snipplet that you posted above is called test.php because you have both connecting to the data base and inserting data into the database in one file.
Taking that into consideration, I think the only line you are missing, to return you back to to top snipplet of code that I shall call index.php would be an include statement just after the data has been added to the database
$query = "INSERT INTO [SalesLT].[Test]
(Name,Age,Address,City) Values ('$Name','$Age','$Address','$City');";
$params1 = array($Name,$Age,$Address,$City);
$result = sqlsrv_query($conn,$query,$params1);
echo "Data added";
include 'index.php'; //This file is whatever had the earlier form
Once you hit the submit button on your form, test.php is called, your data is handled and passed back to index.php.
N.B:
The other thing i should mention is to make it a habit of using mysqli_real_escape_string() method to clean the data that is in the $_POST[]; because in a real website, if you don't, you give an attacker the chance to carry out SQL injection on your website :)
you said page is coming blank and data is saved so i assumed that there are two files one which contains form and another which contains php code (test.php).
when you submit the form you noticed that form is submitted on test.php
and your test.php has no any output code that's why you are seeing blank page.
so make a page thankyou.php and redirect on it when data is saved.header('Location: thankyou.php'); at the end of file.
Put this in form action instead of test.php
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> method="post">
Put your php code at top of the page.
$Name = $_POST['Name'];
This is step closer to being a safer way to posting into your db as well.
$Name =mysqli_real_escape_string( $_POST['Name']);
I like the jscript Alert from svsdnb to tell user data was successfully added to db.
This is not intended to be an out of the box solution; it's just to get you pointed in the right direction. This is completely untested and off the top of my head.
Although you certainly could do a redirect back to the html form after the php page does the database insert, you would see a redraw of the page and the form values would be cleared.
The standard way to do what you're asking uses AJAX to submit the data behind the scenes, and then use the server's reply to add a message to the HTML DOM.
Using JQuery to handle the javascript stuff, the solution would look something like this:
HTML form
<html>
<!-- placeholder for success or failure message -->
<div id="ajax-message"></div>
<form class="form" id="form1">
<p>Name: <input type="Name" name="Name" placeholder="Name"></p>
<p>Age: <input type="Number" name="Age" placeholder="Age"></p>
<p>Address: <input type="text" name="Address" placeholder="Address"></p>
<p>City: <input type="text" name="City" placeholder="City"></p>
<!-- change button type from submit to button so that form does not submit. -->
<button id="create-button" type="button">Create Profile</button>
</form>
<!-- include jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- ajax stuff -->
<script>
// wait until DOM loaded
$(document).ready(function() {
// monitor button's onclick event
$('#create-button').on('click',function() {
// submit form
$.ajax({
url: "test.php",
data: $('#form1').serialize,
success: function(response) {
$('#ajax-message').html(response);
}
});
});
});
</script>
</html>
test.php
<?php
// note: never output anything above the <?php tag. you may want to set headers.
// especially in this case, it would be better to output as JSON, but I'm showing you the lazy way.
$serverName = "xxxxxxxxxxxxxxxxxxxxxxxx";
$options = array( "UID" => "xxxxxxxxx", "PWD" => "xxxxxxxx", "Database" => "xxxxxxxxxx");
$conn = sqlsrv_connect($serverName, $options);
if( $conn === false ) {
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
$Name = $_POST['Name'];
$Age = $_POST['Age'];
$Address = $_POST['Address'];
$City = $_POST['City'];
// if mssql needs the non-standard brackets, then put them back in...
// note placeholders to get benefit of prepared statements.
$query = "INSERT INTO SalesLT.Test " .
"(Name,Age,Address,City) Values " .
"(?,?,?,?)";
$params1 = array($Name,$Age,$Address,$City);
$success = false;
if($result = sqlsrv_query($conn,$query,$params1)) {
$success = true;
}
sqlsrv_close($conn);
// normally would use json, but html is sufficient here
// done with php logic; now output html
if($success): ?>
<div>Form submitted!</div>
<?php else: ?>
<div>Error: form not submitted</div>
<?php endif; ?>

variable in header location doesnt work in iframe?

Hi guys i am doing a personal project which i want to use on my small business, i am not that rich thats why i cant afford to hire a developer to do it for me :( my problem is that variable seems not to work if its called on an iframe, ok just like i said im not a pro developer so even on terms im not sure what to use so i will just explain on whatever i can and i hope some one can catch up with me.
an iframe is called on uikit modal, url on iframe have parameters
file is called firstreminder.php and this is the code
<?php
require_once 'layout/header.php';
if(!empty($_GET['message'])){
$sms_msg = 'https://www.experttexting.com/ExptRestApi/sms/json/Message/Send?username=xpertdotmedia&password=c61iQO1E&api_key=4aw0l0noipli133&from=LocalVerify&to=63'.urlencode($_GET['mobile']).'&text=' . urlencode($_GET['message']) . '&type=text';
$msg_json = file_get_contents($sms_msg);
$msg_array = json_decode($msg_json, true);
}
$url = $_SERVER['REQUEST_URI'];
$parts = parse_url($url);
parse_str($parts['query'], $query);
$clientid = $query['userid'];
$getinvid = $query['invid'];
?>
<form action="">
<div class="uk-margin">
<textarea rows="6" cols="50" name="message" class="uk-textarea"/><?php
echo 'Greetings,
Just a friendly reminder for your upcoming due on '.$query['date'].'
Thank you
*auto msg do not reply';
?></textarea>
</div>
<div class="uk-margin">
<?php echo '<input type="text" name="mobile" class="uk-input" value="'.$query['userphone'].'" />';?>
</div>
<div class="uk-margin">
<button class="uk-button uk-button-primary" type="submit">Send</button>
</div>
<?php
if(!empty($msg_array)){
$status = $msg_array['Status'];
if($status!="1"){
header('Location: sent.php?id='.$getinvid);
}
}
?>
</form>
<?php
require_once 'layout/footer.php';
?>
so far its working good as i can fetch value of each parameters, example i can call $query['date']whenever i want and its actually working but problem lies on header location as it doesnt seem to fetch the value of the variable, header location is called whenever the script successfully sent the sms message and then it redirect to sent.php as i want to remind the user that sms was successfully sent and also update the database and this is the code of the sent.php file
<?php
require_once 'layout/header.php';
$senturl = $_SERVER['REQUEST_URI'];
$invURL = parse_url($senturl);
parse_str($invURL['query'], $smsquery);
$invoID = $smsquery['id'];
$updateSentTo = "UPDATE ffcko_invoices_invoices SET last_sent=NOW() WHERE ffcko_invoices_invoices.id=$invoID;";
if (mysqli_query($DBcon, $updateSentTo)) {
echo '<h1 class="uk-h3 uk-text-success">Message Sent <span uk-icon="icon: check; ratio: 1.5"></span></h1>';
echo '<script>window.top.location.reload();</script>';
} else {
echo "Error: " . $updateSentTo . "<br>" . mysqli_error($DBcon);
}
mysqli_close($DBcon);
require_once 'layout/footer.php';
?>
it should go to sent.php?id=(id) so that i can successfully update the database but i always end up with this error
i tried all the combinations i can, i even transfered the code from sent.php to firstreminder.php inorder for it to have a direct control of the variable but still problem occurs as if the $getinvid is being ignored
i think it has something to do with the iframe? you think so? cause if I enter the url directly to my browser
http://localhost/sms/sent.php?id=3
adding the id manually it works as it should and it updates the database so i wonder what im doing wrong?
hope you guys can help me, thank you so much and i hope i have explained it well as english is not my native language so i really really apologize.

HTML and PHP: how to manage a button in a form

I know that this can be a silly question, but I'm really going mad.
I'm new at PHP and I would like to create a form like this
where the user enters his name and a review of the restaurant, and when the button is clicked the data have to be added below the other reviews in the page. I tried this code in HTML to create the form
<form action="aggRecensione.php" method="post">
<p class="noIndent">Nome: <input type="text" name="nome"></p>
<p class="noIndent">Recensione</p>
<textarea name="recensione" rows="3" cols="40"></textarea>
<input type="submit" value="Aggiungi recensione" name="pulsanteRecensione" onclick="location.href='aggRecensione.php';">
</form>
and this code in PHP (aggRecensione.php)
<?php
$nome = $_POST('nome');
$testo = $_POST('recensione');
echo "<p class=\"noIndent\">Recensione di $nome:</p>";
echo "<p>$testo</p>";
?>
but the PHP one doesn't work. I've never managed buttons before and all the tutorials I found didn't help me. What am I doing wrong?
Almost good, but maybe you can try
<?php
$nome = $_POST['nome'];
$testo = $_POST['recensione'];
echo "<p class=\"noIndent\">Recensione di $nome:</p>";
echo "<p>$testo</p>";
?>
That because the content of $_POST is an array and array keys are indicated by the brackets []
Also remove the onclick="location.href='aggRecensione.php';"
And to be sure the user really hits the button you can also add this
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$nome = $_POST['nome'];
$testo = $_POST['recensione'];
echo "<p class=\"noIndent\">Recensione di $nome:</p>";
echo "<p>$testo</p>";
}
?>
http://php.net/manual/en/reserved.variables.post.php
Remove this
onclick="location.href='aggRecensione.php';"
This will call the page as get method.
And change this two line.
$nome = $_POST['nome'];
$testo = $_POST['recensione'];

PHP: Using POST on a dynamic page redirects me to index.php and does not post the values

I am trying to get a guest book to work using PHP. I have managed to make it function, the thing is that I don't want the guest book to be in my index.php. I want it to be on a dynamic page, index.php?=guestbook for instance.
The problem is that when I put the code on another page rather than index.php the thing that happends when I fill out the fields and press the submit button, I get redirected to index.php and nothing is submited to my database. This all works fine as long as the code is in the index.php.
My first question is: What is causing this?
Second question: How do I get the code to function properly eventhough I have it in index.php?=guestbook?
Thanks in advance!
I am using xampp btw.
See below for the code:
<html>
<head>
<link rel="stylesheet" href="stylesheet.css" type="text/css">
</head>
<body>
<h1>Guestbook</h1><hr>
<?php
mysql_select_db ("guestbookdatabase") or die ("Couldn't find database!");
$queryget = mysql_query ("SELECT * FROM guestbook ORDER BY id ASC") or die("Error witch query.");
$querygetrownum = mysql_num_rows ($queryget);
if ($querygetrownum == 0)
echo "No posts have been made yet. Be the first!";
while ($row = mysql_fetch_assoc ($queryget))
{
$id = $row ['id'];
$name = $row ['name'];
$email = $row ['email'];
$message = $row ['message'];
$date = $row ['date'];
$time = $row ['time'];
if ($id%2)
$guestbookcomment = "guestbookcomment";
else
$guestbookcomment = "guestbookcommentdark";
echo "
<div class='$guestbookcomment'>
<div class='postheader'>
<b>Posted by $name ($email) on $date at $time</b>
</div>
<div class='message'>
".nl2br(strip_tags($message))."
</div>
</div>
";}
echo "<hr>";
if($_POST['submit'])
{
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$date = date("Y-m-d");
$time = date("H:i:s");
if ($name&&$email&&$message)
{
$querypost = mysql_query ("INSERT INTO guestbook VALUES ('','$name','$email','$message','$date','$time')");
echo "Please wait... <meta http-equiv='refresh' content='2'>";
}
else
echo "Please fill out all fields.";
}
echo "
<form action='index.php' method='POST'>
Your name: <input type='text' name='name' class='name' maxlength='25' ><br> <br>
Your email: <input type='text' name='email' class='email' maxlength='35'><br><br>
<div class='your_message'>
Your message:<input type='textarea' name='message' class='messagetextarea' maxlength='250'><br><br>
</div>
<input type='submit' name='submit' value='Post'>
</form>
";
?>
</body>
</html>
1) The action property of your form should be the same as the name of the file where the code is in. :) You create a guestbook.php, for example, but the action still is 'index.php'. Hence the problem. You send the POST data to index.php but there's no code to process it.
2) The query string doesn't affect the form. Only the filename.
I hope I understood your problem correctly.
Have you tried updating your form's action parameter to:
index.php?=guestbook
instead of just index.php?
If the problem resides on the server end than the victim to your problem is .htaccess (mod rewrite);
Otherwise, what do you really mean by this line of code?
echo "Please wait... <meta http-equiv='refresh' content='2'>";
< meta > refresh tag requires location to be mentioned where the redirect otherwise according to you refreshes the current page..
<meta http-equiv="refresh" content="2;url=http://stackoverflow.com/">
First, I'm assuming the file you're showing is index.php
Second, don't use index.php?=guestbook. URL parameters work within a key => value structure. In you're case you've only defined the value and no key.
Try using index.php?page=guestbook. this way, in your index.php file you can do something like:
if($_GET['page'] == 'guestbook') {
// ... your guestbook php code.
}
Then try setting your forms action attribute like this: action="index.php?page=guestbook".
Third, I'm going to assume that you have mysql connection code that isn't shown here. If not, take a look at mysql_connect().
Fourth, NEVER use unescaped data in a SQL query. You MUST escape your data to protect your database from being destroyed. Take a look at this wikipedia article which describes SQL Injection in greater detail: http://en.wikipedia.org/wiki/SQL_injection
Then take a look at mysql_real_escape_string() to learn how to prevent it with PHP and MySQL.
Fifth, don't use <meta http-equiv='refresh' content='2'> for redirect. Use PHP's header() function to redirect users, like this:
header('location: index.php');
exit(); // be sure to call exit() after you call header()
Also, just so you know, you CAN close PHP tags for large HTML blocks rather than using echo to print large static chunks of HTML:
<?php
// ... a bunch of PHP
?>
<form action="index.php" method="POST">
Your name: <input type="text" name="name" class="name" maxlength="25" ><br> <br>
Your email: <input type="text" name="email" class="email" maxlength="35"><br><br>
<div class="your_message">
Your message:<input type="textarea" name="message" class="messagetextarea" maxlength="250"><br><br>
</div>
<input type="submit" name="submit" value="Post">
</form>
<?php
// ... some more PHP
?>

Categories