Checking if an element of an array is present in another array - php

I am writing a php script which aim is to check whether any of the URLs submitted by the user in the text area are present in an array of other URLs. Unfortunately the script does not work as expected and I can't figure out how to correct it. I have the following code:
<?php
$gwt_links = $_POST['gwt_links'];
$gwt_links_exploded = preg_split('/\r\n|\n|\r/', $gwt_links);
$blacklisted = file('blacklist.txt');
foreach ($gwt_links_exploded as $gwt_link) {
if (in_array($gwt_link, $blacklisted)) {
echo 'link found';
}
else {
echo 'link not found';
}
}
?>
If I submit URLs in a text area, the script returns 'link not found' even if the URLs are present in blacklist.txt file. I suppose the problem lies in reading the file into an array - I think some special characters must be added. I tried removing them by trim, however without success... How should I correct the script to make it work?

Related

How Mobile number validation varies with the URL?

I have written mobile number validation script as you can see in below.the problem it is working fine with the URL1.but not with the URL2.I want to know why is that?
URL1 - http://axbc.com/con/s2.php
URL2 - http://axbc.com/con/s2.php?key=d908e8401774411861043
Here is my Code
if(isset($_POST['btn-signup']))
{
$mobilenumber = $_POST['mobilenumber'];
if(!empty($dialogmobilenumber)) // phone number is not empty
{
if(preg_match('/^947\d{8}$/',$mobilenumber)) // phone number is valid
{
echo 'success';
}
else // phone number is not valid
{
echo "<script>alert('Mobile Number is Not valid.. Format should be ');
</script>";
}
}
}
Your code is working fine for me in both urls.
It is doing, what it is meant for, It is matching all the 11 digit numbers starting from '947'+8 nos.
As, you are not using the passed variable anywhere in this piece of code,So it can never be the cause of your error.
One thing,You are receiving mobilenumber as POST in $mobilenumber variable.
So,why are you using $dialogmobilenumber to check if it is empty or not ?
Have you defined this anywhere in the program.
if(!empty($dialogmobilenumber)) // phone number is not empty
{ ...
Another thing, Is your form also present in s2.php ?
If not, what is your action contains (action="?") for the form ?
Note: If you can paste the complete code and output that you are getting for
URL2, that will be good.

Issue Passing JS variable to PHP include file

I have a php file where I am using it to setup dynamically generated pages based on the input variables. It starts on and index.html page where the variables are gathered some of which are not simple strings but complex Google Earth objects. On the submit of that page it is posted to another page and you are redirected to the created file. The trouble is coming when I try to use that variable within the php include file that is used to generate the pages.How do i properly get a variable from this form and then pass it through to be able to use it on the new generated page. Here is what I am trying currently.
On the click of this button the variable flyto1view is set.
$("#flyto1").click(function(){
if (!flyto1view){
flyto1view = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
$("#flyto1view1").val(flyto1view)
}
else {
ge.getView().setAbstractView(flyto1view);
}
});
Then from here I have tried setting the value to an hidden field but Im not sure if that kinda of variable has a value that can be set like that. Whats the best way to get this variable to here after post
<?
if (isset($_POST['submit']) && $_POST['submit']=="Submit" && !empty($_POST['address'])) {//if submit button clicked and name field is not empty
$flyto1view1 = $_POST['flyto1'];
$address = $_POST['address']; //the entered name
$l = $address{0}; // the first letter of the name
// Create the subdirectory:
// this creates the subdirectory, $l, if it does not already exists
// Note: this subdirectory is created in current directory that this php file is in.
if(!file_exists($l))
{
mkdir($l);
}
// End create directory
// Create the file:
$fileName = dirname(__FILE__)."/$address.html"; // names the file $name
$fh = fopen($fileName, 'w') or die("can't open file");
// The html code:
// this will outpout: My name is (address) !
$str = "
<? php include ('template.php') ?>
";
fwrite($fh, $str);
fclose($fh);
// End create file
echo "Congradualations!<br />
The file has been created.
Go to it by clicking here.";
die();
}
// The form:
?>
Firstly. creating files from user input is pretty risky. Maybe this is only an abstract of your code but doing a mkdir from the first letter of the input without checking that the first letter is actually a letter and not a dot, slash, or other character isn't good practice.
Anyway, on to your question. I would probably use $_GET variables to pass to the second file. So in the second file you use <?php $_GET['foo'] ?> and on the first file you do:
echo "Congradualations!<br />
The file has been created.
Go to it by clicking here.";
You could also echo the variable into your template like so:
$str = '
<?php
$var = \'' . $flyto1view1 . '\';
include (\'template.php\')
?>';

how would i clear previously echoed result without affecting any other functions in php?

I am currently working on website where it has a search box to search for specific items. The page echos out results in table format. So far everything works perfectly but when I try to filter the result(depending on features), I get two sets of results. One with previously displayed result table and the other is the filtered result. I do not want previous result to display back again on screen without affecting any other procedure. Something like sessions?? I do not know exactly how to deal with this situation.
<?php
include'search.php';// form for a search box.
if (isset($_POST['search_name'])) {
$search_name=mysql_real_escape_string(htmlentities(trim($_POST['search_name'])));
$errors = array();
if (empty($search_name)){
$errors[] ='please enter a search term';
}
else if (strlen($search_name)<3){
$errors[] = 'your search term must be three or more characters';
}
else if (1==2){
$errors[] ='your search for '.$search_name.' returened no results';
}
if (empty($errors)){
filter($search_name); //it display another form in the navigation bar to filter the search result.
search_results($search_name);//searches for all the result onthe database depending on the keyword entered in searchbox.
} else{
foreach($errors as $error) {
echo $error,'</br>';
}
}
}
?>
See this code:
echo 'world';
echo 'hello !';
You can intercept the echo using ob_start(), ob_get_contents() and ob_clean().
ob_start();
echo 'world';
var $echoed = ob_get_contents();
ob_clean();
// real echo
echo 'hello ' . $echoed . '!';
// now you see
// hello world!
Because the ob 'output buffering' is native to PHP, you can use it with anything like functions, includes and so on. I'm using this approach, to intercept (1.) outputs in my controller flow, and to intercept (2.) the view's output, so I can compose them later (for example to render PHP errors into a debug div.

Codeigniter output and input security

In case of user submitted text, when outputting to the page, what text filter do you use both in input and output?
As I understand it, using $this->input->post('something',true) will clean XSS content from the input data, so there is no other thing to do to be secure? Something like htmlspecialchars(), strip_tags(), etc.?
Also i would like to know if for example htmlspecialchars() is good to use, why CI security library doesn't applyes htmlspecialchars() by default to the passed string?
You should use the form_validation library. You can do rule based checking and filtering. This is a much more robust way of validating input data.
Here are the built in rules and any defined function that takes one parameter can be used as a filter/rule.
required
matches
min_length
max_length
exact_length
greater_than
less_than
alpha
alpha_numeric
alpha_dash
numeric
integer
decimal
is_natural
is_natural_no_zeroetc
valid_email
valid_emails
valid_ip
valid_base64
Kinda depends on what you're doing with this input, but most likely you're going to want to run the string through htmlspecialchars() also.
To my understanding, you would like to store user submitted text in a database, and then later display it on a page -- kind of like a basic commenting system or something. You just don't want any naughty/incomplete HTML characters breaking your page when outputting it.
Whenever you have user submitted data, you want to utilize the form_validation library to clean it up and sanitize it as much as possible as a good security measure. If it goes to your database, you should use Active Records or Query Binding to get additional security from Codeigniter, such as escaping the strings, etc.
Let me show my solution on submitting and outputting user's input on a website. There are probably better ways to do this, but this will get the job done.
<?php
/*Controller
**************************************************/
class Something extends CI_Controller {
function comments_or_whatever() {
//Required -> trim value -> max_length of 100 -> strip HTML tags -> remove additional HTML entities missed by strip tags
$this->form_validation->set_rules('input_1', 'The First User Input', 'required|trim|max_length[100]|xss_clean|strip_tags|callback__remove_html_entities');
$this->form_validation->set_rules('input_2', 'The Second User Input', 'trim|exact_length[11]|xss_clean|strip_tags|callback__remove_html_entities');
if ($this->form_validation->run() == FALSE) {
//form didn't validate.. try again display error messages
$this->load->view('your_view');
}
} else {
$input_1 = $this->input->post('input_1');
$input_2 = $this->input->post('input_2');
$submission_array = array(
'db_field_1' => $input_1,
'db_field_2' => $input_2
);
$this->load->model('comments');
$result = $this->comments->submit_comments_or_whatever($submission_array);
if ($result['is_true'] == TRUE) {
//creates a temporary flash message and redirects to current page
//if on a windows server use 'refresh' instead of 'location'
$this->session->set_flashdata('message', '<div class="message">'.$result['message'].'</div>');
redirect('something', 'location');
} else {
$data['message'] = $result['message'];
$this->load->view('your_view', $data);
}
}
}
// Very important to get rid calling HTML Entities via HTML number codes such as &#60 etc. Strip_tags does not do this.
// This is privately called during validation from the callback__remove_html_entities custom callback
function _remove_html_entities($submission) {
$submission = preg_replace("/&#?[a-z0-9]{2,8};/i","",$submission);
return $submission;
}
}
/* Model
****************************************/
class Comments extends CI_Model {
function submit_comments_or_whatever($submission_array) {
// Active record escapes string and does additional security
$query = $this->db->insert('comments', $submission_array);
if ($query == TRUE) {
$data['is_true'] = TRUE;
$data['message'] = 'Your message has been successfully shared!';
return $data;
} else {
$data['is_true'] = FALSE;
$data['message'] = 'Sorry, but there was an error dude inserting your message into the database.';
return $data;
}
}
}
/* View -> your_view.php
****************************************/
<?php echo validation_errors('<div class="message">', '</div>'); ?>
<?php echo $this->session->flashdata('message'); ?>
<?php if (!empty($message)) echo '<div class="message">'.$message.'</div>'; ?>
<?php echo form_open('something/comments_or_whatever'); ?>
<?php echo form_label('The First User Input', 'input_1'); ?><br>
<?php $input_1_form = array('name' => 'input_1', 'id' => 'input_1', 'value' => set_value('input_1')); ?>
<?php echo form_input($input_1_form); ?><br>
<?php echo form_label('The Second User Input', 'input_2'); ?><br>
<?php $input_2_form = array('name' => 'input_2', 'id' => 'input_2', 'value' => set_value('input_2')); ?>
<?php echo form_input($input_2_form); ?><br>
<?php echo form_submit('submit', 'Dude, submit my user inputed text!'); ?>
<?php echo form_close(); ?>
This code assumes you autoload the Form Validation, Sessions, and Database Libraries and the Form Helper. Now, all your user inputed data is stripped to a bare minimum of plain text using a custom Regular Expression call back during form validation. All naughty HTML characters are gone/sanitized, completely. You can now be worry-free to output the submitted data anywhere you'd like on a webpage without it breaking or being a security concern.
The problem with just doing HTMLSpecialChars() and html decode is it doesn't account for incomplete HTML tags. Hopefully this helps, best of luck dude, and as always, nothing is ever completely secure.

Codeigniter simple validation callback not working

UPDATED
I'm creating a codeigniter callback for validating an input where users enter programming tags for example php, js, jquery. Values are separated by commas.
I want to show a message if you enter duplicate tags for example php, jquery, php, js where php would be the duplicate.
First in my controller I set the validation rules for the 'user_tags` input
$this->form_validation->set_rules('user_tags', 'User Tags', 'callback_user_tags_dublicates', 'trim|xss_clean|max_length[100]|regex_match[/^[a-z,0-9+# ]+$/i]');
Then the callback
<?php function user_tags_dublicates($str)
{
$val = $str; //the input value (all the CSV)
$tags = str_getcsv($val); //creates an array of the CSV
if(count($tags) != count(array_unique($tags))) //if array not equal to unique array it contains duplicates
{
$this->form_validation->set_message('user_tags', 'The %s field can not have duplicate tags.');
return FALSE;
}
else
{
return TRUE;
}
} ?>
and finally in the view I show my error.
<?php echo form_error('user_tags'); ?>
When I enter duplicate tags I get
Unable to access an error message corresponding to your field name.
I'm not sure what I'm doing wrong. I tested the function in a static page without validation rules and it works.
set your error message for user_tags inside your user_tags_dublicates() function
$this->form_validation->set_message('user_tags', 'The %s field can not have duplicate tags.');
This might sound stoopid but have you checked:
$tags = str_getcsv($val); //creates an array of the CSV
actually returns the tags properly?

Categories