How can i call php Require from SQL string - php

i am seeking help with the following
So im using PHP 7.1 and MSSQL 2017, and IIS
i have some tables that are to large to hard-code or create a text out of them to input in a SQL table , so i created a separate file with a query to display the table.
but when i try to add to "<?php require'table1.php';?>"
as a Text or string in another Table, and is set in the browser it gets comment out by the browser
Is there any way to execute the require with out being comment it out?
for now i have just create a link for the tables to open in a new tab, but i really what then to open inside the original document.
So file 1 is the main query where it displays the information.
File 2 runs another query for the Table, i would like to set the <?php require'table1.php';?> on the main query so it displayed File 2 contents in File 1, rather than opening a new tab.
Main table would be like this
Title - ID - Message
Something - RK1 - Something Important
Something 2 - RK2 - <?php require'table1.php';?>
Something 3 - RK3 - Something Kinda Importan
i apologize if its confusing, let me know.
Any help is appreciated, tyvm.

It's never a good idea to store code in the database because if you're database gets compromised whoever managed to get access to your DB will also have access to running php code on your server and can cause even more damage.
I think what you're trying to achieve could be done within your php files alone.
Why don't you just require table1.php file in your main file?
Edit:
In your main php file you can can create a part that your ajax script can communicate with that allows you to retrieve the necessary table contents like so:
<?php
if(isset($_POST['tableChange'])) {
$tableToDisplay = $_POST['tableChange'];
switch($tableToDisplay) {
case 'A':
$realTableName = 'TableA';
$isValidTable = true;
break;
case 'B':
$realTableName = 'TableB';
$isValidTable = true;
break;
default:
$isValidTable = false;
break;
}
if($isValidTable) {
$tableContents = mysql_fetch_array(mysql_query("SELECT * FROM `".$realTableName."`"));
//Then you can retrieve what ever rows you want from the current table with the array you create with mysql_fetch_array
$row1 = $tableContents['name_of_row1'];
$row2 = $tableContents['name_of_row2'];
echo 'row1: '.$row1.' row2: '.$row2;
}
}
?>
Then you can make an ajax POST request to the main php file -- that passes a piece of data named "tableChange" that holds a string representing the table's identifier. In this case it would have to be set to either "A" or "B" in order for it to be accepted.
Here's an example with jQuery:
$.ajax({
url: 'main.php',
type: 'POST',
data: {tableChange: 'B'},
dataType: 'html',
complete: function(dataReturned) {
//Now print the contents of the dataReturned variable to the screen how ever you want
}
});

Related

Can't manage to make $_POST to work

