Prevent img tag on error prompt xss for GET [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to know how to prevent this type of xss, i've been trying for about 4 hours but nothing works.
"><img+src%3Dx+onerror%3Dprompt('XSS')>
This is what I use to prevent xss:
$term = mysql_real_escape_string($_GET['term']);
$term = strip_tags($term);
This is how I print the results:
echo "<i>Search results for <b>" . strip_tags($term) . "</b> based on the <b>Name</b> of the servers</i><br /><br />";
Here is my full php code:
<?php
$term = strip_tags($_GET['term']);
$keywords = preg_split('#\s+#', $term);
$c = 0;
foreach($keywords as $keyword){
if(strlen($keyword) < 3){
$c++;
}
}
if($c > 0){
$errors[] = "One of the keywords you entered is too short.";
}
if(strlen($term) < 4){
$errors[] = "Search string too short!";
}
if(empty($errors) !== true){
echo output_errors($errors);
} else {
echo "<i>Search results for <b>" . strip_tags($term) . "</b> based on the <b>Name</b> of the servers</i><br /><br />";
$name_where = "`name` LIKE '%" . implode("%' OR `name` LIKE '%", $keywords) . "%'";
$query = mysql_query("SELECT * FROM `servers` WHERE {$name_where} AND `disabled` = 0");
?>

$term = filter_var($term, FILTER_SANITIZE_STRING);
Maybe try someting like this:
$term = filter_var($term, FILTER_SANITIZE_STRING);
$term = filter_var($term, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
Theres a lot of filters with which you can filter like everything out.
The advantage of filter_var() is that you can control the behaviour by, for example, stripping or encoding low and high characters.
Here is a list of filters: Filters

You can also filter_input to get external variables and optionally filter them.
<?php
// FILTER_SANITIZE_SPECIAL_CHARS filter HTML-escapes special characters
$term = filter_input(INPUT_GET, 'term', FILTER_SANITIZE_SPECIAL_CHARS);
// FILTER_SANITIZE_STRING strips or encodes unwanted characters
$term = filter_input(INPUT_GET, 'term', FILTER_SANITIZE_STRING);

Related

how to store and edit the mobile number with country codes?

I've asked once but I didn't get the answers.
var phoneno = /^\+?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
this is how I learnt to validate the numbers + error and...
I also have the Mobile bigint(20) & country varchar(200), in my table "users".
what I want to do is to use another file "countries.php" to get their codes in mobile input in "signup.php" page and store them both into the database.
for example, user chooses 'US +1' the country code will appear in mobile section.
$countryArray = array(
'AD'=>array('name'=>'ANDORRA','code'=>'376'),
'AE'=>array('name'=>'UNITED ARAB EMIRATES','code'=>'971'), ...
function countrySelector($defaultCountry = "", $id = "", $name = "", $classes = ""){
global $countryArray; // Assuming the array is placed above this function
$output = "<select id='".$id."' name='".$name."' class='". $classes."'>";
foreach($countryArray as $code => $country){
$countryName = ucwords(strtolower($country["name"])); // Making it look good
$output .= "<option value='".$code."' ".(($code==strtoupper($defaultCountry))?"selected":"").">".$code." - ".$countryName." (+".$country["code"].")</option>";
}
$output .= "</select>";
return $output; // or echo $output; to print directly
}
not to mention I downloaded the file zip. and I don't really know how to add or use the " use", please be more specific, like give with examples. thanks

How to not update database if $_POST value is empty?

I have been having problems with a form of an website of mine. The form values are equal to their corresponding $_POST values, which are the parameters used for updating the database.
I do not want for empty form values to be updated. However, I don't want any of the input areas to be obligatory.
That means that I would be able to update only specific content, not needing to type the values in the input areas I do not want to update. I'm having problems with this, however. Empty form values are being uploaded, so the values in the database are being changed into blank values. I've looked for tutorials in SO and over the internet, and the only (functional) ones are those which turn input boxes into obligatory. That is not how I intend it to work, so it doesn't fit.
I think the best way to do this, and I am not sure, is to change, through javaScript, the "name" attribute of the input areas into blank when the submit button is set IF the values equal empty or null. I do not know how to do this, nor do I know if this is possible, or the best way.
Here is my current code on the matter:
(first, the form an the javascript)
<script>
function validade(){
var formId = document.getElementById("configForm");
var allInputs = formId.getElementsByTagName("input");
var input, i;
for (i=0; input = allInputs[i]; i++){
if (input.value == null || input.value == "") {
input.name = "";
}
}
}
<form method="post" action="" id="configForm">
<label for="home">Home:</label>
<br>
<input type="text" id="home" name="home">
<br>
<label for="apendix">Apêndice:</label>
<br>
<input type="text" name="apendix">
<br>
<label for="about">Sobre:</label>
<br>
<input type="text" name="sobre">
<br>
<label for="contato">Contato:</label>
<br>
<input type="text" name="contato">
<br><br>
<input type="submit" value="Carregar" name="submit">
</form>
<?php require_once('editaForma.php'); ?>
(Secondly, the database query and $_POST values:)
<?php //credentials
if (isset($_POST["submit"])){
$server = 'hypotetical';
$user = 'hypotetical';
$pw = 'hypotetical';
$BD = 'hypotetical';
//estabelece a conexão
$conn = mysqli_connect($server, $user, $pw, $BD);
if (!$conn) {
die ('<span style="color: #FF0000;">"connection failed: "</span>' . mysqli_connect_error());
}
$home = $_POST["home"];
$apendix = $_POST["apendix"];
$sobre = $_POST["sobre"];
$contato = $_POST ["contato"];
$query = "UPDATE form SET
home= '$home',
apendix= '$apendix',
sobre= '$sobre',
contato= '$contato'
WHERE id='1'";
//$query = "INSERT INTO form (home, apendix, sobre, contato) VALUES ('$home', '$apendix', '$sobre', '$contato')";
if (mysqli_query($conn, $query)){
echo "Alterações feitas com sucesso";
} else {
echo "ERRO!" . $query . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
Yes, I know the DB is prone to SQL injection. I'm trying to get everything up and running first, and once all of this is set, I'll look onto security matters before the website is online.
I've been having this problem for over a week and can't figure a way out of it.
Thank you for your time and attention, in advance.
EDIT
I wish I could select two answers for the solving ones. Both of them right down led me to the solving of the problem, each helping me to see the holes in my code. As I cannot choose both, I chose the one who helped me to solve the last issues. Thank you all so much!
Build your query dynamically, by skipping empty values
$p = &$_POST; //make $p refer to $_POST
$query = "UPDATE from SET ";
if($p['home']) $query .= " home = '$p[home]' ,";
if($p['apendix']) $query .= " apendix = '$p[apendix]' ,";
if($p['sobre']) $query .= " sobre = '$p[sobre]' ,";
if($p['contato']) $query .= " concato = '$p[contato]' ,";
$query = trim($query, ','); //remove any trailing comma
$query = "WHERE id = 1";
you can then execute the query. Oh and don't forget to check that at least 1 of the variables was available. If they're all empty, don't execute.
And yeah, your code is highly vulnerable.
Glaring security holes aside, I would usually build up a string, something like this:
$home = $_POST["home"];
$apendix = $_POST["apendix"];
$sobre = $_POST["sobre"];
$contato = $_POST ["contato"];
$query = "UPDATE form SET ";
if(!empty($home)) {
$query .= "home= '$home',";
}
if(!empty($apendix)) {
$query .= "apendix= '$apendix',";
}
if(!empty($sobre)) {
$query .= "sobre= '$sobre',";
}
if(!empty($contato)) {
$query .= "contato= '$contato',";
}
// strip off any extra commas on the end
$query = rtrim($query, ',');
$query .= "WHERE id='1'";
Building the query with the comma at the end also allows you to easily add more options later if you need to.
I did it, in a simple way using NULLIF
set potato = NULLIF(potato,'')

Reading variable number of lines from file php [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
How do I read specific number of lines from a txt file? For example I have a txt file which has 100 lines, and I need to print 25 or 50 lines to my website? I searched website and was not able to find how to do this using php or javascript. Thanks!
For now I have
<?php
if( isset($_GET['submit']) )
{
$pavadinimas = htmlentities($_GET['pavadinimas']);
$result = Myfunction($pavadinimas);
$string = file_get_contents("istorija.txt");
$array = explode(PHP_EOL, $string);
function Myfunction($pavadinimas){
For($i=0;$i<=$pavadinimas($array);$i++){
echo $array[$i] ."<br>\n";
}
}
}
?>
<?php if( isset($result) ) echo $result; //print the result above the form ?>
<form action="administratorius.php" method ="GET" >
Įrašų skaičius:
<input type="text" name="pavadinimas" maxlength="30" value="<?php echo $form->value("pavadinimas"); ?>"> <br>
<input type="submit" name="submit" value="Prideti">
</form>
I want that my input would be as a variable for function. How do I make it work? Thanks!
You need to explode the string on [return].
$string = file_get_contents("file.txt");
$array = explode(PHP_EOL, $string);
Edit: EOL is better. Had forgot about it.
Edit2:
For($i=0;$i<=count($array);$i++){
echo $array[$i] ."<br>\n";
}
This above code will output the full textfile.
$i=0 means start at first line.
$i<=count($array) keep going till end of file. This can be changed to $i<=15 and you only output 15 lines.
$i++ means count up with one at the time.
And then there is a echo to output the linenumber $i
EDIT: I'm not sure what you are trying to do. But this is my best guess of your code:
if( isset($_GET['submit']) ){
$pavadinimas = htmlentities($_GET['pavadinimas']);
$result = Myfunction($pavadinimas, 25); //reads 25 rows of the pavadinimas
$string = file_get_contents("istorija.txt");
$array = explode(PHP_EOL, $string);
$result2 = Myfunction($string, 50); // reads 50 rows of istorija.txt
function Myfunction($pavadinimas,$NoOfRows){
For($i=0;$i<=$NoOfRows;$i++){
$returnstr .= $pavadinimas[$i] ."<br>\n"; // this appends the $returnstr with the next row
}
return $returnstr; // returns it to where the function was called.
}
}
Now $result and $result2 are 25/50 rows of each variable (pavadinimas/string).
You have not given me alot to go on to what you want, your code is beyond what I understan. But this is probably what you wanted.

Get var from a PHP page [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm having a problem with my PHP. I would like to send data from my page to another page. But it's all in PHP. I need to take an input value and a combobox value. And I don't know how to do it.
Here's my PHP :
<?php
session_start();
$q = intval($_GET['q']);
$db = mysql_connect('localhost', 'root', 'root');
mysql_select_db('Projet',$db);
$sql2 = "select IDControle, NomControle from Controle WHERE IDUser='".$_SESSION['id']."'";
$req2 = mysql_query($sql2) or die('Erreur SQL !<br>'.$sql2.'<br>'.mysql_error());
echo'<select id="controleChoix" name="controleChoix">';
while ($data2 = mysql_fetch_array($req2)){
echo '<option value="'.$data2['IDControle'].'">'.$data2['NomControle'].'</option>';
}
echo '</select>';
echo '<input type="hidden" name="selected_text" id="selected_text" value="" />';
$sql = "select ID, Nom, Prenom from User where Groupe ='".$q."'";
$req = mysql_query($sql) or die('Erreur SQL 2!<br>'.$sql.'<br>'.mysql_error());
echo '<ul class="list-group">';
while ($data = mysql_fetch_array($req)){
echo '<li class="list-group-item"><strong>Nom</strong> : '.$data['Nom'].' <br> <strong>Prénom</strong> : '.$data['Prenom'].'<br>';
echo '<input type="text" name="note" id="note"/> ';
echo '<a class="label label-success" href="ajouterNote.php?var1='.$data2['IDControle'].'&var2='.$data['ID'].'&var3='.$test.'"><i class="fa fa-fw fa-check"></i></a></li>';
}
echo '</ul>';
echo '<a class="btn btn-primary" href="#">Ajouter toutes les notes</i></a></li>';
?>
I need to send the input note.value, the select controleChoix.value and the intval q that I've received from another page.
As you already seem to use SESSIONS, you could easily transfer your data from one page to another using these $_SESSION variables.
https://secure.php.net/manual/en/book.session.php
edit: Please keep in mind that this isn't secure at all. The values can easily be changed by the user. Using this you might want to validate the values first, before using.

PHP Mysql Insert Into not working, no error given no data posted to DB, earlier the same page was working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have problem regarding noted above. My code in php is as under:
$con = mysql_connect(xxxx,xxx,xxx) or die(mysql_error());
mysql_select_db(xxx) or die(mysql_error());
if (count($_POST) > 0) echo "form submitted";
if(isset($submit))
{
$name = $_POST['std_name'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$user_type = "student";
if(mysql_query("insert into login (user_id, user_pass, User_type) values ('$email','$pass','$user_type'", $con))
{
echo "<p class='success_msg'>Congrats! your registration has successfully been done.</p>";
echo mysql_error();
}
else
{
echo mysql_error();
}
Earlier this code was working well and the values were being entered into database. but suddenly it is not working and not even giving any error. any help in the regard will be highly appreciated, please.
$submit is not set in the code sample
You are missing a closing bracket at the end of your query
Read about 'SQL injection', your code is vulnerable
Here's what might help...
Connect to your MySQL database via PHPMyAdmin or via SSH.
Once connected, type the query manually (so, INSERT INTO login() etc) — if it works, then it's a bug further up your code. If this is the case, you need to show us more.
OK, so I've applied a nice PDO version down below.
$host = "localhost";
$port = 3306;
$dbname = "myDatabase";
$user = "myUser";
$pass = "myPass";
$db = new PDO("mysql:host=" . $host . ";port=" . $port . ";dbname=" . $dbname, $user, $pass);
echo (count($_POST) > 0) ? echo "form submitted" : "";
if(isset($submit))
{
$name = $_POST['std_name'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$user_type = "student";
$query = $db->prepare("INSERT INTO login(`user_id`, `user_pass`, `User_type`) VALUES (:email, :pass, :utype");
$binds = array(
":email" => $email,
":pass" => $pass,
":utype" => $user_type
);
if($query->execute($binds))
{
echo "<p class='success_msg'>Congrats! your registration has successfully been done.</p>";
}else{
echo "\nPDO::errorInfo():\n";
print_r($db->errorInfo());
}
}
Read the PDO documentation here.

Categories

Resources