How to add javascript to my php MVC framework - php

I created a simple PHP MVC framework and I'm familiar with PHP. I think I understand the basics of JavaScript, but I have no idea how to use it with my MVC framework. Right now I have a folder in my root directory called scripts, a file inside of it called javascript.js and I put the appropriate source thing in my template. All I want to do right now is make a simple confirm box in the admin panel before accepting/deleting an application to join my site. Obviously there are two buttons (accept/delete) and I use onclick to call a function (AdminModel::acceptApplication). This is the AdminModel:acceptApplication function up to this point:
public function acceptApplication($id) {
$confirm=AdminModel::confirm();
if($confirm) {
$mysqli = BaseModel::dbConnect();
$sql = "SELECT * FROM applications WHERE id=" . $id;
$result = mysqli_query($mysqli, $sql);
$row = mysqli_fetch_array($result);
$sql = "INSERT INTO users (fname, lname, email, password) VALUES (" . $row['fname'] . ", " . $row['lname'] . ", " . $row['email'] . ", " . $row['password'] . ")";
mysqli_query($mysqli, $sql);
$sql = "DELETE FROM applications WHERE id=" . $id;
mysqli_query($mysqli, $sql);
header('Location: http://www.canforce.org/' . $_SESSION['language'] . '/admin/applications');
}
public function confirm() {
$confirm = echo '<script> areYouSure(); </script>';
return($confirm);
}
The JavaScript areYouSure() function returns true if you click yes:
function areYouSure() {
if(<?php echo $_SESSION['language'] ?> == "fr") {
confirm("Êtes-vous sûr");
}
else {
confirm("Are you Sure?");
}
}
I'm guessing there's allot wrong with what I've done here, simply bc of the whole server side/client side thing, but then I have no idea how to use javascript properly within my website. I want this to work, but if anybody has any tips or links to tutorial on how I can incorporate javascript into my php mvc framework, that would be appreciated as well. Thanks

PHP runs on a server. Javascript for the purpose of this conversation runs in the browser. You are trying to get the results of a browser level call on the server, another computer, it will not work. Your Model code exists on the server.
You need to have the js file included in your html file, in this case whatever passes for your view.
PS. The purpose of prepared statements is to prevent someone being able to run queries against your database, including deletes and getting all of your user info.

Related

Detect if user downloads with php and html

I build a internet site with php and html. I detect the access from the users with a code like this :
$qry ="SELECT * FROM visit WHERE ip='" .$ip ."' AND date(quando)=CURRENT_DATE";
$arr=$dbcls->query_arr($qry);
if(count($arr)==0)
{
$data=get_location2($row["ip"]);
if($data)
{
$country=$dbcls->escape_string($data->country);
$sub=$dbcls->escape_string($data->subdivision);
$city=$dbcls->escape_string($data->city);
$qry="INSERT INTO visit(ip,n,country,region,city)
VALUES('" . $ip ."',1,'". $country. "','" . $sub . "','". $city. "');";
//echo $qry;
}
else
$qry="INSERT INTO visit(ip,n) VALUES('" . $ip ."',1);";
}
else
$qry="UPDATE visit SET n=n+1 WHERE ip='" . $ip ."' AND date(quando)=CURRENT_DATE ;";
$dbcls->query_command($qry);
that allow me to save all the users that login in my site. The next step is to save how many users downloads my program.
The question is: how can I detect when a user make a download with php? If I have to create code with Javascript How can access to my database with javascript?
Your URL downloads/Treebase.zip is not served by PHP, is a static file.
The download is managed by the web server not by PHP.
To manage by PHP you'll need to make a route and make the PHP send the file.
Something like downloads/download.php?file_name=Treebase.zip.

What's going on with my code?

I am using similar syntax in my blog. However, On my forum, nothing happens! This has been such an infuriating thing to tackle, as everything seems to be working exactly as my blog did. Here's my code I pass through and call the delete_post page
CHUNK FROM VIEWPOST.PHP
while($row = mysqli_fetch_array($result)){
echo '<tr>';
echo '<td class="postleft">';
echo date('F j, Y, g:i a', strtotime($row['forumpost_Date'])) . "<br>" .$row['user_Name']. "<br>" .$row['forumpost_ID'];
echo '</td>';
echo '<td class="postright">';
echo $row['forumpost_Text'];
echo '</td>';
if(isset ($_SESSION['loggedin']) && ($_SESSION['user_AuthLvl']) == 1){
echo '<td class="postright">';
echo '<a class= "btn btm-default" href="#">Edit</a>';
echo '<a class= "btn btm-default" href="delete_post.php?forumpost_ID='.$row['forumpost_ID'].'">Delete</a>';
echo '</td>';}
else if(isset ($_SESSION['loggedin']) && ($_SESSION['user_ID']) == $row['forumpost_Author']){
echo '<td class="postright">';
echo '<a class= "btn btm-default" href="#">Edit</a>';
echo '<a class= "btn btm-default" href="delete_post.php?forumpost_ID='.$row['forumpost_ID'].'">Delete</a>';
echo '</td>';}
echo '</tr>';
}echo '</table>';
DELETE POST FUNCTION
<?php
include ('header.php');
include ('dbconnect.php');
//A simple if statement page which takes the person back to the homepage
//via the header statement after a post is deleted. Kill the connection after.
if(!isset($_GET['forumpost_ID'])){
header('Location: index.php');
die();
}else{
delete('hw7_forumpost', $_GET['forumpost_ID']);
header('Location: index.php');
die();
}
/********************************************
delete function
**********************************************/
function delete($table, $forumpost_ID){
$table = mysqli_real_escape_string($connectDB, $table);
$forumpost_ID = (int)$forumpost_ID;
$sql_query = "DELETE FROM ".$table." WHERE id = ".$forumpost_ID;
$result = mysqli_query($connectDB, $sql_query);
}
?>
Now it is showing the ID's as intended, it just simply does not delete the post. It's such a simple Query, I don't know where my syntax is not matching up!
EDIT FOR DBCONNECT.PHP
<?php
/*---------------------------------------
DATABASE CONNECT PAGE
A simple connection to my database to utilize
for all of my pages!
----------------------------------------*/
$host = 'localhost';
$user = 'ad60';
$password = '4166346';
$dbname = 'ad60';
$connectDB = mysqli_connect($host, $user, $password, $dbname);
if (!$connectDB){
die('ERROR: CAN NOT CONNECT TO THE DATABASE!!!: '. mysqli_error($connectDB));
}
mysqli_select_db($connectDB,"ad60") or die("Unable to select database: ".mysqli_error($connectDB));
?>
Ok, I saw this and I would like to suggest the following:
In general
When you reuse code and copy paste it like you have done there is always the danger that you forget to edit parts that should be changed to make the code work within the new context. You should actually not use code like this.
Also you have hard coded configuration in your code. You should move up all the configuration to one central place. Never have hard coded values inside your functional code.
Learn more about this in general by reading up about code smell, programming patterns and mvc.
To find the problem
Now to fix your problem lets analyse your code starting with delete_post.php
First check if we actually end up inside delete_post.php. Just place an echo "hello world bladiebla" in top of the file and then exit. This looks stupid but since I can't see in your code if the paths match up check this please.
Now we have to make sure the required references are included properly. You start with the include functionality of php. This works of course, but when inside dbconnect.php something goes wrong while parsing your script it will continue to run. Using require would fix this. And to prevent files from loading twice you can use require_once. Check if you actually have included the dbconnect.php. You can do this by checking if the variables inside dbconnect.php exist.
Now we know we have access to the database confirm that delete_post.php received the forumpost_ID parameter. Just do print_r($_GET) and exit. Check if the field is set and if the value is set. Also check if the value is actually the correct value.
When above is all good we can go on. In your code you check if the forumpost_ID is set, but you do not check if the forumpost_ID has an actual value. In the above step we've validated this but still. Validate if your if
statement actually functions by echoing yes and no. Then test your url with different inputs.
Now we know if the code actually gets executed with all the resources that are required. You have a dedicated file that is meant to delete something. There is no need to use a function because this creates a new context and makes it necessary to make a call and check if the function context has access to all the variables you use in the upper context. In your case I would drop the function and just put the code directly within the else statement.
Then check the following:
Did you connect to the right database
Is the query correct (echo it)
Checkout the result of mysqli_query
Note! It was a while ago since I programmed with php so I assume noting from the codes behavior. This is always handy. You could check the php versions on your server for this could also be the problem. In the long run try to learn and use MVC. You can also use frameworks like codeigniter which already implemented the MVC design pattern.
You have to declare $connectDB as global in function.
function delete($table, $forumpost_ID){
global $connectDB;
$table = mysqli_real_escape_string($connectDB, $table);
$forumpost_ID = (int)$forumpost_ID;
$sql_query = "DELETE FROM ".$table." WHERE id = ".$forumpost_ID;
$result = mysqli_query($connectDB, $sql_query);
}
See the reference about variable scope here:
http://php.net/manual/en/language.variables.scope.php
please try to use below solution.
<?php
include ('header.php');
include ('dbconnect.php');
//A simple if statement page which takes the person back to the homepage
//via the header statement after a post is deleted. Kill the connection after.
if(!isset($_GET['forumpost_ID'])){
header('Location: index.php');
die();
}else{
delete('hw7_forumpost', $_GET['forumpost_ID'], $connectDB);
header('Location: index.php');
die();
}
/********************************************
delete function
**********************************************/
function delete($table, $forumpost_ID, $connectDB){
$table = mysqli_real_escape_string($connectDB, $table);
$forumpost_ID = (int)$forumpost_ID;
$sql_query = "DELETE FROM ".$table." WHERE id = ".$forumpost_ID;
$result = mysqli_query($connectDB, $sql_query);
}
?>
I wish this solution work for you best of luck!

Can web robots inflate download counts?

I have a PHP program connected to an MYSQL database on a website.
Upon clicking a link to download a file, the program reads an integer field from the database, increments it, then puts the number back, to count the number of downloads. That program works. The download counts, however, over time, seem to be moderately inflated.
Could the download counts be incremented by web robots following the links to download the files? If so, would telling the web robots to ignore the download page on the website, using the robots.txt file, solve the inflated count problem?
Here is the PHP code:
function updateDownloadCounter($downloadPath, $tableName, $fileNameField, $downloadCountField, $idField)
{
require("v_config.php");
if(isset($_REQUEST["file_id"]) && is_numeric($_REQUEST["file_id"])) {
try
{
$sql = "SELECT * FROM " . $tableName . " WHERE file_id = " . $_REQUEST[$idField];
$connection = new PDO($dsn, $username, $password, $options);
$statement = $connection->prepare($sql);
$statement->execute();
$result = $statement->fetchAll();
if ($result && $statement->rowCount() == 1)
{
foreach ($result as $row)
{
if(is_file($_SERVER['DOCUMENT_ROOT'].$downloadPath . $row[$fileNameField]))
{
$count = $row[$downloadCountField] + 1;
$sql = "UPDATE " . $tableName . " SET " . $downloadCountField . " = " . $count . " WHERE file_id = " . $_REQUEST[$idField];
$statement = $connection->prepare($sql);
$statement->execute();
$documentLocationAndName = $downloadPath . $row[$fileNameField];
header('Location:' . $documentLocationAndName);
}
}
}
}
catch(PDOException $error)
{
echo $sql . "<br>" . $error->getMessage();
}
}
}
The answer to both of your questions is yes.
When a crawler indexes your website, it also looks for related content, akin to creating a sitemap. The first place it looks for related content on a page are the direct links. If you're linking to your files directly on your download page, the crawler will also attempt to index those links.
Preventing the crawlers from seeing your download page with robots.txt would prevent this problem, but then you'd be losing potential SEO. And what if a third party links to your downloads directly? If they have their downloads page indexed, your links will still be visible to crawlers.
Fortunately, you can disable this behaviour. Simply tell the crawlers that the links on the download page are all canonical ones, by adding the following to the <head> section of the downloads page:
<link rel="canonical" href="http://www.example.com/downloads" />
Considering the parameters are essentially different 'pages', crawlers will think that /downloads?file_id=1 is different to /downloads. Adding the above line will inform them that it is the same page, and that they don't need to bother.
Assuming that you have actual files that are being indexed (such as PDFs), you can prevent crawlers from indexing them in your .htaccess or httpd.conf:
<Files ~ "\.pdf$">
Header set X-Robots-Tag "noindex, nofollow"
</Files>
As a fallback, you could always check who is attempting to download the file in the PHP itself! It depends how pedantic you want to be (as there are a lot of different crawlers), but this function works pretty well:
function bot_detected() {
return (
isset($_SERVER['HTTP_USER_AGENT'])
&& preg_match('/bot|crawl|slurp|spider|mediapartners/i', $_SERVER['HTTP_USER_AGENT'])
);
}
Then simply call it as a conditional before running your try:
if (!bot_detected()) {
try { } // Will only get executed for real visitors
}
Also, as an aside, I'd recommend using $_GET["file_id"] over $_REQUEST["file_id"]. $_REQUEST combines $_GET with both $_POST and $_COOKIE, which tend to be used in rather different ways. While this is technically secure if you're only retrieving data, it's far safer to limit the request to a simple $_GET.
Hope this helps! :)

