.htaccess File Extension Remover Code Breaks Website Form - javascript

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]

Related

XHTTP request in chrome extension executes twice

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);
}
}
);

Ajax call to Php script to fetch image in base64 string working on localhost but not from hosting server

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).

Using PHP to parse URL and provide it as variable to HTML

Since I couldn't find the answer to this question anywhere, so here comes the question. But before that, Thanks to anyone who answers/helps in anyway.
The pseudo-code of the index.php page is:
<html>
<head><script>
<?php
$links = parse_ini_file('links.ini');
if(isset($_GET['l']) && array_key_exists($_GET['l'], $links)){
$my_phpvar = $links[$_GET['l']];
}
else{
header('HTTP/1.0 404 Not Found');
echo 'Unknown link.';
}
?>
var myjsvar= <?php echo $my_phpvar; ?>
function go(){
document.cookie = "visited=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
window.location.href = "myjsvar";
}
</script></head>
<body><a id="myA1" href="javascript:go();" target="_blank">Click</a></body>
</html>
As is evident, in the above code the myjsvar comes from my_phpvar, and my_phpvar comes from a seperate file links.ini (sorry if I'm boring you, since it's all evident in the code, but I don't wanna miss anything out for anyone who can help)
I have added some rules to the .htaccess file in the root of this directory where index.php is located. The rules that have been added are
RewriteEngine On
RewriteCond $1 !^(index\.php)
RewriteRule ^(.*)$ index.php?l=$1 [L]
The links.ini file looks like this:
ex = https://www.example.com
So the Main Issue is: When I browse the URL http://www.yoursite.com/short/index.php?l=ex , and Click the Button to initiate the function go(), it doesn't take me to the website https://www.example.com
Once again, Thanks to anyone who solves/helps to solve the issue.
Enclose jsvar inside quotes:
var myjsvar = "<?php echo $my_phpvar; ?>";
and later, use it as a variable (and not sring):
window.location.href = myjsvar;

Auto-login into the IP Camera

I have a IP Camera and I would like to show liveview at my webpage.
IP Camera don't allow for anonymous log in so I need to put username and password while connecting.
I have javascript:
<img src="http://user:password#camera_ip_address/cgi-bin/jpg/image.cgi?" width="640" height="480" name="refresh">
<script language="JavaScript" type="text/javascript">
image = "http://camera_ip_address/cgi-bin/jpg/image.cgi?"
function Start() {
tmp = new Date();
tmp = "?"+tmp.getTime()
document.images["refresh"].src = image+tmp
setTimeout("Start()", 100)
}
Start();
</SCRIPT>
And it works ok in firefox but:
http://user:password#camera_ip_number
don't work in other browsers (it popup a form to enter username and password).
But in PHP you can use user:password I've check it by using:
<?php
header('Content-type: image/jpeg');
print( file_get_contents( 'http://user:password#camera_ip_address/cgi-bin/jpg/image.cgi?' ));
?>
of course it shows only one frame but you don't have to enter username and password.
How can I log in into IP Camera using PHP ? If I could log in one time while enetering webpage, my javascript will work ok because browser will remember username and password until I close the browser.
I don't know how to send username and password to log in.
Sorry for my English.
Ok, so I've made it work using PHP and JavaScript. Maybe it will be helpful for someone else:
Save the PHP file as, for example, snapshot.php:
<?php
$img="http://user:password#camera_ip/cgi-bin/jpg/image.cgi?";
header ('content-type: image/jpeg');
readfile($img);
?>
In the HTML file, add this script:
<img src="http://domain.com/snapshot.php" width="640" height="380" name="refresh">
<script language="JavaScript" type="text/javascript">
image = "http://domain.com/snapshot.php"
function Start() {
tmp = new Date();
tmp = "?"+tmp.getTime()
document.images["refresh"].src = image+tmp
setTimeout("Start()", 300)
}
Start();
</script>
It works ok under every browser. If I set timeout to less then 300, there is some lag. I don't know why that would be caused by; maybe internet connection or website speed.
You may be able to use Apache mod_rewrite instead - Less overhead from the PHP stack, and probably generally faster. See this page for more information.
Choose one of these.
Apache .htaccess - Your page requests http://yoursite/livecam/image.jpg, which is run through Apache's proxy to your camera.
RewriteEngine on
RewriteBase /livecam/
RewriteRule ^image.jpg$ http://user:password#camera_ip_address/cgi-bin/jpg/image.cgi [P]
ProxyPassReverse /livecam/image.jpg http://user:password#camera_ip_address/cgi-bin/jpg/image.cgi
In PHP, create a file called image.php - Your page requests http://yoursite/image.php, which streams the image to whatever requests it.
<?php
$file = 'http://user:password#camera_ip_address/cgi-bin/jpg/image.cgi';
if (file_exists($file)) {
header('Content-Type: image/jpeg');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
?>
Both will proxy the image through your server. It's generally bad practice to give the username and password on any public page, even if an attacker can't damage anything of concern.
See readfile() on PHP.net
Your code would look like (replace image.php with livecam/image.jpg if using the Apache version). I also shortened your code a bit.
<img src="http://yourserver/image.php" width="640" height="480" name="refresh">
<script language="JavaScript" type="text/javascript">setTimeout(function() {document.images["refresh"].src = "http://yourserver/image.php?"+math.random();}, 100);</SCRIPT>
IP:port/cgi-bin/jpg/image.cgi?&user=XXX&pwd=XXX
IP:port/cgi-bin/jpg/image.cgi?&usr=XXX&pwd=XXX
IP:port/snapshot.cgi?&user=XXX&pwd=XXX';
IP:port/cgi-bin/CGIProxy.fcgi?cmd=snapPicture2&usr=XXX&pwd=XXX';

determine the URL in the browser address bar (NOT the real address)

I have two urls - biothoughtblog.co and playfight.co. The first is forwarding to the second and masking is used. I am using this
<?php
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
?>
<?php
echo curPageURL();
?>
on the page http://www.biothoughtblog.co/test.php - however, it echoes the real URL which is http://www.playfight.co/test.php. I need it to echo the URL that is in the address bar. I know very very little Javascript - is it what I need to be using here?
Thanks a lot.
P.S Oh, and the purpose is to run the same website under two different domains and different branding (logo, etc).
That's because http://www.biothoughtblog.co/test.php is framing http://www.playfight.co/test.php.
<frame src="http://www.playfight.co/test.php" frameborder="0" />
PHP has no way of knowing that it is loaded inside a frameset, and how to get the URL of the parent frame.
You want to avoid using the "masking" feature of your registrar or DNS provider. Point the biothoughtblog.co domain to the same hosting server, ensure that your hosting account is setup for both domains. Then biothoughtblog.co wil be hitting your website directly, and PHP will know what it is.
You don't need to do anything in PHP to run the same website under two different domains.
If you are using apache, open your conf file, locate your virtual host config and add a serverAlias.
Example:
<VirtualHost *:80>
DocumentRoot "/var/www/html"
ServerName biothoughtblog.co
ServerAlias playfight.co
<Directory "/var/www/html">
AllowOverride All
</Directory>
</VirtualHost>

Categories