I have a problem with the understanding of variable scopes.
I've got a huge .php file with many $_POST validations (I know that isn't not good practise). Anyways I want a little html-part above all the code which outputs an error message. This message I want to change in every $_POST validation function.
Example:
if($ERR) {
echo '<div class="error-message">'.$ERR.'</div>';
}
Now my functions are following in the same file.
if(isset($_POST['test']) {
$ERR = 'Error!';
}
if(isset($_POST['test2'] {
$ERR = 'Error 2!';
}
But that doesn't work. I think there's a huge missunderstanding and i'm ashamed.
Can you help me?
I didnt catch your question but maybe this is your answer:
<body>
<p id="error_message">
<?php if(isset($ERR)){echo $ERR;} ?>
</p>
</body>
and I suggest you to learn how to work with sessions.
and you should know that $_Post will be empty on each refresh or F5
You can do put the errors in array make them dynamic.
<?php
$error = array();
if (!isset($_POST["test"]) || empty($_POST["test"])) {
$error['test'] = "test Field is required";
} else if (!isset($_POST["test1"]) || empty($_POST["test1"])) {
$error['test1'] = "test Field is required";
}else{
//do something else
}
?>
You can also use switch statement instead of elseif which is neater.
Related
I want to implement recaptcha in a very simple form
I have a index.html file on client-side, and a post.php server side.
I've tried to integrate recaptcha on the server site, as you can see in my code bellow.
I've made some tests, that seem to have an expected result...
The problem appeard when I tried this query
for X in `seq 0 100`; do curl -D - "http://example.com/post.php" -d
"email=email${X}%40example.com&tos=on&g-recaptcha-response[]=plm&submit="; done
The result was that I've bypassed recaptcha succesfully, and I'm not sure what the problem is.
Most probably, there's a problem in my php code, but what exactly?
post.php
<?php
$email;$submit;$captcha;
if(isset($_POST['submit']))
{
$email=filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
}
if(isset($_POST['g-recaptcha-response']))
{
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha)
{
echo '<h2>Please check the the captcha form.</h2>';
exit;
}
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=6Le[whatever[7_t&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success==false)
{
echo '<h2>You are spammer ! Get the #$%K out</h2>';
}
else
{
$file = 'email-list.txt';
if (filter_var($email, FILTER_VALIDATE_EMAIL))
{
if(!(exec('grep '.escapeshellarg($email).' '.$file)))
{
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= $email . "\n";
// Write the contents back to the file
file_put_contents($file, $current);
header('Location: index.html?success='.urlencode($email));
}
else
header('Location: index.html?fail='.urlencode($email));
}
else
{
echo "$email is <strong>NOT</strong> a valid email address.<br/><br/>";
}
}
?>
index.html
...
<div class="form-group" ng-cloak>
<div class="g-recaptcha" ng-show="IAgree" data-sitekey="6LeEW[whatever]-UXo3"></div>
</div>
...
How can I solve this? English is not my native language; please excuse typing errors.
As mentioned in my comments above - file_get_contents returns a string. You need to decode the json string into a php object using the json_decode function:
$url = "https://www.google.com/recaptcha/api/siteverify?"
$response = json_decode(file_get_contents($url));
if($response->success == false) {
echo "Oh no";
}
I am a newbie and trying to implement a simple validation script after reading up, but I can't see how I can have multiple Ifs that will only do an sql insert if all required fields are met. Rather than having the multiple else statements, what is a syntax approach for having all the form validation Ifs together and if one of them fails, then the correct error is shown and the sql is not execute?
if(isset($_POST ['submit'])){
$user_ID = get_current_user_id();
$catErr = $ratingErr = $titleErr = $textErr = "";
if (empty($_POST["category"])) {
$catErr = "Category is required";
} else {
//DO THE INSERT BELOW!
}
if (empty($_POST["rating"])) {
$ratingErr = "Rating is required";
} else {
//DO THE INSERT BELOW!
}
if (empty($_POST["post_name"])) {
$postErr = "Title is required";
} else {
//DO THE INSERT BELOW!
}
if (empty($_POST["text"])) {
$textErr = "Text is required";
} else {
//DO THE INSERT BELOW!
}
//PDO query begins here...
$sql = "INSERT INTO forum(ID,
category,
rating,
post_name,
text
Use one variable for all the error messages and concatenate to it in the branches, so in the end if that variable is still empty string you won't do the insert. (And you don't need any of the empty else blocks that contain nothing but a comment.)
$err = "";
if (empty($_POST["category"])) {
$err .= "<br/>Category is required";
}
if (empty($_POST["rating"])) {
$err .= "<br/>Rating is required";
}
if (empty($_POST["post_name"])) {
$err .= "<br/>Title is required";
}
if (empty($_POST["text"])) {
$err .= "<br/>Text is required";
}
//PDO query begins here...
if($err=='')
{
$sql = "INSERT INTO forum(ID,
category,
rating,
...";
...
}
There are many solutions to your problem. Here are 3 methods of solving your issue.
You could combine all of your if statements like so:
if (empty($_POST['rating']) || empty($_POST'rating']) || ... ) { ... }
and separate them by double pipes.
You could also check the entire array:
if (empty($_POST)) $error = "There was an error!";
You could set a universal error variable and then output it.
A third solution could keep your current syntax but cut down on the amount of lines. You could save lines by doing without brackets. You can create an array and push your errors to the array.
Note: You can use empty() or isset().
// create an array to push errors to
$errors_array = array();
// if a particular field is empty then push the relevant error to the array
if(!isset($_POST['category'])) array_push($errors_array, "Category is required");
if(!isset($_POST['rating'])) array_push($errors_array, "Rating is required");
...
Once you have an array full of errors you can check for them like so:
// if the array is not empty (then there are errors! don't insert!)
if (count($errors_array) > 0) {
// loop through and echo out the errors to the page
for ($i = 0; $i < count($errors_array); $i++) {
echo $errors_array[i];
}
} else {
// success! run your query!
}
You should use javascript to validate the page before it is even processed into a post. This script will run client-side when they hit submit and catch errors before they even leave the page.
Here's a tutorial on how to do something like that: tutorial
Each field can have its own validation parameters and methods, and it will also make the page's code look a lot nicer.
I got it to go with this approach after showdev got me thinking that way. It's not very elegant perhaps, but does the trick, although all the user is taken to a blank page if there are errors and it simple says: Missing category (or whatever). Wondering if I can echo a link or something back to the page with the form from there so the user has an option like "go back and resubmit". Otherwise I will have to handle and display the errors alongside the form which will require a different approach altogether...
if(isset($_POST ['submit'])){
$errors = false;
if(empty($_POST['category'])) {
echo 'Missing category.<br>';
$errors = true;
}
if(empty($_POST['rating'])) {
echo 'Missing rating.<br>';
$errors = true;
}
if(empty($_POST['post_name'])) {
echo 'Missing title.<br>';
$errors = true;
}
if(empty($_POST['text'])) {
echo 'Missing text.<br>';
$errors = true;
}
if($errors) {
exit;
}
// THEN ADD CODE HERE. But how display form again if user makes errors and sees nothing but error message on page if they miss something (which is how it works now)
Generally, if you find yourself repeatedly writing very similar statements, using some sort of loop is probably a better way to go about it. I think what you said about "handling and displaying the errors alongside the form" is really what you need to do if you want the process to be user-friendly. If you put your validation script at the top of the file that has your form in it, then you can just have the form submit to itself (action=""). If the submission is successful, you can redirect the user elsewhere, and if not, they will see the form again, with error messages in useful places.
if (isset($_POST['submit'])) {
// define your required fields and create an array to hold errors
$required = array('category', 'rating', 'post_name', 'text');
$errors = array();
// loop over the required fields array and verify their non-emptiness
foreach ($required as $field) {
// Use empty rather than isset here. isset only checks that the
// variable exists and is not null, so blank entries can pass.
if (empty($_POST[$field])) {
$errors[$field] = "$field is required";
}
}
if (empty($errors)) {
// insert the record; redirect to a success page (or wherever)
}
}
// Display the form, showing errors from the $errors array next to the
// corresponding inputs
I want to use PHP to check if $_POST["pass"] is set, and do something if it's not, and do something else if it is.... But I can't get it working, I'm sure my logic is wrong.
I have a php code that looks something like this...
if (!isset($_POST["pass"])) {
...some form with an input type text here...
if (...wrote the wrong thing in input type text...) {
echo "something is wrong....";
}
else {
$pass_var = "Pass";
$pass_var = $_POST["pass"];
}
}
else {
echo "This thing is working...";
}
If I type the right thing in my input type text, I wan't to get to "This thing is working", and if not I wan't to echo "something is wrong....".
It works almost fine, except that if I type the right thing in my form, I never get to "This thing is working...".
The page just does nothing..
I'm sure it's the
$pass_var = "Pass";
$pass_var = $_POST["pass"];
that I'm doing wrong.
I know that I could set this up in another way to make it work, but I have a large script that is set up like this, and I really want it to work...
You test in the form against the $_POST NOT being set (See the !). You want however the post to be set!
if(isset($_POST["pass"]))
{
print_r($_POST); // basic debugging -> Test the post array
echo "The form was submitted";
// ...some form with an input type text here...
if(...wrote the wrong thing in input type text...)
{
echo "something is wrong with the input....";
}
else
{
// Valid user input, process form
echo "Valid input byy the user";
$pass_var = "Pass";
$pass_var = $_POST["pass"];
}
}
else
{
echo "The form was not submitted...";
}
You can use the empty() function of php
if(!empty($_POST['pass'])){
// do something
}else{
// do something else
}
Hope this will work for you .
Make sure you have "method='POST'" in your html form else $_POST isn't accessible in php, and logic was a bit screwy, try this?
e.g.
if (!isset($_POST["pass"])) {
//no POST so echo form
echo "<form action='".$_SERVER['PHP_SELF']."' method='POST'>
<input type='text' name='txtInput' />
<input type='submit' name='pass' />
</form>";
} elseif (isset($_POST["pass"])) {
//have POST check txtInput for "right thing"
if ($_POST["txtInput"] == "wrong thing") {
echo "something is wrong....";
} elseif ($_POST["txtInput"] == "right thing") {
//$pass_var = "Pass";
$pass_var = $_POST["pass"];
echo "This thing is working...";
}
}
Well, if (!isset($_POST["pass"])) means if $_POST["pass"] is not set, so you might want to remove the '!' which stands for not.
I have coded some alerting system.
But let's not look at the system itself, Let's look at how will the system know that the system really did sent the alert/error to the browsing user.
I have made something so when you randomly go to ?alert=name, without doing any error, it will say 'No errors'.
But if the system makes you go to ?alert=name, it will echo the error.
How I handle posts
function postComment() {
if (!empty($_POST['name']) || !empty($_POST['comment'])) {
$comment = mysql_real_escape_string(htmlentities($_POST['comment']));
$guest = mysql_real_escape_string(htmlentities($_POST['name']));
}
$guestId = 1;
if (empty($guest)) {
$alert = 1;
return header('location: index.php?alert=name');
}
if (empty($comment)) {
$alert = 2;
return header('location: index.php?alert=comment');
}
if (!isset($_COOKIE['alreadyPosted'])) {
mysql_query("INSERT INTO `comments` (`comment_guest`, `guest_id`, `comment`, `comment_date`, `comment_time`) VALUES ('$guest', '$guestId', '$comment', CURDATE(), CURTIME())") or die(mysql_error());
header('Location: index.php?action=sucess');
setcookie(alreadyPosted, $cookieId+1, time() + 60);
} else {
$alert = 3;
header('location: index.php?alert=delay');
}
}
As you see, to check if user really getting that error, I will set $alert to whatever error number it is.
And to check if hes getting the error I will use this:
if (isset($_GET['alert']) == 'name') {
if ($alert == 1) {
echo 'hai';
} else {
echo 'No errors';
}
}
You will probably wonder why I am doing it this way.., well because I use 1 function for post, and my post function goes under the form, and i want the alerts to display up to the form.
Problem:
The variable either doesn't get set to the number that it is supposed to when running the function,
or.. something is blocking it from it.. I don't know..
My guess: Because the check for errors is located up to the postComment function before the variables even get set?
<?php
if (isset($_GET['alert']) == 'name') {
if ($alert == 1) {
echo 'hai';
} else {
echo 'No errors';
}
}
?>
<form action="index.php" method="POST">
<input type="text" name="name" placeholder="Your name here" class="field">
<textarea class="textarea" name="comment" placeholder="Your comment here..."></textarea>
<input type="submit" name="send" class="blue_button" value="Post Comment">
</form><input type="submit" name="" id="margin" class="blue_button" value="See all messages">
<br />
<?php
//Show the comments
showComments();
if (isset($_POST['send'])) {
postComment();
}
if (isset($_GET['delete']) == "comment"){
deleteComment();
}
echo '<br />';
?>
If it is, what is the solution?
Thanks!
Please don't start with the story about mysql_ function, I understood & I will use PDO instead, but I am using mysql_ at the moment for testing purposes
The problem is that you're redirecting on an error, and so the $alert variable does not get carried over.
To fix the problem add the alert type to the $_GET parameters:
function postComment()
{
// ...
if (empty($guest))
{
header('location: index.php?alert=name&alert_type=1');
exit;
}
// ...
}
And then when you check for the error:
if (isset($_GET['alert']) && 'name' == $_GET['alert'])
{
if (isset($_GET['alert_type']) && '1' == $_GET['alert_type'])
{
echo 'hai';
}
else
{
echo 'No errors';
}
}
Note also that I fixed the error here:
isset($_GET['alert']) == 'name'
That doesn't do what I think you think it does. What you want is:
isset($_GET['alert']) && 'name' == $_GET['alert']
(Excuse the order of the comparison; I prefer to have variables on the right for comparisons as it will cause a parse error if you miss a = -- much better than having it run but not do what you expect)
if you are a newbie, you better consider using client side scripting (viz javascript) for validation as using server side validation will simple make the process longer. but as you are facing problems, this might give you the solution.
as you are redirecting the page to index.php?alert=name', so $alert is never set initially when the page loads itself. when you call the function postcomment(), $alert is initiated but immediately destroyed when the system redirects. And as $alert never holds a value when you randomly visit the page, it shows no error.
I got an ajax submitting form source code, and learning it right, I found the return errors are all in a big square. I want to separate errors to where they belong to.
then I can simply add something like following code
<?php if($_session('errorarray'): ?>
<span class="errorclass"><?php echo $errorarray['phone']; ?></span>
<?php endif; ?>
here is validation php code, (I have 5 items need to be checked)
$error = array();
if(!check('name'))
$error[]='too short!';
else if(validate_name($_POST['name']))
$error[]='letters please!';
..........
if(checkphone($_POST['phone'])){
$error[]="Please enter a valid phone number";
}
here is the code return to $_Session
if(count($error))
{
if($_POST['ajax'])
{
echo '-1';
}
else if($_SERVER['HTTP_REFERER'])
{
**$_SESSION['errorarray'] = array ($error);** // possible?
$_SESSION['post']=$_POST;
header('Location: '.$_SERVER['HTTP_REFERER']);
}
exit;
}
Sorry I am very new to php. Hope my expression is not too hard to understand.
Many thanks in advance.
You can just set $_SESSION['errorarray'] = $error; Then in your view, you can do something like <span class="errorclass"><?php foreach ($_SESSION['errorarray'] as $err) { echo $err; } ?></span>
Sorry, your question is a bit unclear, if you provide more details we could probably give you a better answer.