I have three files in a server (000webhost.com):
"Test01.php" (main file),
"database.txt" (saved data, which will be changed by users),
"save_txt.php" (the file which gets data from the main file and writes it to the "database".
"Test01.php" is supposed to show a simple list, with a few names in a table (single column, multiple lines).
Those names will be retrieved from a file named "database.txt".
Everytime some user click on a name, that name will be sent to the bottom of the list, and the list will be saved to "database.txt", so the next user will see the changes made by the last one.
A function in "Test01.php" sends the changed list to a second file ("save_txt.php"), which is supposed to write it back to "database.txt".
I can manage to retrieve the data from the txt file, and the clicking events as well, but I still can't find a way to save the data into the txt file...
In fact, I don't understand why my variable isn't seen from inside the second php file ("save_txt.php").
To retrieve data I use:
<?php
$Data_from_File = file("database.txt",FILE_IGNORE_NEW_LINES);
?>
And the script:
var sSaved_Data = <?php echo json_encode($Data_from_File); ?>;
The listing stuff works fine.
I get many names from the txt file and store it into an array. Then I display it in the table. No problem from reading the file.
I send data to "save_txt.php" by doing this:
var sNew_Data = " is blue";
.
.
.
xmlhttp.send("php_Data_to_Save=" + sNew_Data);
But, could anyone tell me why the simple code below doesn't work?
https://rbonphp.000webhostapp.com/Test01.php
"save_txt.php" is just like this:
<?php
$var1 = $_POST["php_Data_to_Save"];
echo $var1;
?>
In time: in this example I just want to see " is blue" echoed in the screen (no matter where). I just want to understand how to get the data back to "save_txt.php".
Later I will try to write $var1 to "database.txt".
But first things first...
:-(
As I said, this "Test01.php" is just a test. The list and all the clicking events I wrote in another file. That part works just fine.
* Edited *
Let's try to put it all in a few lines.
The main file (Test01.php) does:
var sNew_Data = " is blue";
// there's more code for the XMLHttpRequest function
xmlhttp.send("php_Data_to_Save=" + sNew_Data);
The secondary file (save_txt.php) does:
<?php
$var1 = $_POST["php_Data_to_Save"];
echo $var1;
?> // and this is ALL its code, just these 4 lines.
That line echo $var1; should simply show " is blue" on the screen.
Right???
Extra info: Test01.php is a step prior to make the following page to work:
https://rbonphp.000webhostapp.com/DailyTasks1.php
Your code is working.
Calling Send_Data_to_Server() returns "The sky is blue" which is what you wanted, as the sent data is var sNew_Data = sSaved_Data + " is blue"; and it is correctly echoed by save_txt.php
Note: your commented jquery ajax call is wrong however, that's not how you define the sent data, check the first example at http://api.jquery.com/jquery.ajax/
You'd write this:
$.ajax({
url: 'save_txt.php',
data: { php_Data_to_Save : sNew_Data },
type: 'POST'
});
first, you didnt call Send_Data_to_Server() anywhere, you've just declared it.
secont, you just send the request to server, but don't store the answer anywhere.

Is it possible to manipulate the post data in an jquery Ajax post?

I was wondering if code I have written is open to attack.
$.ajax({
url: site_url+"/customer/update",
type: 'POST',
dataType: "json",
async: true,
data: {
'id':$('#id').val(),
'cuFirstname':$('#firstname').val(),
'cuLastname':$('#lastname').val(),
'cuPersonalnr':$('#personalnr').val(),
},
});
On the server it looks like this:
$this->db->where('cuID = '.$customerid);
$this->db->update('customers',$_POST);
So I'm thinking that maybe if someone could change the variables (cuFirstname, cuLastname, cuPersonalnr) in the data part of the ajax post, that they would be able to write sql-code there.
"update customers set cuFirstname = 'charlie', cuLastname = 'brown', cuPersonalnr = '7012230303' where cuID = 1000"
So if they changed cuLastname to something else it could look like this:
update customers set cuFirstname = 'charlie', [cuShouldnotbechanged] = 'brown', cuPersonalnr = '7012230303' where cuID = 1000
So my question is: Is it possible for an attacker to change those variable names, and if so, how?
The client can change any aspect of the AJAX call, simply by making their own HTTP request to your URL with their own parameters. So, yes, they could conceivably change any part of the request.
In your code, the question really boils down to "how does my database library handle the update?". You're doing the following:
$this->db->where('cuID = '.$customerid);
$this->db->update('customers',$_POST);
which is, presumably, building a query like:
UPDATE customers SET column1='some value', column2='some other value', ... WHERE cuID='whatever';
based on the keys and values of the $_POST array. To address your specific question about what happens if a client changes the keys n the $_POST array, it seems to me there are two possibilities:
if they enter a column name that does not exist, the database library is either going to ignore it (and update the stuff it is able to) or throw an error (because an UPDATE statement with a non-existent column name is an SQL error).
if they enter a column name that exists but that you did not intend to update, then that new column name will probably be used and updated (unless your database library has protection in place for that - some require you to explicitly state which columns can be updated in this way).
Can a user write SQL code into those variabiles? The answer is yes.
Is it open to attack? That entirely depends on your method of sanitization/SQL input.
You can use prepared statements such as PDO (properly) to prevent the possibility.
Otherwise sanitize/check the sent data:
It looks as the cuPersonalnr, should be numeric? check to make sure:
if (!is_numeric ($_POST['cuPersonalnr']))
exit(); //script stops, not a number
first name and last name, im assuming need to be alphanumeric only?
well create a check, or sanitize any other values that are not alphanumeric:
if(!ctype_alnum($_POST['cuFirstname'])) {
exit(); //script stops, contains unsafe characters
}
instead of exit() you can create an error variable, and return the error.

Look for in Mysql table and pass information from the javascript

My web-server has PHP and MySQL.
One table of database has information about user.
User that uses my site wants to receive some information.
So he or she presses mouse button and happen click event for this button and submit event for a form.
I use framework jQuery and in my javascript (method .submit())
I use AJAX for retrieving necessary information.
First, I want to know exist so user in the table or not.
I receive this information using ajax and php file – first.php.
If information about user hasn’t in the table I report about this in the script.
If information about user hasn’t in the table but like user(s) exist(s) in it I inform of this situation.
If information about user has in the table I call command: window.location.href = “second.php?param=2&user=userid” in my script and I have to look for necessary information again in the table and show it in the web-page.
So my next question is: How can I refrain from repeating a query on the same table?
I must show about 10 account’s records in my web page.
I want to know. How can I pass information (10 account’s records) from my script into second.php file?
I am afraid to do the second command $.ajax() in the script. I think there is no need for it.
What you are doing now is pretty much the standard. If you dont want to use this method then I suggest that you look into session.
On your first page you will need to include the line:
<?php
session_start();
then your normal code.
Once you have read the information from the database then place the values into session variables;
$_SESSSION['var1'] = $result['id']; //--- continue for all the values you want to save
On the second page you will need to do the reverse
<?php
session_start();
$id = $_SESSION['var1'];
You could write the query result into a semi-static1 JavaScript snippet:
<?php
// do your query
$result = ...;
echo '<script type="text/javascript">'
. 'var accountData = ' . parseForJavaScript($result) . ';'
. '</script>';
// do your other stuff
Then you can write code that depends on that (not necessarily global) variable accountData:
// JavaScript:
doStuff(accountData);
because it will essentially be expanded to (if parseForJavaScript returns a json representation):
<script type="text/javascript">
var accountData = {users: {
0 : { "name" : "John" },
1 : { "name" : "Jack" },
2 : { "name" : "James" }
}};
</script>
Of course the JSON object would look differently depending on your actual data structure.
Or you can skip that variable and inject the data directly as a function parameter:
<?php
// do your query
$result = ...;
echo '<script type="text/javascript">'
. 'doStuff(' . parseForJavaScript($result) . ');'
. '</script>';
// do your other stuff
1 semi-static because it is actually dynamically generated by php but looks static when looking at the final HTML.

Counter in ActionScript 3.0 with...PHP or?

I am doing this flash banners for multiple clients and one major request is to have some sort of counter so they know how many times the banner has been clicked.
I know how to do it in ActionScript 3.0, I make a simple var:int and i increase it +1 when a click is made on the banner. What do I do with the value of this var(say its 121) where do I store it online so its safe and can be changed by multiple flash banners(as3).
But how do I save this information so next time when the banner is loaded(on diffrent webpages) the number of clicks is whatever it was last time it was loaded.
Should I look into PHP for that ? I have no clue how to do this... some examples, tutorials, whatever works... would be much appreciated.(I am a designer, not programmer...please dont speak php-ish, or you know... :D)
I've googled a bit, and found some help, but i am still confused, and much of it its not AS3, I'm thinking maybe stuff has evolved a bit since the stuff that I found(2008)...
Thank you very much.
You'd have to store (and fetch) the value somewhere - either in the DB, in a text-file, ...
I'd go search for a tutorial on PHP+MySQL. If you don't like PHP-ish, you're probably better of finding another solution though :p
Example tutorial: http://www.freewebmasterhelp.com/tutorials/phpmysql
You need to store the data you want be retrievable/update-able from multiple clients, to be stored on a server.
You can use any server side language with a database.
Server Languages : PHP, ASP.net, JSP, ColdFusion
Database : MySQL, MSSQL, PostgreSQL, Oracle, DB2 etc..
Use whatever combination you are comfortable with.
In general:
You have a web app that increments the counter in the database
call the page using URLLoader from your AS3 banner.
Database
counter_table
-------------
counter INT
PHP File
$db = mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_select_db('database_name');
mysql_query('UPDATE counter_table SET counter = counter + 1');
AS3 Banner
// url request with your php page address
var scriptRequest:URLRequest = new URLRequest("http://www.example.com/script.php");
// loader
var scriptLoader:URLLoader = new URLLoader();
// load page to trigger database update
scriptLoader.load(scriptRequest);
Do you also want to retrieve the value of the number of clicks in Banner ?
Easy solution (really not the best :) You should use one of the other answers.. anyways, make a php file that reads txt file containing the count of visits.. and in your flashbanner just call the php file. It'll add one hit per call..
PHP:
<?php
/**
* Create an empty text file called counterlog.txt and
* upload to the same directory as the page you want to
* count hits for.
*
*
* #Flavius Frantz: YOU DONT NEED THESE:
* Add this line of code on your page:
* <?php include "text_file_hit_counter.php"; ?>
*/
// Open the file for reading
$fp = fopen("counterlog.txt", "r");
// Get the existing count
$count = fread($fp, 1024);
// Close the file
fclose($fp);
// Add 1 to the existing count
$count = $count + 1;
// Display the number of hits
// If you don't want to display it, comment out this line
//echo "<p>Page views:" . $count . "</p>";
// Reopen the file and erase the contents
$fp = fopen("counterlog.txt", "w");
// Write the new count to the file
fwrite($fp, $count);
// Close the file
fclose($fp);
?>
Example code from: (google: php counter file) http://www.totallyphp.co.uk/text-file-hit-counter
Code is not tested, but looks ok. I only commented just a little..

PHP + Mysql queries for a real Beginner

After years of false starts, I'm finally diving head first into learning to code PHP. After about 10 failed previous attempts to learn, it's getting exciting and finally going fairly well.
The project I'm using to learn with is for work. I'm trying to import 100+ fixed width text files into a MySql database.
So far so good
I'm getting comfortable with sql, and I'm learning some php tricks, but I'm not sure how to tie all the pieces together. The basic structure for what I want to do goes something like the following:
Name the text file I want to import
Do a LOAD DATA INFILE to import the data into one field it to a temporary db
Use substring() to separate the fixed width file into real columns
Remove lines I don't want (file identifiers, subtotals, etc....)
Add the files in the temp db, to the main db
Drop the temp db and start again
As you can see in the attached code, thigns are working fine. It gets the new file, imports it to the temp table, removes unwanted lines and then moves the content to final main database. Perfect.
Questions three
My two questions are:
Am I doing this 'properly'? When I want to run a pile of queries one after anohter, do I keep assinging mysql_query to random variables?
How would I go about automating the script to loop through every file there and import them? Rather than have to change the file name and run the script every time.
And, last, what PHP function would I use to 'select' the file(s) I want to import? You know, like attaching a file to an email -> Browse for file, upload it, and then run the script on it?
Sorry for this being an ultra-beginner question, but I'm having trouble seeing how all the pieces fit together. Specifcally I'm wondering how multiple sql queries get strung together to form a script? The way I've done it below? Some other way?
Thanks x 100 for any insights!
Terry
<?php
// 1. Create db connection
$connection = mysql_connect("localhost","root","root") or die("DB connection failed:" . mysql_error());
// 2. Select the database
$db_select = mysql_select_db("pd",$connection) or die("Couldn't select the database:" . mysql_error());
?>
<?php
// 3. Perform db query
// Drop table import if it already exists
$q="DROP table IF EXISTS import";
//4. Make new import table with just one field
if ($newtable = mysql_query("CREATE TABLE import (main VARCHAR(700));", $connection)) {
echo "Table import made successfully" . "<br>";
} else{
echo "Table import was not made" . "<br>";
}
//5. LOAD DATA INFILE
$load_data = mysql_query("LOAD DATA INFILE '/users/terrysutton/Desktop/importmeMay2010.txt' INTO table import;", $connection) or die("Load data failed" . mysql_error());
//6. Cleanup unwanted lines
if ($cleanup = mysql_query("DELETE FROM import WHERE main LIKE '%GRAND%' OR main LIKE '%Subt%' OR main LIKE '%Subt%' OR main LIKE '%USER%' OR main LIKE '%DATE%' OR main LIKE '%FOR:%' OR main LIKE '%LOCATION%' OR main LIKE '%---%' OR `main` = '' OR `main` = '';")){
echo "Table import successfully cleaned up";
} else{
echo "Table import was not successfully cleaned up" . "<br>";
}
// 7. Next, make a table called "temp" to store the data before it gets imported to denominators
$temptable = mysql_query("CREATE TABLE temp
SELECT
SUBSTR(main,1,10) AS 'Unit',
SUBSTR(main,12,18) AS 'Description',
SUBSTR(main,31,5) AS 'BD Days',
SUBSTR(main,39,4) AS 'ADM',
SUBSTR(main,45,4) AS 'DIS',
SUBSTR(main,51,4) AS 'EXP',
SUBSTR(main,56,5) AS 'PD',
SUBSTR(main,100,5) AS 'YTDADM',
SUBSTR(main,106,5) AS 'YTDDIS',
SUBSTR(main,113,4) AS 'YTDEXP',
SUBSTR(main,118,5) AS 'YTDPD'
FROM import;");
// 8. Add a column for the date
$datecolumn = mysql_query("ALTER TABLE temp ADD Date VARCHAR(20) AFTER Unit;");
$date = mysql_query("UPDATE temp SET Date='APR 2010';");
// 8. Move data from the temp table to its final home in the main database
// Append data in temp table to denominator table
$append = mysql_query("INSERT INTO denominators SELECT * FROM temp;");
// 9. Drop import and temp tables to start from scratch.
$droptables = mysql_query("DROP TABLE import, temp;");
// 10. Next, rename the text file to be imported and do the whole thing over again.
?>
<?php
// 5. Close connection
mysql_close($connection);
?>
If you have access to the command like, you can do all your data loading right from the mysql command line. Further, you can automate the process by writing a shell script. Just because you can do something in PHP doesn't mean you should.
For instance, you can just install PHPMyAdmin, create your tables on the fly, then use mysqldump to dump your database definitions to a file. like so
mysqldump -u myusername -pmypassword mydatabase > mydatabase.backup.sql
later, you can then just reload the whole database
mysql -u myusername -pmypassword < mydatabase.backup.sql
It's cool that you are learning to do things in PHP, but focus on doing the stuff you will do in PHP regularly rather than doing RDBMS stuff in PHP which is not where you should do it most of the time anyway. Build forms, and process the data. Learn how to build objects, and why you might want to do that. Head over and check out Symphony and Doctrine. Learn about the Front Controller pattern.
Also, look into PDO. It is very "bad form" to use the direct mysql_query() functions anymore.
Finally, PHP is great for templating and including disparate parts to form a cohesive whole. Practice making a left and top navigation html file. Figure out how you can include that one file on all your pages so that your same navigation shows up everywhere.
Then figure out how to look at variables like the page name and highlight the navigation tab you are on. Those are the things PHP is well suited for.
Why don't you load the files and process them in PHP, and use it to insert values in the actual table?
Ie:
$data = file_get_contents('somefile');
// process data here, say you dump it into a 2d array like
// $insert[$rows][$cols]
// then you can insert these into the db, ie:
$query = '';
foreach ($insert as $row) {
$query .= "INSERT INTO table VALUES ({$row[1]}, {$row[2]}, {$row[3]});";
}
mysql_query($query);
The purpose behind setting mysql_query to a variable is so that you can get the data you were querying for. In the case of any other query than SELECT, it only returns true or false.
So in the case where you are using if ($var = mysql...) you do not need the variable assingment there at all as the function returns true or false.
Also, I feel like doing all your substring and data file processing would be MUCH better suited in PHP. you can look into the fopen function and the related functions on the left side of that page.

Categories