page not refreshing after clicking delete button

good day
need some help here, my Delete button works but page is not automatically refreshing after i clicked the delete button. i still need to manually retrieve the data from db and it would reflect that data is deleted already...
here is my code for delete php: how can i make this to refresh the page automatically?
<?php
require 'include/DB_Open.php';
$id = $_POST['id'];
$idtodelete = "'" . implode("','",$id) . "'";
$query = "DELETE FROM tbl WHERE ticket in (" . $idtodelete . ")";
$myData = mysql_query($query);
echo "DATA DELETED";
if($myData)
{
header("Location: delete.php");
}
include 'include/DB_Close.php';
?>
I suggest fetching the data after your delete logic. Then the delete logic will be executed before fetching the tickets.
Then a redirect to the same page isn't even necessary.
//
// DELETE
//
if (isset($_POST['delete'] && isset($_POST['id'])) {
// Do delete stuff,
// notice delete variable which would be the name of the delete form button e.g.
// If you like, you can still echo "Data deleted here" in e.g. a notification window
}
//
// FETCH data
//
$query = "Select * FROM tbl";
...
if you use post method better with this
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$id = $_POST['id'];
$idtodelete = "'" . implode("','",$id) . "'";
$query = "DELETE FROM tbl WHERE ticket in (" . $idtodelete . ")";
if (mysql_query($query))
{
header("Location: delete.php");
} else {
echo "Can not delete";
}
}
As suggested on one of the comments, and on the php documentation:
http://it2.php.net/manual/en/function.header.php :
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
Basically you have to take out the :
echo "DATA DELETED";
What's the point to try to echo that string if the page is going to be redirected anyway?
If you want to make it fancy you could use Ajax to delete it, and trigger a setTimeout() on JavaScript x seconds after showing the message.
Or if you really really really really, REALLY, want to do it this way, you could disable the errors report/display (using error_reporting(0) and ini_set('display_errors', 'Off'). By experience I know that it will work, but it's nasty and extremately ultra highly not recommended

CMS homepage in php

I am working on something it has 2 pages. One is index.php and another one is admin.php.I am making CMS page where you can edit information on the page yourself. Then it will go to the database, where the information is stored. I also have to have it where the user can update the information on the page. I am getting a little bit confused here.For instance here I am calling the database and I am starting a function called get_content:
<?php
function dbConnect(){
$hostname="localhost";
$database="blank";
$mysql_login="blank";
$mysql_password="blank";
if(!($db=mysql_connect($hostname, $mysql_login, $mysql_password))){
echo"error on connect";
}
else{
if(!(mysql_select_db($database,$db))){
echo mysql_error();
echo "<br />error on database connection. Check your settings.";
}
else{
return $db;
}
}
function get_content(){
$sql = "Select PageID,PageHeading,SubHeading,PageTitle,MetaDescription,MetaKeywords From tblContent ";
$query = mysql_query($sql) or die(mysql_error());
while ($row =mysql_fetch_assoc($query,MYSQL_ASSOC)){
$title =$row['PageID'[;
$PageHeading =$row['PageHeading'];
$SubHeading = $row['SubHeading'];
$PageTitle = $row['PageTitle'];
$MetaDescription =$row['MetaDescription'];
$MetaKeywords = $row['MetaKeywords'];
?>
And then on the index page and I am going to echo it out in the spot that someone can change:
<h2><?php echo mysql_result($row,0,"SubHeading");?>A Valid XHTML and CSS Web Design by WG.</h2>
I do know that the function is not finished I am still working on that part. What I am wondering is am I echoing it out right or I am way off. This is my first time messing with CMS in php and I am still learning it. I am working with navicat and text pad on this, yes I know it is old school but that is what I am being shown with. But my index is a form not a blog. I have seen many of CMS pages for blogs not to many to be used with forms. Any input will be considered thanks for reading my question.
Your question is a bit confusing and your code very incomplete. I'ts hard to say if you do it the right way since I don't see the rest of the script. You need to connect to the database there as well and get your data. The $row variable only exists in the while statement inside you function get_content() though.
You could complete the get_content() and use it in the index.php as well. Remember that the variables you define inside a function only is available there though. If you need the data outside that function you need to return the values you need and save them to some other variable there. Put if you do the same as you've started doing in the get_content() function in index.php, then you just have to echo the variables you define. Like this:
<h2><?php echo $SubHeading; ?></h2>
or you could also do it like this somewhere inside the php tags:
echo '<h2>{$SubHeading}</h2>';
I hope that answers your question.
EDIT:
What you need in the index.php page is exactly what you seem to be doing in the admin file. You need to connect to db using mysql_connect() and select db with mysql_select_db(). You then need to select the data from the db using the appropriate query with $query = mysql_query($sql). If it's more then one row you want to display you need to put it in a while loop otherwise (which seems to be the case here) you just need to do one $row = mysql_fetch_assoc($query). After that you can get the data using $row['column_name']. If you have more than one row you can just use $row['column_name'] in side the while loop to get each consecutive row's data.
Here is an example index.php:
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password') or
die('Could not connect: ' . mysql_error());
mysql_select_db('database_name')) or die('Could not select database: ' .
mysql_error());
$sql = "SELECT SubHeading FROM tblContent WHERE PageID='1' LIMIT 1;";
$query = mysql_query($sql);
$row = mysql_fetch_assoc($query);
echo '<h2>{$row[\'SubHeading\']}</h2>';
mysql_close();
?>
This is just what you need to display the SubHeading from you database. You probably also need to handle your form and save the submitted data to the database in your admin.php file.

Categories