Say I have domain.com/php/ with all my php functions, then I share a ftp account with the front-end developers for domain.com/frontend/, now the frontend can do their work and call "../php/" functions. Is this safe to assume my php code are protected? Or another way of asking, is there anyway for them to see the php source code or somehow copy/include those files then display them?
You could restrict the user by jailing them to a folder:
http://allanfeid.com/content/creating-chroot-jail-ssh-access
This way they would have access to the folders to create the files. Then simply give them the path to which PHP files are needed. Or create an object or PHP function template to allow them to call access
Pseudo code:
class GlobalPaths
function getPathToThisResource(return string)
You can use the UNIX account system to make files unreadable to certain users. The problem is, if the PHP files can include each other, they can read each others sources. You can use an RPC system to hide the backend code. The frontend would only communicate with the RPC interface, and it wouldn't need to read the sources of the backend code.
For example, on the frontend:
<?php
error_reporting(-1);
function ask_backend($cmd, $args) {
$decoded = json_decode($data = file_get_contents("http://localhost:8800/backend/rpc.php?cmd=" . urlencode($cmd) . "&args=" . urlencode(json_encode($args))),true);
if ($decoded === null) throw new Exception("invalid data from backend: " . $data);
if ($decoded["status"] !== "ok") throw new Exception("error occurred on backend: " . $data);
return $decoded["msg"];
}
?>
The backend says:
<?php
$res = ask_backend("greeter", ["peter"]);
var_dump($res);
?>
on the backend, you could have rpc.php as follows:
<?php
error_reporting(-1);
$cmd = $_GET["cmd"];
$gargs = json_decode($_GET["args"],true);
$cmds = [
"greeter" => function($args) {
list($name) = $args;
return "hello " . $name;
}
];
$res = ($cmds[$cmd]($gargs));
$res = json_encode(["status"=>"ok", "msg"=>$res]);
echo $res;
?>
The disadvantage of this implementation is that you can only pass JSON serializable objects. Of course you can use Protocol Buffers for serialization instead. You don't even need to use HTTP, but I used that since you probably already have an HTTP server if you are running PHP.
Keep in mind that the RPC interface only needs to be available to localhost! And most importantly for your use case: the sources do not need to be readable by the developers of the frontend. Since it is not publicly accessibly, you could consider using something like PHPDaemon for the backend since that makes it easier build a proper REST interface.
Related
I state that I'm not familiar with Prestashop and I'm using version 1.7.6.
I'm trying to understand how I could use the import function from csv file without using of user interface.
I tried to look for documentation on a possible web api but I found nothing.
What I'd like to accomplish is the following scenario:
I have two web applications on the same server
/my_webapp
/my_prestashop
By "my_webapp" I receive a csv file, process it and produce a new csv file.
Now continuing running the process in "my_webapp", I would like to instantiate the ambient of the prestashop application to invoke the import csv function by passing it the new file just created.
Searching the web I found some sample code but, trying to use and adapt it, I am not making it work.
For example, on “my_webapp” folder I just create a “myimport.php” file and call it with two GET parameters.
The following is the call:
localhost/my_webapp/myimport.php?csv=prod.csv&limit=5
note: the file “prod.csv” is on
"path to admin folder"/import
Content of “myimport.php” file:
<?php
$rootPrestashop = '/var/www/html/my_prestashop”;
define('_PS_ADMIN_DIR_', $rootPrestashop.'/admin_shop'); //not sure if this instruction is needed
$pathConfig = $rootPrestashop.'/config/config.inc.php';
$initConfig = $rootPrestashop.'/init.php';
require_once($pathConfig);
require_once($initConfig); //this line throw an error and then I can't test the others!
$importCtrl = new AdminImportControllerCore();
$crossSteps = array();
$limit = $_GET["limit"];
$importCtrl->productImport(false, $limit, $crossSteps, true, 0);
This is what I’m trying to do, but I failed to initialize the environment.
Maybe I’m on the wrong way and there’s a better way.
I ask if anyone can help me understand if I can carry out this process and what would be the correct way.Thanks in advance
if (!defined('_PS_ADMIN_DIR_')) {
define('_PS_ADMIN_DIR_', __DIR__);
}
include _PS_ADMIN_DIR_.'/../config/config.inc.php';
if (!Context::getContext()->employee->isLoggedBack()) {
Tools::redirectAdmin(Context::getContext()->link->getAdminLink('AdminLogin'));
}
I once was a Web-Designer who knew HTML/CSS. Now I'm a 3D animator, but I want to get back into the Web-Developer world.
But there's so much new to learn. E.g. flat file cms. Wow!
But my question for now is how I read an API, create the right PHP file to pull an XML file and put that data onto a web page.
Specificially I'm interested in this mobile.de API:
http://services.mobile.de/manual/search-api.html
And it seems that this is the XML that I need:
http://services.mobile.de/schema/ad-1.0.xsd
What are the next steps to get this beginner's project going?
I guess I need some sort of PHP file that uses GET and some sort of authentication. How can I test, if and what will come back?
And how do I use the pulled information to put in into a new page?
Or is my thinking all wrong?
Many thanks in advance.
Ben
Little bit you can understand through this post and answers on this post:
How to echo xml file in php
If you don't mind using already created library, please check : PHP Curl Class
Taken from the readme:
PHP Curl Class is an object-oriented wrapper of the PHP cURL extension that makes it easy to send HTTP requests and integrate with web APIs.
And this code snippet (also taken from the readme) could be your starting point:
$curl = new Curl();
$curl->setBasicAuthentication('username', 'password');
$curl->setUserAgent('');
$curl->setReferrer('');
$curl->setHeader('X-Requested-With', 'XMLHttpRequest');
$curl->setCookie('key', 'value');
$curl->get('http://www.example.com/');
if ($curl->error) {
echo 'Error: ' . $curl->errorCode . ': ' . $curl->errorMessage;
}
else {
echo $curl->response;
}
var_dump($curl->requestHeaders);
var_dump($curl->responseHeaders);
Oh, and it's an unlicensed license type software.
My question may be incorrect or even strange, but I'm really interested in such programming experience, and there is two reasons for that:
As a PHP developer I should do my work so I can't just switch to other programming language that easy; however, there is a lot of things that causes a lot of pain to write in PHP.
As a Python beginner I'm already a huge fan of this language, and there are things that can be done a lot easier and, IMHO, in more righteous way that PHP implementation suggests.
For example, I've been writing a broadcasting multiple-connection socket server in PHP, and anybody who has done similar thing would understand how many restrictions will cause such solution - detecting disconnect if client just closed browser is dreadful. Looking at broadcasting server implementations in Python makes me feel more comfortable.
Also, a think about applications that could work, say, in offline mode to gather user input and sending it to the processing server later, or stand-alone applications that are connected to a website, etc.
Searching the web is poor in this case. All I've found is PiP, but it was released too long ago and not documented well - there is probably a good reason for that.
I would be glad to hear any thoughts about this, because I understand that this idea is kind of crazy and looks like not a lot of people is concerned about it.
Some time ago I ran into a similar dilemma. The solution I found was use xml-rpc to expose python objects and methods so I can use them from php scripts. Here I left you the documentation of both.
Python: Python xml-rpc.
PHP: XML-PHP
EDIT: Adding example. The examples are the same that in the documentation. I just changed them a bit to make them shorter. In client.php I only call the div function from python server. Add the others your self.
server.py
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)
# Create server
server = SimpleXMLRPCServer(("localhost", 8000),
requestHandler=RequestHandler)
server.register_introspection_functions()
# Register pow() function; this will use the value of
# pow.__name__ as the name, which is just 'pow'.
server.register_function(pow)
# Register a function under a different name
def adder_function(x,y):
return x + y
server.register_function(adder_function, 'add')
# Register an instance; all the methods of the instance are
# published as XML-RPC methods (in this case, just 'div').
class MyFuncs:
def div(self, x, y):
return x // y
server.register_instance(MyFuncs())
# Run the server's main loop
server.serve_forever()
client.php
<html>
<head><title>xmlrpc</title></head>
<body>
<h1>Php - Python - XMLRPC Demo</h1>
<?php
// Note that the path to xmlrpc.inc file is relative.
// to this file.
include("xmlrpc/lib/xmlrpc.inc");
// Params to python function 10 and 5.
// Build the message you want send.
// The message takes the function name and the params. See doc for details on how
// build params, is pretty easy.
$msg = new xmlrpcmsg( "div", array(new xmlrpcval(10, "int"), new xmlrpcval(5, "int")) );
// Build a XMLRCP - Client.
$client = new xmlrpc_client("/RPC2", "localhost", 8000);
// And send the message.
$response = $client->send($msg);
// From here all should look familier to you.
if(!$response->faultCode())
{
$v=$response->value();
echo "The result from div is" . htmlspecialchars($v->scalarval());
}
else
{
print "An error occurred: ";
print "Code: " . htmlspecialchars($r->faultCode())
. " Reason: '" . htmlspecialchars($r->faultString()) . "'</pre><br/>";
}
?>
<hr/>
</body>
</html>
I have a fairly basic website, written in pure php, no framework was used, running in a basic LAMP environment.
The site dynamically generates markup based on the HTTP User Agent header, and some query string parameters. For example "itemdetail.php" would inspect the querystring param "itemid" and the User Agent header and produce some markup.
I want to cache this markup, so that the next time a device with the same User Agent and itemid in the query string tries to request the page, it simply dumps out whatever markup is in its cache.
I realise I could do this manually in php using memcache, and just write some code at the top of the page to inspect the relevant params, and either try serve from memcached or render the page and store the markup in memcached, but I was thinking it might be possible to avoid the PHP layer altogether, using something like what is described here http://httpd.apache.org/docs/2.2/caching.html
So, my question, which I realise might be vague and this post will get killed is:
What is the recommended caching implementation here? Is it indeed to use memcache at the php level, or are the apache modules sufficient to meet my needs?
Generating different pages depending on User Agents is just bad practice. You shouldn't do that.
If you want to cache entire pages because your website is slow, the problem probably has to be searched in your code.
On-topic: Write a simple function that hashes the uri being served with a small footprint hash function (md5, sha1,...)
e.g.
<?php
$hash = md5('itemdetail.php-'.$itemid);
if ( file_exist('cache/'.$hash.'.html') {
echo file_get_contents('cache/'.$hash.'.html');
die();
}
and then at the end of your script save the result to 'cache/'.$hash.'.html';
You can offcourse use different kind of extension or folder or...
If you want to cache without using PHP, take a look at Varnish. Or the other example posted here.
If you are familiar with OpenCart at all here is something I wrote to do just this. hopefully you will get the idea given the possible unfamiliar
context.
ob_start();
$enableCaching = false; // Boolean flag
$route = !isset($_GET['route']) ? 'home' : str_replace("/",'-',$_GET['route']);
$cacheFile = DIR_CACHE . $route . '.' . md5($_SERVER['QUERY_STRING']) . ".cache.tpl";
if ($enableCaching !== false && in_array($_GET['route'], $cachePages) && file_exists($cacheFile) ||
$enableCaching !== false && file_exists($cacheFile) && !isset($_GET['route'])) {
/**
* This block of code will output the contents of the cache file.
*/
require ($cacheFile);
}
else {
/**
* Cache file doesn't exist, process the request
*/
$response->output();
if($enableCaching !== false && in_array($_GET['route'], $cachePages) ||
$enableCaching !== false && !isset($_GET['route'])){
file_put_contents($cacheFile, str_replace(array("\n","\r","\t"),'', str_replace(" "," ",ob_get_contents())));
}
}
Basically, create a variable generating a unique file name based on the file name and quest string.
Create that file, writing all HTML output to that file.
Then when it comes to processing request you can check if the unique cache file exists and just send that instead of processing the request.
use the memcached library...
you'll have to install it first and then memcached provides and in-memory caching system for php
I need ways to securize my own php administration panel. I read here about some:
A simple authentication using apache2.conf
Using ssl to send encrypted passwords
Host the tools on a completely seperate domain
A proper robots.txt should also be used
Using chmod 777 when i want to use and do a chmod 000 when i finish
But eachone has problems.
If i want to do it with apache2.conf, i must use ssl too. Only with this is it secured?
If i upload the tools in other domain and use robots.txt to "hide" them, could someone find them?
Using chmod is like "non-professional"
What do you use to secure your administration panel?
But eachone has problems. If i want to do it with apache2.conf, i
must use ssl too. Only with this is it secured?
Sort of. If you don't use ssl, passwords are sent over the net unencrypted if someone is listening in on your communication, they will know the password. That being said, it is usually impossible for someone to listen to your communication with the server unless one of the participating parties has already been compromised or you are communicating through an unsafe medium like unencrypted public wlan.
If i upload the tools in other domain and use robots.txt to "hide"
them, could someone find them?
Yes, if they guess the URL. robots.txt just hides you from search engines, but it does not work for protecting your admin panel from unwanted access.
Using chmod is like "non-professional"
And unsafe. It means that whenever you are working on the admin panel, everyone else also can. Don't do this.
What do you use?
Access control with Apache (either through the global config or an .htaccess file) with SSL. It may be a bit painful to set up at first, but for the given problem, it really is the only choice that makes any sense.
What you could do is use a php class that requires you to log in or sign up to your Website. You can find plenty from a quick Google.
Then, you should make an API on your Website that only sends data back if you're authenticated. Here's an example that would read data from a MySQL database:
<?php
require_once $_SERVER["DOCUMENT_ROOT"] . "/includes/accounts.class.php"; //Change this to the path to your authentication script
header("Content-Type: application/json"); //Important if you're using json
$account = new Accounts(); //A fictional Accounts class is opened
$json = array();
if (!$account->authenticated or $account->rights != "administrator") { //Ask the class if the user is not an admin
$json = array(
"error" => "Not an administrator"
);
} else {
$query = mysqli_query($link, "SELECT * FROM example"); //Assuming you use mysqli and there's a table called example
if (!$query or mysqli_num_rows($query) < 1) {
$json = array(
"error" => "Query returned no results"
);
} else {
while ($row = mysqli_fetch_array($query)) { //Read the data from the table
$json[] = $row;
}
}
}
echo json_encode($json); //Send the data as a json string
Remember that the above code is only an example of how you would do this sort of script. You'll need to modify it to work with the class and database you are using.
Now you can make your own program for your own internal use that logs in to and queries data from your API. This could be a Website running on an internal server, a Windows program or a smartphone app. All it would need to do is fill in the form on the log in Webpage, then send a HTTP request to the script above and decode the json result.