I have a function called InputFilter that I use for validating/sanitizing form data and I want to know how to implement it correctly into this? I need to run it through $_GET['media']. The file that the function InputFilter is in is clean.php and if I try to include clean.php into this it makes my result pages not show when a search is performed. This script below is my search.php. Even when I paste the contents of clean.php into search.php it will make my result pages blank and I am not sure why. Is there any easy way to get this to work or a simple way to sanitize/validate $_GET['media']?
$media = isset($_GET['media']) ? $_GET['media'] : 'no_media';
switch($media) {
case 'all':
include("all_media.php");
break;
case 'only':
include("only_media.php");
break;
default:
include("def_search.php");
}
I am open to any other way of securing $_GET['media'].
The switch makes your script very save! No matter what anybody sets as media, there will be no security hole in this code.
To sanitize $_GET check the PHP method filter_input().
Related
Is it possible to submit a query without updating the URL?
On a dictionary, I want to do first one simple query: www.example.com/?q=word
On the result page there will be a button with which I want to search for more results with another query.
This second query will be done normally with www.example.com/more.php?q=word.
That code would look as follows:
<button onclick="window.location.href = 'more.php?q=<?php echo "$trimmed"; ?>';">search for more results</button>
However, I want that the URL remains unchanged so that the next dictionary query starts again with a simple query. In other words, I want to hide the part "more.php" from the URL.
Assuming that your www.example.com?q=word points to the index.php.
Assuming also that your more.php contains functions.
Assuming as third, that your index.php returns something displayable in the browser even if there is no GET-parameter i.e. the initial page call.
Doing so, a really simple solution would be to fire every query against the index.php.
There you can handle every query, even different types, based on a new GET-parameter type use use.
#index.php
require 'more.php';
// do something here to validate the parameters you use
switch($_GET('type')) {
case 'simple':
return simpleCall();
break;
case 'more':
return additionalInfo();
break;
}
function simpleCall() {
// do stuff here
// access $_GET for other paramters
}
#more.php
function complexCall() {
//do complex stuff here
}
Finally, your HTML would look something like this
<button onclick="window.location.href = '/?type="more"&q=<?php echo "$trimmed"; ?>';">search for more results</button>
Until you get more than these two types it becomes cluttering at your switch-statement.
For this reason, it would be a good idea to think about different solutions like:
having a routing system like this https://medium.com/the-andela-way/how-to-build-a-basic-server-side-routing-system-in-php-e52e613cf241
using asynchronous calls from your frontend with the help of JavaScript to call to different PHP files on the server but stay on the same page in the frontend. This will immediately lead to some kind of API. But this is generally not the badest idea.
Please validate your parameters regardless if POST or GET before you do anything with them in the rest of your code. Having the example of a dictionary sounds extremely like to query a database where SQL injection is, for example, a big thing if data us used unchecked.
I hope this helps a bit.
Yesterday I asked a question about how to include files passed in via the URL, and someone give me this:
if (isset($_GET['file'])){
include($_GET['file'].'.php');
}
But one of the answers told me to do something with this to avoid possible attacks from hackers or something like that. The problem is that I don't understand how to do it myself.
He said I should do something like this:
$pages_array=('home','services','contact').
And then check the GET var:
if(!in_array($_GET['page'], $pages_array) { die(); }
What does this do, and how do I integrate it into my original code above?
Your original code is looking for a file parameter in the URL, and then including whatever file was passed in. So if somebody goes to your PHP page and adds ?file=something.txt to the URL, you'll include the contents of something.txt in your output.
The problem with this is that anybody can manually modify the URL to try to include whatever file they want - letting them see files on your system that should be private.
The solution is to have a list of allowed filenames, like this:
$pages = array('home', 'services', 'contact');
And then before you include the file, check that it's one of the allowed filenames first.
$pages = array('home', 'services', 'contact');
if (isset($_GET['file'])){
if (!in_array($_GET['file'], $pages_array)) {
exit('Not permitted to view this page');
}
include($_GET['file'].'.php');
}
We're using a PHP array to define the list of allowed pages, checking if our page is in the list with the in_array() function, and then stopping all script execution if it's not in the list with the exit() function.
The code checks the GET information passed from the browser to your PHP page by making sure that the page name is present in your $pages_array.
As long as you list all of the pages in your $pages_array, the code will execute. If the page is not in your array list, then it will die and not be executed.
When using GET it is always beneficial to validate the code sent in this way, as arbitrary statements can be sent and executed without validation.
The code, in this instance, is being validated - so you have taken the necessary steps; as long as there is nothing more to the code that you haven't submitted.
Correct code
$pages_array=array('home','services','contact');
You almost answered your own question...
Except this line becomes...
$pages_array=array('home','services','contact');
Instead of what you had...
$pages_array=('home','services','contact').
//change the variable array declaration
$newArray = array('home','services','contact');
Just do an else statement in your if like
else {
//include your file
include($_GET['page'].'.php');
}
Basically, Your syntax for an array definition is wrong, but also why die() if $_GET['file'] is not set? would it not be better if you reverted to a default so as to fail silently.
Using in_array()
<?php
$pages_array = array('home','services','contact');
if(isset($_GET['file']) && in_array($_GET['file'], $pages_array)){
include($_GET['file'].'.php');
}else{
include('home.php');
}
?>
Or even using switch() with hard coded values.
<?php
$page = isset($_GET['file']) ? $_GET['file'] : 'home';
switch($page){
case "home" : include($page.'.php'); break;
case "services" : include($page.'.php'); break;
case "contact" : include($page.'.php'); break;
default:
include('home.php');
break;
}
?>
$pages=array('home','services','contact');
if(isset($_GET['page']))
{
$page=$_GET['page'];
if(!in_array($page,$pages))
{
die ('');
}
else {
include($page.'.php');
}
}
So, your links will look like:
yoursite.com/index.php?page=home -> with this tool:
http://www.generateit.net/mod-rewrite/
you can make nicer URL's.
I saw some websites that (for example):
if you want to view your message box, then it is: example.com/file.php?action=pm and also if you want to send a message again the address and the file is the same, but the $_GET is different : example.com/file.php?action=sendpm
How does it work?
Is it just:
if ($_GET['action'] == "pm")
{
//lots of html code(divs, forms, etc) paste here for action=pm.
}
else
{
//lots of html code paste here for action=send
}
instead of having files : pm.php, send.php ... ?Or the mechanism is different?
I saw that SMF use this mechanism and also I saw something like this for facebook.com/?ref=something.
How does it work?
The easiest way is this:
$action = isset($_GET['action']) ? $_GET['action'] : 'default';
if(!in_array($action, array('list', 'of', 'allowed', 'pages')))
$action = 'default';
include($action . '.php');
Note that the validation step is incredibly important. Not properly validating the value leads to nasty security holes from users being able to read any files your script can access to users being able to execute arbitrary code.
Putting all code in a single file like you suggested in your question is a bad idea since it results in unreadable code. Especially when mixing PHP and HTML in the same file like your question suggested (tip: use a template engine!).
This is called routing and allows a single entry point to many functions within an single application.
Requests are taken, processed and routed to the correction function. This routing pattern fits well into the Model View Controller (MVC) pattern for organizing code.
Take a look at how the Zend Framework describes MVC and Routing:
http://framework.zend.com/manual/en/learning.quickstart.intro.html#learning.quickstart.intro.mvc
You can have a switch statement. For example
example.com/file.php?action=pm or example.com/file.php?action=sendpm
if (isset($_REQUEST['action'])) {
$param = $_REQUEST['action'];
switch($param) {
case "pm":
// Code goes here
break;
case "sendpm":
// Do something here
break;
default:
// handle the default case
break;
}
} else {
// Handle it here
}
Well there are even other ways to do it !!
Switch is one of the easiest way !!
My first contact with Ajax is happening right now, and I'm kind a confused. I've read many of questions asked, but I'm not able to read the answer, that is most likely here somewhere.
Situation is, I'm using OOP PHP approach, and all I do go through index.php with parameters. So I do not call any other .php file in form posts, button clicks..
I've created an HTML listbox (which I'd like to remove vertical scrollbar, but that's just a bonus to resolve), which feeds my categories in it.
Now, by clicking each category I'd like to call certain function that would then generate output for the other div.
function swapContent(){
$("#myPresentDiv").html('<img src="../../imgs/ajax-loader-big.gif"/>').show();
var cat = $('#listbox').val();
$("#action").change(alert(cat));
var url = "&s=".cat;
$.post(url, {contentVar: cat} ,function(data) {
$("#myPresentDiv").html(data).show();
});
}
So, my JQuery script picks up correct Category, I alert it to alert dialog, so I'm sure that's fine, and then with code as it is at the moment, I reload my whole page so I get, page in page in page in page...
I'm trying to figure out how to write JQ ajax call, that would return only the results, not the whole page.
can I put URL "index.php&s="cat, and then somehow tell to ajax "go through index, call function displayresults ($cat); ?
Hope everything I wrote make sense to you :)
Tnx.
The url's your ajax function call, must return only the page parts and not the whole html document.
If you have
$.post('ajax.php',data,function(d){
$('#responsediv').html(d).show();
});
The file ajax.php must only return the page parts,like
<div>This is the new content</div>
so you will not have page inside page.
If you look at the frameworks or cms out there, they basically have routes that map calls to your index.php function to methods of the controller.
This is a complex argument, you could try to start out reading this article
Yeah, that makes sense. Your question is basically: when you get a result of an AJAX op and insert it into your page, it inserts the whole layout again, rather than the template.
OK, so the solution is to make a call to a PHP script that is "unstyled" i.e. has no template data. Your PHP script should therefore just output a short HTML snippet rather than a page (you might have a 'header' and 'footer' that can be removed for this page). What action you need to take depends what you're using on the server side - framework? CMS? Custom PHP app?
I did the exact thing for a internal app quite some time ago....What happened was i was passing the class name, function name and the function parameters via ajax variables and reading the same in php at the backend and then call the appropriate function in the class with those paraeters.
The PHP code:
$option = trim($_GET['v']);
switch ( $option ) {
case 1:
$sid = trim($_GET['q']);
$page = trim($_GET['p']);
$method = trim($_GET['m']);
$class = new $page( $link );
echo $class->$method( $sid );
break;
case 2:
$page = trim($_GET['p']);
$method = trim($_GET['m']);
$class = new $page( $link );
echo $class->$method();
break;
default:
echo '';
break;
}
But this was an internal app, so there was no injection attacks, xss,xsrf,session hijack issues....things might differ for you
Hope this helps.
I think you are searching for a GENERAL strategy to handle ajax requests its upto you
for example Server Side Ajax
unless you are using a specific framework (CI , yii etc)
You might want to look into some frameworks, as they can make this for you infinitely easier to implement:
http://demo.atk4.com/demo.html?t=20
I want to call various functions made in PHP from my javascript file. Normally using Jquery.post we call a PHP file and and pass various values as post.
function new_user(auth_type, tr_id, user_name, email)
{
$.post("bookmark.php",{AuthType:auth_type, TR_Id:tr_id, UserName:user_name, UserEmail:email});
}
If I want to create multiple functions in the PHP file and call them through jquery/ajax how do i do that?
I think everyones given correct answers here but they aren't the nicest or even radest examples.
Let's spice up your initial code a bit. Like everyone has said, you'll need to write a bit of PHP on the server side to handle what's being passed by jQuery but right now everyone's given pretty "static" versions of this methodology.
An okay example JS:
function new_user(auth_type, tr_id, user_name, email){
$.post("bookmark.php",{Function:doSomething, AuthType:auth_type, TR_Id:tr_id, UserName:user_name, UserEmail:email});
}
You can see I added a variable for the function to call "Function:doSomething". doSomething() will be the function executed server side.
This is a good way to call your functions dynamically but your variables are still sitting all together with that function var. This means you'll eventually have to write code to grab each one separately in order to pass them into that function (server side). Not very elegant.. soo we'll write an even better example...
New, and far more awesome, JS:
function new_user(auth_type, tr_id, user_name, email){
$.post("bookmark.php", {Function: doSomething, Data: [{ Authtype, TR_ID:tr_id, UserName:user_name, Email:email}] });
}
In this new example you can see I've wrapped your secondary variables/data in a Data variable. It's easier this way to pass multiple parameters to your PHP file / function.
Now: Wicked, awesome, scalable bookmark.php:
<?php
if(isset($_POST['Function'])){
call_user_func($_POST['Function'], $_POST['Data']);
}
doSomething($data=array()){
print_r($data);
}
?>
As you can see, all you have to add in your bookmark.php file is a check to make sure that the Function variable has been passed and then use PHP's call_user_func() which will call a function for you and pass in the variable Data (which is the array of values you send in your $.post()).
You'll notice I only set one parameter for the function doSomething() which expects an array. This means you could send any parameters into that function.
Any function can be called this way and you'll find wrapping all your parameters into an array helps keep everything dynamic and scalable.
If you have any questions about this code feel free to ask.
send along a variable in your post designating what function you want to call in your php file, then add a switch statement to the start of your php file and look at a designated variable say $_POST['function'], set the different conditions and have them call the corresponding function
<?php
switch($_POST['function']){
case '1': do_this(); break;
case '2': do_that(); break;
case '3': do_the_other(); break;
default: break;
}
function do_this(){
echo 'do this called';
}
function do_that(){
echo 'do that called';
}
function do_the_other(){
echo 'do the other called';
}
?>
You can add other parameters to the ajax call.
What i would do is add parameters for 'function'(string) and 'arguments'(array) so the php script on the other side knows what to do with the data being passed over.
Send an extra parameter in your Jquery post that defines what function you want to call in your PHP file. One possible example (easiest to implement):
For function 1
$.post("bookmark.php?f=1",{AuthType:auth_type, TR_Id:tr_id, UserName:user_name, UserEmail:email});
Note: Do some hardcore checking on your side to ensure someone didn't 'Fiddle' with your URL/Post variables.