Admin Panel: PHP form doesn't send data to MySQL - php

I have a simple code to add banners from admin panel to the index of the site. But the add function doesnt work correctly here is the form to add banner
<h2>Add Banner</h2>
<?php include ("../engine/config/config.php"); ?>
<form method="post" action="">
Clicks
<input type="text" name="click" value="0" style="width: 200px;" /> <div class="hr"></div>
Impressions
<input type="text" name="imp" value="0" style="width: 200px;" /> <div class="hr"></div>
LINK
<input type="text" name="url" value="http://" style="width: 200px;" /> <div class="hr"></div>
Size
<select name="razmer">
<option value='468x60'>468x60</option>
<option value='88x31'>88x31</option>
</select>
<div class="hr"></div>
Banner<br />
<input type="text" name="picurl" value="http://" style="width: 200px;" /><div class="hr"></div>
<input type="submit" name="submit" value="Submit"> <br />
</form>
<?
if($_POST['submit']) {
$click = $_POST['click'];
$imp = $_POST['imp'];
$url = $_POST['url'];
$razmer = $_POST['razmer'];
$picurl = $_POST['picurl'];
$sql = "INSERT INTO `banneradd` (click, imp, url, razmer, picurl, username) VALUES ('$click', '$imp', '$url', '$razmer', '$picurl', '')";
$result = mysql_query($sql);
echo "<div class='hr'>The Banner has been added, please go back to the index: <a href='view_reklama.php'> Index </a></div>";
}
?>
So it say it was added but when I go back ITS NOT. There is no error or anything, can someone help? Thanks in advance :)

Okay, there are way too many things wrong with your code, so if you're learning from a particular site or person... find a different source.
Don't open PHP with <?. This is the shorthand style. It is disabled on many if not most web servers, and for good reason -- because XML introduces its encoding using the same opening <? and it causes conflict. Always open your PHP with <?php. http://www.php.net/manual/en/ini.core.php#ini.short-open-tag
Don't use if($_POST['submit']), use if (isset($_POST['submit'])). Your current script should generate an error, but it's probably being masked because PHP defaults to not showing very many errors. It does trigger a warning, though, because you're checking if the variable (or rather array value) $_POST['submit'] is equal to true. In fact, that variable is undefined. Use isset() to check if a variable exists. http://php.net/manual/en/function.isset.php
Sanitize your user's input. If somebody typed a ' into any of your fields, your query would break. Why? Because in your query, you're placing your stringed values in single quotes, and any instance of another single quotation mark would break out of that. There is such a thing as magic quotes in PHP (which automatically escapes POST values), but it's absolutely awful, so please disable it. http://php.net/manual/en/security.magicquotes.php The best way to escape user input is with real escape functions (more on that later).
mysql_ functions are deprecated. Use PDO or MySQLi. If you're getting used to the mysql_ functions, it is easier to transition to MySQLi. For simplicity, I'll use the procedural style, but it's much better to go with the OOP style....
If you want to debug MySQL commands with PHP, you should format your queries carefully, print the error, and also print the computed query, because sometimes you need to look at the actual resulted query in order to see what is wrong with it.
That said, here's what I suggest:
<?php
error_reporting(E_ALL);
// Turn on all error reporting. Honestly, do this every time you write a script,
// or, better yet, change the PHP configuration.
$connection = mysqli_connect('host', 'username', 'password', 'database');
// Somewhere in your config file, I assume you're calling mysql_connect.
// This is a pretty similar syntax, although you won't need mysql_select_db.
if (isset($_POST['submit'])) {
$click = mysqli_real_escape_string($connection, $_POST['click']);
// This will escape the contents of $_POST['click'], e.g.
// if the user inputted: Hello, 'world'! then this will produce:
// Hello, \'world\'!
$imp = mysqli_real_escape_string($connection, $_POST['imp']);
$url = mysqli_real_escape_string($connection, $_POST['url']);
$razmer = mysqli_real_escape_string($connection, $_POST['razmer']);
$picurl = mysqli_real_escape_string($connection, $_POST['picurl']);
$query = "
INSERT INTO `banneradd` (
`click`,
`imp`,
`url`,
`razmer`,
`picurl`,
`username`
)
VALUES
(
'$click',
'$imp',
'$url',
'$razmer',
'$picurl',
''
);
";
// Format your query nicely on multiple lines. MySQL will tell you what line
// the error occurred on, but it's not helpful if everything's on the same line.
$result = mysqli_query($connection, $query);
$error = mysqli_error($connection);
if ($error) {
echo "A MySQL error occurred: $error<br>";
echo "<pre>$query</pre>";
// If an error occurred, print the error and the original query
// so you can have a good look at it.
die;
// Stop executing the PHP.
}
echo '<div class="hr">The Banner has been added, please go back to the index: Index </div>';
}
?>
See if that helps. Chances are, the MySQL error will be helpful with diagnosing the problem. You might have just misspelled a column name or table name.

