I am trying to execute a PHP script on my server from a Chrome extension. Here is the ajax call:
data_array_ = JSON.stringify(data_array_);
//console.log("Connections array" + data_array_);
var file_address = "https://my.server/add_on_php_files/update_database.php";
var xhttp_request = new XMLHttpRequest();
xhttp_request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = this.responseText;
console.log(response);
};
};
xhttp_request.open("POST", file_address, true);
xhttp_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhttp_request.send("data_array=" + data_array_);
This is the PHP code:
<?php
session_start();
include_once 'database.php';
$data_array = $_REQUEST["data_array"];
$data_array_entry = json_decode($data_array, true);
$statement_to_call = "INSERT INTO contacts (name, phone) VALUES ";
$length = count($data_array_entry);
$index = 0;
foreach($data_array_entry as $single_data) {
$statement_to_call .= "('".$single_data['name']."','".$single_data['phone']."')";
if(++$index != $length){
$statement_to_call .= ", ";
} else {
$statement_to_call .= ";";
}
};
$sql = mysqli_query($connect, $statement_to_call);
echo $statement_to_call;
?>
Unfortunately, when I execute this call without the developer tools open, the script ends up executing a second time, putting additional data into my database (I looked at the server logs and saw that the script executed twice). If I execute the call with the developer tools open, the call only executes once and the network panel and database both show the expected results. Obviously, I cannot expect a user to keep the developer tools open all the time, so this is a problem that I need to solve. Stepping through the Javascript step by step also fails to show me the problem because it also executes with no problems. If the problem occurs when I use it normally but does not occur when I attempt to debug, how can I find the reason why the PHP is executed additional times?
I looked at php run once and insert twice in mysql database and saw that people recommended editing the .htaccess to prevent the second call to the PHP file, but when I tried to implement the solution, all of the files on the website became 404'd.
.htaccess code:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?path=$1 [QSA,L,NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(.+\.)?my\.server/ [NC]
RewriteRule .*\.(js|css)$ - [NC,F,L]
.htaccess code with attempted .htaccess solution:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !favicon.ico
RewriteRule .* index.php [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?path=$1 [QSA,L,NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(.+\.)?my\.server/ [NC]
RewriteRule .*\.(js|css)$ - [NC,F,L]
The process is triggered by clicking this button:
<button class="screen_button" id="add_data">Add data</button>
A click event listener was added to the button on startup, thus the button triggers a process that passes a message to the content script and receives a message back that leads to:
function get_array_data (contact_array_) {
//create data to insert
var data_array_ = [];
data_array_.push({name: name_1, phone: phone_1});//data retrieved from the content script and passed in through the contact_array_ parameter
data_array_.push({name: name_2, phone: phone_2});
//so on so forth
ajax_call(data_array_);//refer to top of post for the ajax code
}
The data is created and sent to the request correctly, and the console.log statement in the ajax callback outputs what I expect it to, and just once. Therefore, I am led to believe that something is causing the PHP file to execute again, independent of the ajax call. The extra PHP file execution doesn't come back and give another console.log.
After additional investigating, I found that the problem seems to start occurring after a specific item in the chrome.storage gets set. I set the variable in chrome storage so I can use it to determine whether to have my content script respond to double-clicking.
The code that toggles the setting (setting is uninitialized until this is called the first time):
function toggle_setting () {
chrome.storage.sync.get(["setting"], function(result){
var setting = result.setting;
if (setting == "on"){
chrome.storage.sync.set({"setting": "off"});
}else{
chrome.storage.sync.set({"setting": "on"});
}
});
}
The content script code:
document.addEventListener("dblclick", function() {
chrome.storage.sync.get(['setting'], function(result){
if (result.setting == "on") {
chrome.runtime.sendMessage({info: "click", data: contact_data_});
}
}
}
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse){
if(request.message === "get_contacts"){
chrome.runtime.sendMessage({info: "contacts", data: contact_data_});
}
//other conditions, etc.
}
);
And the code that listens for the sent messages in the extension environment:
chrome.runtime.onMessage.addListener(
function(message, sender, sendResponse){
if(message.info == "click"){
get_array_data(message.data);
}else if(message.info == "contacts"){
get_array_data(message.data);
}
}
);
Related
I have on my host a pages that i want to prevent access to theme except through XMLHttpRequest, so i have already tried this code on htaccess file but it doesn't work:
in this code the target page is: "localhost/page/table.php"
RewriteEngine On
RewriteCond %{HTTP:X-Requested-With} !=XMLHttpRequest
RewriteCond %{HTTP:X-REQUESTED-WITH} !^(XMLHttpRequest)$
in the rewriteRule i don't know what to write.
i have already trying to search in Prevent access to php files (folder) with .htaccess EXCEPT for XMLHttpRequest but that doesn't help enough.
EDIT
i have tried this code, the page table.php are not accessable but there is no XMLHttpRequest response:
javascript code :
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("contentp").innerHTML =
xhttp.responseText;
}
}
xhttp.open("GET", "table.php?doc=" + str1 + "&module=" + str2 , true);
xhttp.send();
htaccess code:
RewriteEngine On
RewriteCond %{HTTP:X-Requested-With} !=XMLHttpRequest
RewriteCond %{HTTP:X-REQUESTED-WITH} !^(XMLHttpRequest)$
RewriteRule table-view+.php$ - [L,F]
Description: I have a HTML page which onloading triggers Ajax call. In this Ajax call I'm passing in the ids(which is the same as image name which are placed on server) .Each id sent via ajax function to the php script which then fetches the image convert it to base64 and returns it back to ajax call. On success this Javascript function writes base64 string to(href="base64") the corresponding id it came from.
Problem: Now all of this is working fine on localhost with directives in .htaccess file but just when I placed it on my hosting server the HTML page is making the ajax call to PHP script but the PHP script is not returning the base64 string as on localhost but is returning the markups of Index.html. In my .htaccess file on server I have condition that "# Redirect all requests to index.html" (but that's only to avoid any unwanted requests from user).
Checks performed: 1) case sensitivity of names.
2)Have placed the files in correct directory locations.
3)Compared the requests(using Developers tool,Network tab) that's made on localhost with the one on hosting server and both are same with 'Status 200' (their content 'base64string' and 'markups of index.html' respectively).
HTML
JavaScript
<script type="text/javascript">
$('.example-image-link').each(function() {
var id = $(this).attr("id");
var data = id;
$.ajax({
type: "POST",
url: 'http://mysite.in/home/myname/public_html/image_extract.php',
async: true,
data: {post: data},
success: function(data) {
var x = "data:image/jpeg;base64,";
var y = data;
z = x + y;
document.getElementById(id).href= z;
return false;
}
});
});
</script>
image_extract.php
$q = $_POST['post'];
$main = explode("_", $q);
if($main[0] == "travel")
{
$dir = "images/travel_pics/".$q.".jpg";
$image = file_get_contents($dir);
$imdata = base64_encode($image);
if ($imdata !== false) {
echo $imdata;
}
else {
echo 'An error occurred.';
}
}
.HTACCESS
# Allows ModRewrite to work
Options FollowSymLinks
# Turn on rewrite engine
RewriteEngine On
RewriteBase /
# Redirect all requests to index
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.html
IndexIgnore *
RewriteCond %{HTTP_REFERER} !^http://mysite.in/.*$ [NC]
RewriteCond %{HTTP_REFERER} !^http://mysite.in$ [NC]
RewriteCond %{HTTP_REFERER} !^http://www.mysite.in/.*$ [NC]
RewriteCond %{HTTP_REFERER} !^http://www.mysite.in$ [NC]
RewriteRule .*\.(jpg|jpeg|gif|png|bmp)$ - [F,NC]
Why am I not receiving base64 string from php script on hosting server(Godd*dy)? Thanks in advance. :)
.htaccess looks fine, JS also - it seems like the php file image_extract does not exist.
You are using path http://mysite.in/home/myname/public_html/image_extract.php
try http://mysite.in/image_extract.php instead because /home/myname/public_html is your document root (i suppose).
.htaccess
RewriteRule ^info/{0,1}$ index.php?page=info [QSA,L]
RewriteRule ^login/{0,1}$ index.php?page=login [QSA,L]
the same : index = index/
RewriteRule ^info/?$ $1
RewriteRule ^login/?$ $1
javascript:
reg_e=/#$/; if(!window.location.href.match(reg_e)) {
window.location.href = decodeURIComponent(window.location.href)+"#";}
it's working... good
I have problem that
when someone try to add '/' or any at the final url http://example.com/info/# will return http://example.com/info# or http://example.com/info/# but page will change nothing ?
Can you help me establish any rules for none breaking web addresses at ends of lines?
example : http://example.com/info# <- base url
http://example.com/info/# to be => http://example.com/info#
or : http://example.com/info/# <= or if anyone add '/#-' e.tc. the web will be nothing change.
And when I click 'info' and add '/' [http://example.com/info/#, it's ok. but i click other link it will be :
http://example.com/info/login# <- RewriteRule ^login/?$ $1
instead of: [http://example.com/login/#
if remove #RewriteRule ^login/?$ $1 ->> http://example.com/login# when add '/' handle => css wont load.
'info' and 'login are the same level in index folder.
i'd tried "<base href='/' /> but not working.
how to have a safe url? thanks your opions.
I am not 100% sure what you want here but it seems as though you want a link to redirect from base URL and not the relative URL.
Say your link is this:
Login
Try this instead
Login
The / at the beginning will say to go back to the base URL and start from there. Let me know if I missed the point completely though :)
So I had this code in my HTACCESS which was great because it first removes the .php file extension from my pages if the visitor enters the page with the .php file extension, and then it allows the page to load without the extension. (So it's just prettying up the URL)
# REMOVE FILE EXTENSIONS
RewriteEngine On
# browser requests PHP
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^\ ]+)\.php
RewriteRule ^/?(.*)\.php$ /$1 [L,R=301]
# check to see if the request is for a PHP file
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^/?(.*)$ /$1.php [L]
It works great, but then I run into problems on the page: http://www.CyberBytesInc.com/contact because I have a form which calls out to a .php file to send:
<form id="request-form" action="resources/script/question-send.php" method="post">
And the above htaccess code removes the .php for this file and I get the error code "Direct access to this page is not allowed." which is inside of the script, it's the
} else {
die('Direct access to this page is not allowed.');
}
Once I remove this from htaccess though then it starts working:
# browser requests PHP
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^\ ]+)\.php
RewriteRule ^/?(.*)\.php$ /$1 [L,R=301]
But then I don't get the perk of it removing the file extension if .php is placed at the end of the page (which much of Google is indexed with the file extension and I'm trying to remove this.
I guess if I could somehow make it so the htaccess code work except for when accessing a file from my /resources/scripts/ folder, I don't know the best way to fix this.
You can go to the site right now to see that it's not working because of this. For the time being I am probably going to remove the above mentioned line of code so my form is atleast working. So if you view the site and the form is working, it's because I removed the above .htaccess until I figure out how to successfully have it in there.
Thanks!
EDIT: Full code for question-send.php
<?php
// Get email address
$email_address = 'email#site.com';
// Ensures no one loads page and does simple spam check
if( isset($_POST['name']) && empty($_POST['spam-check']) ) {
// Declare our $errors variable we will be using later to store any errors
$error = '';
// Setup our basic variables
$input_name = strip_tags($_POST['name']); //required
$input_email = strip_tags($_POST['email']); //required
$input_subject = strip_tags($_POST['subject']);
$input_message = strip_tags($_POST['message']); //required
// We'll check and see if any of the required fields are empty
if( strlen($input_name) < 2 ) $error['name'] = '<label for="question-name">Please enter your <b>Name</b></label>';
if( strlen($input_message) < 5 ) $error['message'] = '<label for="question-message">Please leave a longer <b>Message</b></label>';
// Make sure the email is valid
if( !filter_var($input_email, FILTER_VALIDATE_EMAIL) ) $error['email'] = '<label for="question-email">Please enter a valid <b>Email Address</b></label>';
// Set a subject & check if custom subject exist
if( $input_subject ) $subject = "(Question) - $input_subject";
else $subject = "(Question) - No Subject";
// $message .= "$input_message\n";
$message .= "\n\n---\nThis email was sent by $input_name from $input_email";
// Now check to see if there are any errors
if( !$error ) {
// No errors, send mail using conditional to ensure it was sent
if( mail($email_address, $subject, $message, "From: $input_email") ) {
echo '<p class="success"><b>EMAIL SENT SUCCESSFULLY.</b><br />' . "Dear $input_name, " . 'thank you for contacting CyberBytes Inc. Please allow us <b>24-48</b> hours to review your request and get back to you. If you need a response sooner, please contact us via telephone at (716) 876-1824.<br /><br /><b>Please verify that this is your correct Email Address:</b><br />' . "Email Address: <i>$input_email</i>" . '<br /><br /><span class="red"><b>PLEASE NOTE:</b></span><br /> If we do not respond to your request within a reasonable amount of time, please give us a call as there may have been an error on our end with your request.</p>';
} else {
echo '<p class="error">There was a problem sending your email! Please give us a call at (716) 876-1824 as there seems to be an error on our end with the form.</p>';
}
} else {
// Errors were found, output all errors to the user
$response = (isset($error['name'])) ? $error['name'] . "\n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "\n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "\n" : null;
echo "<p class='error'>$response</p>";
}
} else {
die('Direct access to this page is not allowed.');
}
Change your rule to skip POST request:
# browser requests PHP
RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{THE_REQUEST} ^\s/([^\ ]+)\.php
RewriteRule ^/?(.*)\.php$ /$1 [L,R=301]
So I am trying to create a search in my website and I need to encode some text so it is URL friendly. However, if I search anything with a "<" symbol I get HTTP error 403 (access forbidden) because the "<" is not being encoded.
This is the code I am using:
var search = $("#txtHomeSearch").val();
if(search != ""){
var urlSearch = encodeURIComponent(search);
window.location.href = "/search&s=" + urlSearch;
}
Example of a working url: http://website.com/search&s=helloword
Example of a broken url : http://website.com/search&s=<
Maybe the problem is with my .htaccess file which contains:
RewriteEngine on
RewriteRule ^([^.*]+)$ index.php?page=$1 [L]
ErrorDocument 404 /errorPages/404.php
There is a simple utility here: http://www.the-art-of-web.com/javascript/escape for verifying the operation of the various Javascript escaping functions. Accoring to the ECMA standard, and verified using that tool, the "<" should be escaped correctly by the encodeURIComponent() function.
Could it be a character other than "<" causing the problem? There are various remedies for the characters that encodeURIComponent misses. One is the url_encode function listed here and elsewhere: javascript window.location do I need to escape?
Try escaping your back reference using [B] flag.
RewriteEngine on
RewriteRule ^([^.*]+)$ index.php?page=$1 [B,L]
ErrorDocument 404 /errorPages/404.php