JavaScript (document.write(function())) value into php MySql insert statement - php

$name="document.write(get_name());";
echo $n= $name; // Here it prints name also (correct one)
$sql=mysql_query("INSERT INTO tab1 (name,visited_time) values ('$n',NOW())");
Ideally this should print got name from the function but it inserting
document.write(get_name());
Note : get_name function is returning the value correctly. and function is mandatory. Only the problem is it inserting document.write(get_name()); instead it's value.

It looks like you missed an important chapter about PHP / JS programming...
PHP code is executed server side.
JavaScript code is executed client side.
Steps to solve this are:
whenever you need this query to be executed, you need to make a call from JavaScript to PHP and pass the variables to the PHP. You can do this with an asynchronous call with jquery for example:
// JS, executed on client side
var name = get_name(); // this javascript function must exist
$.get("path/to/your/page.php", {"name":name});
More info about jQuery here: http://api.jquery.com/jQuery.get/
then, in PHP, you get this value from the global $_GET and you can use it:
// php code that will be executed when path/to/your/page.php will be called
$name = $_GET['name'];
$sql = "INSERT INTO tab1 (name,visited_time) values ('" . $name . "',NOW())";
$rs= mysql_query($sql);
And that will do what you expect.
You can use this code to implement the logic, but it requires lots of improvements then:
It is highly unsecured and leaves room for the most simple SQL injection attack. You must "quote" all values you use in your SQL queries (you can't trust any data coming from the client)
$_GET['name'] may not exist or contain what you except so you need to use function like isset and to do more tests after to verify that nobody is trying to hack your variable
you should POST method and not GET since this HTTP call will result in changing the state of the datbase
mysql_query is deprecated: http://us2.php.net/manual/en/function.mysql-query.php you should use mysqli_query or PDO...
I'm not gonna talk about all these topics, they are highly covered on the web and a simple search your favorite search engine will give all the information you need.
Note: I wrote that "JavaScript code is executed client side". This is not exactly true since it is possible to build a server in JavaScript but this is far far far away from you concern and that wouldn't even change the fact that you still need to send the value from the client to the server with the kind of logic I just described.

Related

PHP runs a storing procedure on a database, how can I see concrete parameters passed into without altering source code?

Here is php code:
$query = Container::get('db_connection')
->prepare('sp_Util_SearchMemberByKeyWord');
$query->bind('szSort', $searchcol, DatabaseTypes::NVARCHAR(100))
->bind('szKeyWord', $searchstr, DatabaseTypes::NVARCHAR(100))
->bind('partnerid', $partnerid, DatabaseTypes::INT)
->bind('hideDisabled', $hideDisabled, DatabaseTypes::INT)
->bind('hideDemo', $hideDemo, DatabaseTypes::INT)
->bind('hideByLmtdAccountManagerUserID',
$hideByLimitedAccountManagerUserID, DatabaseTypes::NVARCHAR(100))
->execute();
I need to see exact values of the params passed into the storing procedure. There is no way I can debug or alter source code. Google Chrome (or any other browser) seems to be only one option. I also got access to the appropriate database. Can I capture those values somehow using built-in Chrome functionality or some advanced features of SQL Management Studio?
P.S. I am not php dev, not at all.
The simplest way to see variables in PHP is using the var_dump(); and exit;
Use it before your code.
For example:
var_dump($searchcol); exit;

mysql table won't update when using php UPDATE

I have a HTML page for updating a mysql table, and when the user is finished modifying it clicks a "submit" button at the bottom of the page, named 'valider'. I use POST method and the action leads to a php page with the UPDATE request but it won't update. I've tried putting the values from the previous page into variables before using them in the request but it still won't work. Here is the php code:
<?php
include_once("connexionMysql.php");
if(isset($_POST['valider'])){
$titreIci=$_POST["titre"];
$idIci=$_POST["id"];
$envoie= "UPDATE AY_albums SET titre='$titreIci' WHERE id='".$idIci."'";
}
header("Location: pageDaccueilAdmin.php");
?>
The "id" must be an int in your database and you are casting it as string this may cause issue also check your config file:
remove the header redirection to see if there is an error.
CAREFUL !! You have a BIG mistake in you code: you don't control the $idIci parameter!! so it is highly vulnerable about SQL injection attacks!! Anyone can wipe you database or deface you website...
Firstly, I suggest to control $idIci:
$idIci = $_POST['id']
if (!is_numeric($idIci))
{
echo "Bad parameter!!";
exit;
}
Or use PDO->bindParam() method... And where do you execute the query?
You should send $invoie variable to some function which send it to database server. Like PDO::query($invoie);
The code shown in the question is simply assigning a string value to a variable.
That's all it's doing.
There's no execution of a SQL statement.
The contents of that variable are not getting sent to the database to be executed as a SQL statement. That's not happening, no matter how much you make the string look like a SQL statement. It's not going to be executed as a SQL statement unless your code makes that happen.
And fair warning... when the code does send that string to the database as a SQL statement, the code is going to be vulnerable to SQL Injection.
Check var_dump($_POST); and see what data you have before SQL update line. You probably sent the wrong data. Also, use $idIci = (int) $_POST["id"]; because of security reasons.

Where to validate variables (to make it a well designed pattern)?

Lets say I have an index.php file and some $_GET variables. After a few hundred lines of code I call a method, with the variables as parameters.
Should I validate the variables on top of everything, or should I validate them inside the class/method I call?
2 things in mind:
Avoiding to validate the variables multiple times, everywhere..
Having multiple sources, not only $_GET, and multiple calls to such a method from different files.
Some code:
<?php
function do_something($string) {
// Validate $string here?
}
// ...or here, before using it?
$result = do_something($_GET['some_string']);
This is a question where's no standard solution possible.
You could write yourself a helper class (i recommend this since this is a solution with less maintanance and best flexibility) which is called at the very first beginning of your index.php file, as some kind as a "contract" which is like:
<?
require_once "validator.php";
$validator = new Validator();
$validated = $validator->validateGet($_GET);
// all the remaining site's php code goes here
?>
this class could return anything you want, such like a boolean indicating whether every variable is okay or not, or an array containing the values with removed tags, etc.
Another barrier for cross site scripting and/or SQL injection should be prepared statements: http://php.net/manual/de/pdo.prepared-statements.php
All your SQL queries should also be contained in a external utilities class called ProductDataAccessObject (ProductDAO) or ProductQuerier, etc., which is also for structural/maintanance reasons.
But there's no rule that says "you must validate your variables at the very first beginning or at time of use"
Validate at the very first point when you are receiving $_GET at the entry level so that you are sure for the below code at later stage as well-
// Validate $_GET['some_string'] HERE
$result = do_something($_GET['some_string']);
If you validate here -
function do_something($string) {
// Validate $string here?
}
then there is a possibility that u miss the validation and it will open a loop hole in the code as validation is available only to the method this time.
If you are setting some values for the database, it is a good practice to double check the data and make it safe from code injections.
You can validate on top of the page your every single variable with a one line
$_GET = array_map("mysqli_real_escape_string",$_GET);
Array_map applies one function over every value of an array which in our case is applying mysqli_real_escape_string to the array $_GET
IMPORTANT:
Please do note this is only for sanitization and not validation
You need to validate every variable by your own, for example if what is being sent in an integer, make sure to use intval to validate it
Refer to this question for more information: Sanitization and Validation
I'm not satisfied with your answers yet, I did not ask HOW to validate, I did ask WHERE to do it.
Here is my own suggestion:
As I think the times for procedural coding in PHP are finally over (!!), I dont have any logic inside of my index.php, all logic goes into controller classes.
So you have a data Sender, and data Reciever.
As a Reciever (not only in PHP, it's something very common in realife, too), I have to validate the information sent by the Sender. The Reciever does not trust anybody (this is important in APIs for example). Therefore, validation has to be inside the methods you create, not at the top of index.php files or outside of a class. Imagine someone else using your method, is he going to validate the arguments, or has it been YOUR task? I think it's up to you, so you (the Reciever!) can throw Exceptions.
I also like to keep my data ($_GET, $_POST, ...) as raw as possible outside of the controller. Imagine you have a method which needs validated data at line 100, and a method at line 200 which needs raw data. Now on liee 5 you changed the raw into sanitized. => You have to keep two variables, $data and $data_raw, which is unnecassary overhead.
Think about it

Where the PHP $_GET superglobal can be used

Can the PHP superglobal $_GET be used and work as intended outside of the form tags? For example, can I do $_GET('select box id') outside of the form tags and have it work as intended?
<?php
---Placeholder for DB login info---
switch($_GET['select box id'])
{
case "text shown for second option of select box":
$query = mysql_query("placeholder for actual query");
$row = mysql_fetch_row($query);
$textboxValue = $row[0];
break;
}
?>
Can the PHP superglobal $_GET be used and work as intended outside of the form tags?
Yes. The position of PHP code within HTML is entirely irrelevent except in determining where output will appear in a document.
$_GET['select box id']
Form controls use their names for submission keys, not ids.
mysql_query
Read the big red warning box on the documentation page for that function.
If this is for login info, you should not be using a get request anyway--you should be using post.
But at any rate, yes it should work. As long as the data is sent with the query, it should work.
That said, you may also want to do some research into some basic security aspects, such as validating and sanitizing inputs. Otherwise, you may wind up opening yourself up to some rather nasty attacks.
I would recommend the book Essential PHP Security from O'Reilly Press. I would also look into using something like MySql PDO for making database queries, as it tends to be more reliable and secure than simply using mysql_query.
Superglobal means available for use anywhere/everywhere.

How do I send a variable in a URL through AJAX?

I'm sending the variable like this:
xmlhttp.open("GET","insert-karma.php?pid=<? echo $pid; ?>",true);
The AJAX part doesn't seem to be the problem, if I check the Sript the PHP is echoing the integer correctly. (It displays the url as: insert-karma.php?pid=5). However the PHP isn't getting the variable. (I tried echoing and it does't show anthing)
This is the PHP file:
// Connect to db;
$pid = $_POST['pid'];
$sql="UPDATE Poems SET Karma = Karma + 1 WHERE Pid = '$pid'";
// Disconnect form database;
What am I doing wrong? How do I manage to send $pid to the PHP update-karma.php?
try $pid = $_GET['pid']
or
$pid = $_REQUEST['pid'];
You are sending the variable using GET, so in your php you have to use the $_GET variable
$pid = $_GET["pid"];
Also avoid using your variable directly in your sql query. you will be vulnerable to sql injection.
if using mysql:
$pid = mysql_real_escape_string($_GET["pid"]);
or in case you are passing an integer:
$pid = (int)$_GET["pid"];
first you should not use PHP in you ajax requests it's just make things more complicated and PHP is for server side scripting in the first place
secound , you should use xmlhttp.open("POST","insert-karma....) if u plain to use POST
Third the only important difference (not the only but the important) between POST and Get is :
GET requests can be cached
GET requests can remain in the browser history
GET requests can be bookmarked
GET requests can be distributed & shared
GET requests can be hacked lool
so u cant use Get For unsecured and dangerous action like LOGIN OR ...
POST Can handel too long Data
Post is more secured Cuz it's not gonna be cached or saved in history or bookmarked
u can clearly notice that POST's dont display in the browsers address bar but Get do
'www.anything.com/index.php?bla=bhe'
i hope that i am helping here !! :)
Just a suggestion here since you have already got the answer. Try to use some javascript library to aid you while you are writing your JS code.
I would suggest jquery
And also please read what is the difference in GET, POST requests and when it should be used.

Categories