PHP Multiple file upload with multiple inputs - php

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

Related

php throwing undefined index warning but the script works as intended?

I wrote a simple php script that basically echos the values put into a form on the page, later, I will have this write to a DB but I was working on troubleshooting it before I did that since I keep getting this warning.
Does anyone know why I am getting it? If I just fill in the fields and submit the form, the script works fine and the warning disappears.
PHP Function:
function quickEntry()
{
$subTitle = $_POST['subTitle'];
$subDetails = $_POST['details']; //This is line 13 in my code
echo "$subTitle";
echo "<br>$subDetails";
}
HTML / PHP Code:
<form method="post" action="">
<hr>
<h1>Quick Entry:<p></h1>
Subject Title:<br> <input type="text" name="subTitle"><br><br>
Subject Details: <p><textarea name="details" placeholder="Enter Details here..."></textarea><p><br>
<input type="submit" name="QuickEntrySubmit" value="Submit Quick Entry" /><br>
</form>
<?php
if (isset($_POST['QuickEntrySubmit']))
{
quickEntry();
}
?>
I know that I could disable warnings and I wouldn't see this, but I really just want to know why php is throwing the warning so I can fix the syntax appropriately and keep my code clean going forward. Full warning is:
Notice: Undefined index: details in C:\xampp\htdocs\test1.php on line 13
Thanks!
The reason why you are getting that error is because you are not checking whether the 'subTitle' and 'details' inputs have values in them.
Your code should work well like this:
function quickEntry(){
$subTitle = isset($_POST['subTitle'])? $_POST['subTitle']: null;
$subDetails = isset($_POST['details'])? $_POST['details']: null ; //This is line 13 in my code
if(!is_null($subTitle) && !is_null($subDetails)){
echo "$subTitle";
echo "<br>$subDetails";
} else{
//blah blah blah
}
You get the warnings because the $_POST variables with the indexes that you're checking for ($_POST['subTitle'] & $_POST['details']) aren't set, so the variables are empty as you reference something that isn't there.
You should do a check to ensure they are set first before trying to assign them to a variable:
$subTitle = (isset($_POST['subTitle']) && !empty($_POST['subTitle'])) ? $_POST['subTitle'] : null;
$subDetails = (isset($_POST['details']) && !empty($_POST['details'])) ? $_POST['details'] : null;
The above code will check to ensure the post index isset() and isn't empty() before assigning it to the variables.
NOTE
The variables are set when you submit the form because you are actually posting the data to the script.
You see the input attribute name? When you submit the form, they are the relevant $_POST indexes.
Just remember to ensure that the values aren't empty if you intend to print them to the markup.

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!

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

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.

PHP Fatal error: Call to undefined method resultSet::free()

I am attempting to get a function working on an old php based application, autonomous lan party. It is based on php4 but it does work with what I want it to do on a php5 server (it is also only used in an intranet environment). I'm adding an accounting add-on from here. I can understand php, but still somewhat rusty.
Below is a small sample of code I'm stuck with...
<FORM ACTION="<?php echo $_SERVER['PHP_SELF']; ?>" METHOD="post" NAME="accounting" ID="accounting">
<strong>user: </strong><br>
<SELECT NAME="userid[]" SIZE="5" class="formcolors" TABINDEX="1" MULTIPLE>
<?php
$data = $dbc->query('SELECT username,userid FROM users ORDER BY username');
while ( $row = $data->fetchRow()) {
$option = '
<OPTION VALUE="%s" class="formcolors">%s</OPTION>';
printf($option, $row['userid'], $row['username']);
}
$data->free();
unset($option, $data);
?>
</SELECT>
The problem is once it reaches te $data->free(); line, the script stops executing and supplies the error mentioned in the topic. If I comment it out (twice, there is a similar line) the script runs but once i submit the data I get another error in the logfile...
PHP Warning: mysql_escape_string() expects parameter 1 to be string, array given
I believe that error is because I've commented out $data->free(); so it's not able to get the correct result.
I've pasted the full code from the file at pastebin here (didnt want to fill this page up with all the other code).
Any help or assistance would be much appreciated. Everything else on the application works as expected.
If I understand correctly, $data is a mysql result.
To free the result from memory, try using mysqli_free_result() instead.
$data = $dbc->query('SELECT username,userid FROM users ORDER BY username');
while ( $row = $data->fetchRow()) {
$option = '
<OPTION VALUE="%s" class="formcolors">%s</OPTION>';
printf($option, $row['userid'], $row['username']);
}
mysqli_free_result($data->free());
unset($option, $data);

php - filling in form fields from database values

I'm trying to "pre-fill" (not sure if there's a technical term for this) form fields with values that the user has previously entered in the database. For this example it's a City and State. When the user loads the page to edit options, these values (which they have previously entered) will automatically be in the text boxes.
<tr><td>City</td><td><input type="text" name="city" value="<? $city = "usercity"; echo $formValue->location('$city'); ?>"></td>
<td>State</td><td><input type="text" name="state" value="<? $state = "userstate"; echo $formValue->location('$state'); ?>"></td>
Is there any way to set a value based on the input (from the boxes above)? If it was something like function location($input) I would know how to, but when there's nothing in the parenthesis, is there any way to set a value?
function location(){
$userid = $_SESSION['userid'];
$server = 'localhost';
$user = 'root';
$password = '';
$connection = mysql_connect($server, $user, $password) or die(mysql_error());
mysql_select_db(testdb, $connection) or die(mysql_error());
$result = mysql_query("SELECT '$location' FROM userinfo WHERE userid = '$userid'");
$user_data = mysql_fetch_array($result);
if($location =='usercity'){
$userlocation = $user_data['usercity'];
return $userlocation;
}
else
$userlocation = $user_data['userstate'];
return $userlocation;
}
Instead of thinking about this from a global perspective think about the problem in it's context.
Your starting point (from the server perspective) is that an HTTP GET request has come in from a client for this page, or a client is returning to this page from after a POST request. In either case, the server has located the "resource" (the PHP script) that should handle this request and dispatched it by loading the PHP interpreter with the script file.
The context at this point is at the first line of the script; at the point where the interpreter has just finished parsing and started executing. Ask yourself: does the current request include an active session identifier? If it does have an active session, then check to see if the client has filled in this form before and if they have, substitute the default form values they've previously submitted for the normal form default values. If the client does not have an active session or has not used the form before then show a blank form with default values as needed.
Tip: Consider using this technique to debug your code. Pick a line in your code and place a mental "break point" at that place. Ask yourself: what is the context of this script at this point? What variables are defined? What is the server state? What is the client expecting? Once you have an answer to those questions, writing the code is simple.
From what I see in your code you have the variable in single quotes:
$city = "usercity"; echo $formValue->location('$city');
remove the single quotes, as it will pass '$city' as is, not the value of $city. Try
$city = "usercity"; echo $formValue->location($city);
to make it clearer:
$city = "usercity";
print ('$city'); // will print $city
print ($city); // will print usercity
My last few projects had forms all over the place and telling php to fill out the forms each time was a pain in the arse.
For my current project, I kept the input names the same as the mysql field names. Makes submitting and populating way easier.
When it comes to populating the forms, I use some ajax (jQuery used all over the project so using jquery's ajax() function;
FORM
<form>
<input name="field_one" type = "text" >
<input name="field_two" type = "text" >
<input type="button" value="Send">
</form>
I put a conditional statement at the top of the doc along the lines of:
<?php if($_POST['update']){
$query=mysql_query("SELECT * FROM table WHERE unique_id='$id' LIMIT 1");
echo json_encode(mysql_fetch_assoc($query));
exit;
} ?>
Lets say you have a list of items you want to be able to click on and edit (populate the form with it's corresponding data). I assign it a data- attribute and fill it with it's unique id, normally an AI PRIMARYKEY eg:
while($r=mysql_fetch_assoc($data)){
echo "<li data-unique_id=\"\">$r[name]<span class="edit">edit</span></li>";
?>
$('.edit').click(function(){
var toget = $(this).parent().data('unique_id');
$.ajax({
url:'here so it sends to itself',
data:'update='+toget,
success:function(data){
for (var key in data) {
if (data.hasOwnProperty(key)) {
$('input[name="'+key+'"]').each(function(){
$(this).val(data[key]);
});
}
}
}
});
There's a little more work required for <select>, <textarea>, checkboxes, but same general idea applies, (I threw in a couple of if statements, but it could probably be handled way better)
I could probably explain this better, but I hope you get the idea and i've been of some help.
FYI
my inserts are like...
foreach($_POST as $k=>$v){
$v=mysql_real_escape_string($v);
$fields.=" `$k`,";
$vals.=" '$v',";
}
$fields=substr($fields,0,strlen($fields)-1);//to get rid of the comma :)
$vals=substr($vals,0,strlen($vals)-1);//and again
mysql_query("INSERT INTO ($fields) VALUES ($vals)");

Categories