Related

php form post updates database and refreshes page but does not update data on the page after refresh

I can't seem to find a working solution in stackoverflow. I wish to update the form values with the updated data that is submitted in the form post. The database updates but after the refresh, the values are still the same. Any help would be appreciated. Thanks!
<?php
global $wpdb;
$user_id = get_current_user_id();
$org_id = get_user_meta($user_id, '_org_id', true);
$orgs = $wpdb->get_results("select * from wp_organization");
$user_org = null;
foreach($orgs as $struct) {
if ($org_id == $struct->id) {
$user_org = $struct;
break;
}
}
?>
<?php
$connection = mysqli_connect("address", "login", 'password');
$db = mysqli_select_db($connection, 'databasename');
if(isset($_POST['update'])) {
$id = $org_id;
$query = "UPDATE `wp_organization` SET
name = '$_POST[org_name]',
shortname = '$_POST[shortname]',
industry = '$_POST[industry]',
description = '$_POST[description]'
where id = $id ";
$query_run = mysqli_query($connection, $query);
}
}
?>
<!-- organization info form -->
<form class="py-4 col-md-6 mx-auto" method="post" action="">
<h2 class="mb-3 text-center">Organization Information</h2>
<label class="form-label">Name</label>
<input type="text" required name="org_name" value="<?php echo $user_org-> name; ?>"
class="form-control mb-3" />
<label class="form-label">Industry</label>
<input type="text" name="industry" value="<?php echo $user_org-> industry; ?>" class="form-control mb-3" />
<label class="form-label">Short name (4 characters)</label>
<input type="text" name="shortname" required maxlength="4" value="<?php echo $user_org-> shortname; ?>" class="form-control mb-3" />
<label class="form-label">Description</label>
<textarea class="form-control mb-3" name="description" rows="5" cols="50"><?php echo trim(stripslashes($user_org-> description)); ?></textarea>
<div class="d-flex justify-content-center">
<input type="submit" name="update" value='Update' class='btn btn-primary'>
</div>
</form>
The main issue that's causing old data to appear is that you are querying the database before you update it. The data displayed in the form is queried at the beginning of the page's execution, and later, if there's POST data, the database is updated. As a result, the data used to render the form is the old data, not the recently updated data. So in a very minimal way, you could simply switch the database query with the database update, and your data flow would work as intended.
However, there's several other issues with this code, most notably the SQL attack vulnerability. As a result, I'll address all of these issues in creating a complete and safe answer to this question.
This is WordPress!
Based on the presence of the $wpdb variable, as well as some of the table names, it appears that this is running as part of a WordPress site (or else alongside a WordPress install). As a result, you never need to make a any of the raw mysqli_ calls. Instead, use the the methods documented in the $wpdb class which provide safe access to the database, and also will help ensure that any future changes to the WordPress database system don't break your code.
Result: Remove mysqli_ methods.
Watch out for unnecessary syntax
There's several unnecessary bits of syntax which may have undesirable side effects. For instance, in the middle of the code you have
?>
<?php
What this code snippet actually does is insert a phantom bit of whitespace (in this case one literal newline character or \n) into the output of your page. If, for instance, you tried to set a header after this value you would get a difficult and mysterious error about output already having been sent. A good practice is that all of your business code lives in a single, contiguous block with just a single <?php at the top of your file.
In addition, your block that begins if(isset($_POST['update'])) ends with an extra dangling closing bracket }.
Furthermore, inside your actual update section, the calls to the $_POST superglobal are not actual strings but raw tokens (such as $_POST[shortname]. I suspect you did this in order to take advantage of PHPs string interpolation. While this raw format does work for legacy reasons, it's much clearer and safer when interpolating a string like this to use something like {$_POST['shortname']} inside your string.
Result: Remove and clean up unnecessary syntax.
SQL Injection! Oh My!
The biggest scary bit of this code is wide open SQL injection attack that's enabled by passing un-trusted strings (in the form of the $_POST variables) to SQL. This has been the bane of thousands (if not millions) of websites. Anyone who can access your web page can pass any data they want into the form field, including SQL commands which can delete your database and compromise your server. Using raw SQL like this is wildly dangerous and should never be used. PHP includes a great library PDO for this, and there are many other options. However, as discussed above, since you're using WordPress, you can just use the $wpdb, which also has protections against SQL injection built in and provides further compatibility benefits with the WordPress database.
Result: Don't use raw SQL
Update then Query (but Query first, too)
The core problem that caused you to post the question was data not updating in the web page when a form is submitted until the next load. This is because you currently query the data from the database, then update the database after that. Since you use the result from the early query to display values in the web page, they're naturally not the new values.
I suspect you did this because you need the value of $org_id in order to create and query and as a result all your querying got clumped together. Nonetheless, this primary fetch of the $org_id needs to be in the beginning, but the rest of the query after the update.
Result: Fix query and update ordering.
No data validation
You blindly use the value of $_POST values, but these may not be set. In your example this will probably only lead to empty database values, but in other context this could be catastrophic. As mentioned above, anyone can request your page with any $_POST data they desire. Therefore, it's good practice to ensure that you provide default values in case the data sent to the server is missing some fields.
Result: Validate that all expected data is present.
A version of this code that updates the database before querying, so the data is correct on each page load and update, as well as incorporating the other fixes mentioned, might look something like this:
<?php
/// 1. Get the global WordPress Database Object
global $wpdb;
/// 2. Use WP helper functiosn to query the current user and org IDs
$user_id = get_current_user_id();
$org_id = get_user_meta($user_id, '_org_id', true);
/// 3. Update the database if necessary
if (isset($_POST['update'])) {
/// 3.i Prepare the variables
// Note: In new versions of PHP, each of the isset ? : lines below could be replaced
// with something like:
//
// $name = $_POST['org_name'] ?? "default org name";
//
// I've used the long version here, so you can really see what ?? means. You can also
// put any value you want in the final string of these expressions, so for example
//
// $name = isset($_POST['org_name']) ? $_POST['org_name'] : "unknown";
//
// would provide the value "unknown" into the database. You could inline all of these
// checks into the following call to $wpdb, but that would make for a very hard to read
// line. Setting local variables to these values makes the code easier to follow.
$name = isset($_POST['org_name']) ? $_POST['org_name'] : "";
$short = isset($_POST['shortname']) ? $_POST['shortname'] : "";
$ind = isset($_POST['industry']) ? $_POST['industry'] : "";
$desc = isset($_POST['description']) ? $_POST['description'] : "";
/// 3.ii Execute the query
// Note: I assume that $org_id is an integer. If it's actually a string, then that
// line in the query should read
//
// where id = %s
$wpdb->query(
$wpdb->prepare("
UPDATE `wp_organization` SET
name = %s,
shortname = %s,
industry = %s,
description = %s
where id = %d
",
$name, $short, $ind, $desc, $org_id
)
);
// Alternatively to the raw $wpdb->query above, you could use the built in update method
// of $wpdb, like so
//
// $wpdb->update('wp_organization', array(
// 'name' => $name,
// 'shortname' => $short,
// 'industry' => $ind,
// 'description' => $desc,
// ),
// array( 'id' => $org_id ),
// array('%s', '%s', '%s', '%s'),
// array('%d')
// );
//
// This has the advantage that you don't have to write any SQL, but may be harder to understand
// if you come back to maintain this code far in the future.
}
/// 4. Load the current value of $user_org, this will reflect any database changes made above
$orgs = $wpdb->get_results("SELECT * FROM `wp_organization`");
$user_org = null;
foreach($orgs as $struct) {
if ($org_id == $struct->id) {
$user_org = $struct;
break;
}
}
/// 5. Render the form
?>
<!-- organization info form -->
<form class="py-4 col-md-6 mx-auto" method="post" action="">
<h2 class="mb-3 text-center">Organization Information
<label class="form-label">Name
<input type="text" required name="org_name" value="<?php echo $user_org->name; ?>" class="form-control mb-3" />
<label class="form-label">Industry
<input type="text" name="industry" value="<?php echo $user_org->industry; ?>" class="form-control mb-3" />
<label class="form-label">Short name (4 characters)
<input type="text" name="shortname" required maxlength="4" value="<?php echo $user_org->shortname; ?>" class="form-control mb-3" />
<label class="form-label">Description
<textarea class="form-control mb-3" name="description" rows="5" cols="50"><?php echo trim(stripslashes($user_org->description)); ?>
<div class="d-flex justify-content-center">
<input type="submit" name="update" value='Update' class='btn btn-primary'>
</div>
</form>

PHP /MySQL update form from within results

I've got a search function written in PHP/MySQL which works fine. What I want to happen is that when a user produces a search they can click a button which will submit the $id from the output to a table in my database.
I've copied my code below, the error is within the php echo in the form, it just displays the plain text of the php code.
Everything else works fine, I've tested this by setting value to "" and entering the id myself and then it works. I want it though to be a hidden input in future where the id automatically comes through from the search result. Multiple searches can be returned on the same page and this form is underneath each individual search result.
<?php
$conn = mysqli_connect("localhost","root","","users");
$output = '';
if(isset($_POST['search'])) {
$search = $_POST['search'];
$search = preg_replace("#[^0-9a-z]i#","", $search);
$query = mysqli_query($conn, "SELECT * FROM users WHERE main LIKE '%".$search."%'") or die ("Could not search");
$count = mysqli_num_rows($query);
if($count == 0){
$output = "There was no search results!";
}else{
while ($row = mysqli_fetch_array($query)) {
$id = $row ['id'];
$main = $row ['main'];
$postcode = $row ['postcode'];
$available = $row ['available'];
$email = $row ['email'];
$output .='<div><br><b>Player ID: </b>'.$id.'<br><b>Main:
</b>'.$main.'<br><b>Postcode: </b>'.$postcode.'<br><b>Available:
</b>'.$available.'<br>
<br>
<form action="request_player.php" action="post">
<input type="text" name="id" value="<?php echo $id ?>">
<input type="submit" value="Request Player">
</form>
</div>';
}
}
}
echo $output;
?>
<br> Back to your account
The issue Jay Blanchard highlighted and which you took a bit lightly - perhaps b/c you fear the distraction from your current problem - is actually pretty related to the issue you highlight in your question.
This btw. is nothing uncommon. In this little script you deal with at three languages: HTML, SQL and PHP. And all these are intermixed. It can happen that things jumble.
There are methods to prevent these little mistakes. What Jay highlighted was about how to encode a SQL query correctly.
The other problem is to encode a HTML string correctly. Let me highlight the part:
$output = '... <input type="text" name="id" value="<?php echo $id ?>"> ...';
In this PHP string you write "<?php echo $id ?>" verbatim, that means, this will echo'ed out then.
What you most likely meant was to write it this way:
$output = '... <input type="text" name="id" value="' . $id . '"> ...';
So this seems easy to fix. However, it's important that whether it is SQL or HTML, you need to properly encode the values if you want to use them as SQL or HTML. In the HTML case, you must ensure that the ID is properly encoded as a HTML attribute value. In PHP there is a handy function for that:
$output = '... <input type="text" name="id" value="' . htmlspecialchars($id) . '"> ...';
Or as the ID is numeric:
$output = '... <input type="text" name="id" value="' . intval($id) . '"> ...';
works similarly well.
You need to treat all user-data, that is all input - which includes what you get back from the database (!) - needs to be treated when you pass it into a different language, be it HTML, SQL or Javascript.
For the SQL Jay has linked you a good resource, for the HTML I don't have a good one at hand but it requires your own thoughtfulness and the will to learn about what you do (write) there. So sharpen your senses and imagine for each operation what happens there and how this all belongs together.
One way to keep things more apart and therefore help to concentrate on the job is to first collect all the data you want to output and then process these variables in a template for the output. That would prevent you to create large strings only to echo them later. PHP echoes automatically and a benefit of PHP is that you can use it easily for templating.
Another way is to first process the form input - again into your own variable structure - which is the programs input part and run first. Then follows the processing of the input data, in your case running and processing the database query. And after that you care about the presentation. That way you have common steps you can become more fluent in.
I hope this is understandable. It's full of further obstacles, but it pays to divide and conquer these programming problems. It will also help you to write more while you need to write less for that.
And btw., you don't need to switch to PDO, you can stick with Mysqli.
The reason it is happening is because you have put <?php echo $id ?> inside a string. You want to do the same thing you did elsewhere in your example: value="' . $id . '" It can quickly get confusing when you have single and double quotes happening together. You might be best off learning how to use PHPs multiline strings.
Also, <?= $id ?> is a useful shorthand for <?php echo $id ?> (although you don't want to use either here)

How can i pass the variable in the anchor to the next page?

I have two pages where one links one to the other. How can i pass the value of the variable(region_name) in my anchor(select.php) to the next page(display.php)? i used the following codes and im getting Notice: Undefined variable: region_name.how do i fix it?
select.php
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a name="region_name" method="POST" value="Greater Accra Region" type="submit" href="display.php" target="main">Greater Accra Region</a>
</h4>
</div>
</div>
display.php
<?php
ob_start();
session_start();
if(isset($_POST['region_name'])){
$region_name = $_POST['region_name'];
}
$con=mysqli_connect("localhost","root","root","findings");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT * FROM approved_reservation WHERE region_name = '$region_name'";
$records=mysqli_query($con,$sql);
?>
We pass the variable $myVar through the URL and use $_GET in the next page to use it. We use htmlspecialchars(); to clean user input.
We use the if (isset($_GET['myVar'])) so it doesn't throw Notice: Undefined index error.
pageOne.php
<?php
$myVar = "My variable one.";
echo "<a href='pageTwo.php?myVar=" . $myVar . "'>Page Two</a>"
?>
pageTwo.php
<?php
if (isset($_GET['myVar'])) {
$myVar = htmlspecialchars($_GET['myVar'], ENT_QUOTES);
// Now you can use $myVar.
}
?>
Now I'm not sure what variable you want to pass through so I used a simple skeleton which I made yesterday to show you how it is done. If you supply more code, I'll edit it to suit your scenario.
Edit 1
Your code below is incorrect because you're declaring your variable $region_name inside the scope of the if statement your queries and other code which is dependent on the variable has to be in that if statement.
Another solution would be to define an empty variable $region_name outside of the if statement then after the if statement you won't get the error Undefined Index.
if(isset($_POST['region_name'])){
$region_name = $_POST['region_name'];
}
Edit 2
That error is being thrown for two reasons,
Your not actually passing the region name through the URL - though even if you were it wouldn't work as you're using $_POST instead of $_GET.
I outlined reason 2 in the above edit. You're using a variable which isn't in the scope of the queries.
You're getting an undefined variable because of the following:
href does not use methods, nor values, nor type, <form>...</form> does.
Forms use inputs with name attributes set for its method.
Your code is expecting it to be passed via a form and using a POST method.
More on forms here http://php.net/manual/en/tutorial.forms.php
What you want to use here is a GET in your conditional statement:
if(isset($_GET['region_name']) && !empty($_GET['region_name']) ){
$region_name = $_GET['region_name'];
echo $region_name;
}
Sidenote: I used !empty() should someone want to modify the URL as ?region_name=
and using a ? parameter after the filename and a = followed by the "value" you wish it to be:
Greater Accra Region
which in turn will echo "your_value".
You will need to modify its value respectively.
In your case, that would read as:
Greater Accra Region
You can also add to the above and inside the conditional statement:
if($_GET['region_name'] == "Greater Accra Region"){
echo "Region is Greater Accra Region";
}
Which can be modified as:
Sidenote: The following example checks if a region equals to something, and if the value was modified in the URL such as ?region_name=.
if(isset($_GET['region_name'])){
$region_name = $_GET['region_name'];
echo $region_name;
if($_GET['region_name'] == "Greater Accra Region"){
echo "Region is Greater Accra Region"; }
if(empty($_GET['region_name'])){
echo "EMPTY"; }
}
Now, seeing your query, that is unknown as to what the ultimate goal is.
Only you know and goes beyond the scope of your original question.
If you have a form (with a POST method) that you haven't posted, then you can use an input:
I.e.:
Greater Accra Region:
<input name="region_name" value="Greater Accra Region" type="submit">
and using your present POST arrays.
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
The simplest form of passing along the data to display.php would be to add the region_name to the URL like so:
href="displayApprovedReservation.php?region_name=<?php echo $region_name; ?>"
In the display.php, you would then use $_GET['region_name'] to retrieve the data from the URL. Doing it this way, you would need to make sure you sanitize the input as it can be changed very easily from the URL by a user.
The reason you are getting the error Notice: Undefined variable: region_name is because the data is not being posted to the page, therefore $_POST['region_name'] is not set, thus not setting $region_name in the process -- yet you are still calling it in the SQL query regardless of the variable being set:
$sql="SELECT * FROM approved_reservation WHERE region_name = '$region_name'";
There are several ways to do what you're trying to do. The method that you're trying to achieve would require a form like:
<form name="selection" method="POST" action="display.php">
<input name="region" type="radio" value="Greater Accra Region">
</form>
But it doesn't look great and don't work the way you want to.
Another method would be just to use a get variable like this
Greater Accra Region
Then on your display file you can use the variable $_GET['selection']; to use your selection :)

PHP Multiple file upload with multiple inputs

I'm new to PHP. Now i have a problem with files upload.
All files are moved, but It didn't store file's name to database.
and it didn't show error. I have no idea to fix this one. Please help me out.
<form method="post" action="index.php?insert_ads" enctype="multipart/form-data">
<input type="file" name="b1" id="b1"/>
<b>Link</b></br>
<input type="text" id="b1l" name="b1l" class="form-control"/></br>
<b>Home Small</b> <b style="color: blue;">100 x 100 px</b></br>
<input type="userfile" name="b2" id="b2"/><br>
<b>Link</b></br>
<input type="text" id="b2l" name="b2l" class="form-control"/></br>
<input type="submit" name="submit" value="Publish"/>
</form></br>
<?php
if(isset($_POST['submit'])){
$b1 = $_FILES['b1']['name'];
$tmp1 = $_FILES['b1']['tmp_name'];
$b1l = $_POST['b1l'];
$b2 = $_FILES['b2']['name'];
$tmp2 = $_FILES['b2']['tmp_name'];
$b2l = $_POST['b2l'];
move_uploaded_file($tmp1,"ads/$b1");
move_uploaded_file($tmp2,"ads/$b2");
$insert_posts = "insert into ads (b1,b2) value ('$b1','$b2')";
$run_posts = mysql_query($insert_posts);
}
?>
Notwithstanding any issues about using mysql_query or injection attacks, there are a number of things that could be going wrong here.
One option is that the query is executing, but you haven't assigned the $b1 and $b2 variables correctly. This would be the case if rows are being added to the database, but the rows are empty (e.g., SELECT b1, b2 FROM db.ads" returns rows of '',''); in that case, you probably just aren't extracting the name attribute from the $_FILES variable correctly. You can run var_dump($_FILES); to see more information about it and figure out what you need to get.
Another possibility is that the query is not executing. Again, this may be for a couple of reasons -- maybe (somehow) it's not reaching that point in the code. You can test that like so:
$insert_posts = "insert into ads (b1,b2) value ('$b1','$b2')";
echo $insert_posts; // if this shows up, you're running the next line also
$run_posts = mysql_query($insert_posts);
Another option is that your error reporting level is not capturing an error. A likely cause of this is that you have not connected to the database -- according to the mysql_query documentation...
If no connection is found or established, an E_WARNING level error is generated.
A E_WARNING level error will allow the program to continue to execute unless you have configured your program to behave differently.
Finally, you may have a syntax error (and indeed it seems you do -- VALUES, not VALUE); according to the documentation, mysql_query returns false on error -- it does not throw an error.
You can rig it to do so by testing for false and using the mysql_error function to get the error:
$run_posts = mysql_query($insert_posts);
if ($run_posts === false) {
trigger_error("Error in SQL!\n" + mysql_error(), E_USER_ERROR);
}

Simple Captcha in PHP with rand()

I'm trying to make a simple captcha in PHP, but it does not work. The query is not currently executing. This is my current code:
<?php
$Random = rand(1, 100);
$Random2 = rand(1,100);
echo "Result: ".$Random." + ".$Random2." ?";
?>
<input type="text" name="r_input"/><br />
$Cap = mysql_real_escape_string($_POST['r_input']);
$Result = $Random+$Random2;
if(isset($_POST['myButton']) and trim($Var) and trim($Var2) and trim($Var3) and $Cap==$Result){
//My Query
}
When you use rand() to generate 2 values, and show those 2 values, and give the form for the user to enter the answer, ...
... the user enters the answer and submits back to the server ...
... the server gets the answer, and then GENERATES 2 NEW VALUES, that don't correspond to the answer given by the user.
Try using session variables to store the generated values in, and match against when the user submits the form!
<?php
session_start();
$captcha_id = 'captcha_' . rand();
$_SESSION['$captcha_id']['val1'] = rand(1,1000);
$_SESSION['$captcha_id']['val2'] = rand(1,1000);
echo "
<form action='' method='post'>
<p>Result: {$_SESSION['$captcha_id']['val1']} + {$_SESSION['$captcha_id']['val2']} = </p>
<input type='hidden' name='captcha_id' value='{$captcha_id}' />
<input type='text' name='captcha_answer' />
<p>?</p>
</form>
";
if (
isset($_POST['captcha_id'])
&& isset($_SESSION[$_POST['captcha_id']])
&& isset($_POST['captcha_answer'])
&& $_SESSION[$_POST['captcha_id']]['val1'] + $_SESSION[$_POST['captcha_id']]['val2'] == intval($_POST['captcha_answer'])
) {
unset($_SESSION[$_POST['captcha_id']]); // don't let this answer be reused anymore.
// do allowed stuff
}
?>
Because $Random and $Random2 have a different value each time.
When you show the form for the first time, they may have the values $Random = 12 and $Random2 = 26. The User sees those, adds them up correctly and types in 38 (which is the correct answer for those two values). The answer is sent to the script again, the values of $Random and $Random2 are generated again (this time as $Random = 23 and $Random2 = 30 which equals 53) and the answer the user has sent is not correct any more.
So you would need to store those values in hidden fields and add these up, instead of the generated ones, like so:
<input type="hidden" name="rand_1" value="<?php echo $Random; ?>">
<input type="hidden" name="rand_2" value="<?php echo $Random2; ?>">
<?php
if ($_POST['rand_1'] + $_POST['rand_2'] == $_POST['r_input']) {
// Query etc.
EDIT: As suggested by #nl-x you should use the Session variables instead of hidden fields to prevent abuse of the captcha:
<?php
$Random = $_SESSION['rand_1'] = rand(1, 100);
$Random2 = $_SESSION['rand_2'] = rand(1,100);
echo "Result: ".$Random." + ".$Random2." ?";
?>
And check those values against the given result afterwards:
<?php
$Cap = mysql_real_escape_string($_POST['r_input']);
$Result = $_SESSION['rand_1'] + $_SESSION['rand_2'];
if ($Result == $Cap) {
// ...
You never re-enter PHP mode after you output your form field:
<input type="text" name="r_input"/><br />
<?php // <----this is missing
$Cap = mysql_real_escape_string($_POST['r_input']);
Pardon me, but you are not making a real captcha. The purpose of the captcha is to distinguish the human from the bots. I would highly suggest you to pick a image database, and randomize a function to call a image. Internally, i would check if the text/description of the image matches with what the user typed.
The only thing you will rand() is what image to load from your image database.
That's a not-healthy way to do it, and there are plenty of better ways to do this. But it's more closer to a captcha than just your current code.
There is also a lot of libraries and engines that can do the job for you.
I'm not a pro at PHP, or even programming at all, but i think you're going to the wrong side - your code won't block any... malicious actions at all, or whatever kind of action that you will try to prevent with the captcha.
Search google for the libraries. PhpCaptcha is one of them. And here is a very simple quickstart guide for phpcaptcha.
Here's a code example, extracted from PHPCaptch that I linked above.
At the desired position in your form, add the following code to display the CAPTCHA image:
<img id="captcha" src="/securimage/securimage_show.php" alt="CAPTCHA Image" />
Next, add the following HTML code to create a text input box:
<input type="text" name="captcha_code" size="10" maxlength="6" />
[ Different Image ]
On the very first line of the form processor, add the following code:
<?php session_start(); ?>
The following php code should be integrated into the script that processes your form and should be placed where error checking is done. It is recommended to place it after any error checking and only attempt to validate the captha code if no other form errors occured. It should also be within tags.
include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
$securimage = new Securimage();
This includes the file that contains the Securimage source code and creates a new Securimage object that is responsible for creating, managing and validating captcha codes.
Next we will check to see if the code typed by the user was entered correctly.
if ($securimage->check($_POST['captcha_code']) == false) {
// the code was incorrect
// you should handle the error so that the form processor doesn't continue
// or you can use the following code if there is no validation or you do not know how
echo "The security code entered was incorrect.<br /><br />";
echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
exit;
}
Following the directions above should get Securimage working with minimal effort.
This code is included here as well.
Good luck!

Categories