Trying to find the best method - php

I will set up a register page using MSSQL.
The system must work like:
User appends data at something.com/register.php
The data is sent to host-ip-address/regsecond.php which my database will be at. (For security reasons, this php page wont directly access to the database.
The php page at host will start another PHP page or EXE file will directly reach database directly and securely.
As my php level is not high, I wanted to learn If i could start php scripts which will work and do their job without coming into users browsers. Here I explain what I say:
" I append some data at x.php, and it starts another PHP script which will do the job with the DATA appended from x.php but the -another PHP script- wont come into users browser "
I was hopefully clear ,as summary, should I use exe [will be harder] or can I start PHP script without coming into browser. And how of course.

You can do this using the curl extension. You can find info on it here:
http://php.net/manual/en/book.curl.php
You can do something like the following:
$postdata = array(
'item1' => 'data'
);
$ch = curl_init("http://host-ip-address/regsecond.php");
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
curl_exec($ch);
curl_close($ch);
This makes a call directly from your first script to your second script without exposing anything to the user. On the far side, the data will come in as regular post data ($_POST).

You can't post data through PHP to a different website.
If you would like your website then you can configure your PHP script to connect to a different server for your MySQL, I wouldn't say it's a huge amount safer. For example
Instead of:
mysql_connect(localhost,username,password);
Try this
mysql_connect(http://your-ip:portnumber,username,password);

I'm not sure I understand this correctly but you may
§1 use a "public" php script that invokes a private one:
<?php
//public register script
//now call private
//store data to txt-file or similar..
require('/path/outside/www-data/script_that_processes_further.php');
§2 request a script at another server,
<?php
file_get_contents('http://asdf.aspx?firstname=' . $theFirstName); //simplistic
//other options would be curl, xml/soap or whatever.
§1 may be used with §2.
regards,
/t

Related

Submit a form on remote site via cURL and PHP, and download the file in response, remote page is html and https

What I am trying is submit a form on remote site, the output of that form is a pdf file which I want to store to my site locally. I want to automate this via cron job, using PHP and cURL.
Problems:
Remote site is https (even worse it is not properly setup)
The site is html and not PHP but it gives result as if PHP
What I have tried so far
I used cURL in PHP but did not quite work. It simply submits a response which does not include the response from the form submission.
I tried to create remote form on my local host and when I submit form, it does return pdf file but this solution does not uses Curl and hence I cannot automate it.
Code that I have tried so far
<?php
// set post fields
$post = [
'bench_sno' => '1',
'causelist_date' => '2010-10-1',
'btnSearch' => 'Search Causelist',
];
$ch = curl_init('http://peshawarhighcourt.gov.pk/app/site/4/p/Causelists_List.html');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
// execute!
$response = curl_exec($ch);
// close the connection, release resources used
curl_close($ch);
// do anything you want with your response
//var_dump($response);
echo $response;
?>
When I just copy the remote form to my site and submit the form, it does work fine Working Example but the problem is it does not work with cURL. I need to automate this task via cron job, any other solution if available, I can consider.
As came under discussion in the question itself, and pointed out by #vivek_23 to include it in the fields, the form now works
<input type="hidden" name="url" value="http://peshawarhighcourt.gov.pk:443/app/site/4/p/Causelists_List.html">

How can i print php code by call url?I tried by file name but i want to print by url

I am trying to print php code on web page by using my URL. I know by file name i can print php code using "show_source('filename.php');" but i want to print code by URL, not by file.
I tried:-
<?php
show_source("http://URL.com/index.php");
?>
I also tried this code:-
<?php
$c = curl_init('http://URL.com');
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
//curl_setopt(... other options you want...)
$html = curl_exec($c);
if (curl_error($c))
die(curl_error($c));
// Get the status code
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);
curl_close($c);
I also tried this code:-
$html = file_get_contents('https://www.URl.com');
print_r ($html) ;
?>
Short answer: If the web server is configured correctly, it should be impossible to do what you are trying to do.
A correctly configured web server will only send content after PHP has processed it. If the web server is sending raw PHP when a .php file is requested, it is misconfigured. If you are trying to view your own PHP files from a server you control, you can try making a copy of the PHP files and changing the extension to .phps, which the server should send as raw PHP code. Note that this will expose the PHP source to the web, which could present a security risk.
As Mr. Squidward already mentioned, this should not be possible. Otherwise this would be a major security breach since you can store passwords for databases in the PHP files.
A possible solution for your problem would be that you create a REST API on the second server and there you have a function that gets the content of a specific file and returns it in JSON.
But ensure that you don't pass any critical data as passwords or user-data in it.

Download external JSON regularly

I'm currently using an API which returns a JSON object. I pay per hit, so I would like to minimize my hits. I use this object to fill in images and text on my page. The object that gets returned is very similar to a itunes lookup hit.
A simplified version of my code is this:
<img id="test" src="" alt="Image" />
<script>
$.getJSON( "https://itunes.apple.com/lookup?id=284910350", function( data ) {
document.getElementById('test').setAttribute("src", data.results[0].screenshotUrls[0]);
});
</script>
Everytime a users opens this page, a request gets sent to the server and a hit gets added to my account (obviously). I would like to store the object temporarily on my own server so I can request the data once, and serve a 'local' version to the user. What is the best way to do this? Is it possible to have the file updated every week or so automatically?
Thanks in advance!
It's an easy cron job. Assuming that you can execute bash script in your server:
1 - In your server put a bash script called fetchItune.sh. The content of this script basically stores some curl requests to outside API:
#!/bin/sh
curl -H "Accept: application/json" https://itunes.apple.com/lookup\?id\=284910350 -o /path/to/storage/data.json
You can get fancy with this script e.g. putting the list of endpoints in an array or output to different files, etc. but at the core, just make sure they are valid HTTP requests that accept a JSON response.
2 - Set up a cron job to do it weekly. It could be as simple as putting this script in /etc/cron.weekly if you are using an Ubuntu server. Otherwise, please search through your server documentation. I'm sure there is a section on cron job.
3 - From your JavaScript, request your server endpoint instead of the outside API:
<script>
$.getJSON( "/path/to/storage/data.json", function( data ) {
document.getElementById('test').setAttribute("src", data.results[0].screenshotUrls[0]);
});
</script>
EDIT: You can write PHP script to make request to external API instead of bash script. The principle is the same. I take this directly from PHP curl documentation: http://php.net/manual/en/curl.examples-basic.php
<?php
$ch = curl_init("https://itunes.apple.com/lookup\?id\=284910350");
$fp = fopen("/path/to/storage/data.json", "w");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

Passing variable from php to php

I was wondering how to send a php variable from one server to another php script on another server?
I have 2 php scripts on 2 different server and one must send vars to the other.
I've been searching with little luck.
Would appreciate any help.
You could achieve that using curl and sending the variable as a GET value.
Something like this:
$data = "data you want to send";
$data = urlencode($data);
$url = "http://example.com?data=" . $data;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_exec($ch);
curl_close($ch);
Let's assume $data = "foobar"
Doing the above from a PHP script would be the same as someone visiting http://example.com?data=foobar from a browser.
You could obviously send it to any script using the url:
http://example.com/yourscript.php?data=foobar
At yourscript.php you can get the data at $_GET['data'], do some input validation to ensure it is being sent from your script and not from someone else via a browser (more on that later) and then proceed with your script.
For this to work, yourscript.php will have to reside in the public html folder of youtr webhost so it is accessible to your other script.
SECURITY
Whether you are passing the data over GET or POST, someone else can send (possibly malicious) data to your script as well. Thus, when yourscript.php receives data, there needs to be a way for it to ensure you are the sender of the script. An easy way to achieve this is: decide on any arbitrary number known only to you, say, 12.
Concatenate the number with the data you are passing and calculate the md5 hash and send it as another get variable.
In this case, you would calculate md5("12foobar")
and the URL would be: http://example.com/yourscript.php?data=foobar&auth=hash
When yourscript.php receives the data, it calculates the same hash (using the number 12, known to no one else) and if the hash it calculates matches with $_GET['auth'], you can be sure you sent the data.
If someone tried to imitate you and send data, they would not know how you calculate the hash, and would thus send the wrong hash.
PS
Another way to ensure rock solid security, would be to just check the IP address of the user-agent at $_SERVER['REMOTE_ADDR']. If it is the IP address of the webhost where your other script resides, then you know it is you.
I haven't thought this method through, so there might be some loopholes.
You can do that either using GET query strings (second_php?var=value) or using a curl connection with POST method and then send your data over POST.
You should probably use SOAP. It's used for remote function calls and it brings you little more overhead than just calling http requests, but it also brings you guarantee that remote function will be executed (or will cause error), it will directly return whatever datatype you need and I believe that's what this technology was developed for :)

Make cURL behave like exactly like form

I have a form on my site which sends data to some remote site - simple html form.
What I want to do is to use data user enters into form for statistical purposes.
So I instead of sending data to the remote page I send it first to my script which resends it the remote site.
The thing is I need it to behave in exact way the usual form would behave taking user to the remote site and displaying resources.
When I use this code it kinda works but not in the way I want it to:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $action);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch);
curl_close($ch);
Problem is that it displays response in the same script. For example if $action is for example:
somesite.com/processform.php and my script name is mysqcript.php it would display the response of "somesite.com/processform.php" inside "mysqcript.php" so all the relative links are not working.
How do I make it to send the user to "somesite.com/processform.php"? Same thing that pressing the button would do?
Leonti
I think you will have to do this on your end, as translating relative paths is the client's job. It should be simple: Just take the base directory of the request you made
http://otherdomain.com/my/request/path.php
and add it in front of every outgoing link that does not begin with "/" or a protocol ("http://", "ftp://").
Detecting all the outgoing links is hard, but I am 100% sure there are ready-made PHP classes that do that. Check for example this article and the getLinks() function in the user comments. I am not 100% sure whether this is what you need but it certainly goes to the right direction.
Here are a couple of possible solutions, which I post separately so they don't get mixed up with the one I recommend:
1 - keep using cURL, parse the response and add a <base/> tag to it. It should work for pretty much everything on that page.
<base href="http://realsite.com/form_url.php" />
2 - do not alter the submit URL. Submit the form to the real URL, but capture its content using some Javascript library (YUI does that) and send it to your script via XHR. It's still kind of hacky though.
There are several ways to do that. Here's one of the easiest: just use a 307 redirect.
header('Location: http://realsite.com/form_url.php', true, 307');
You can do your logging and stuff either before or after header() but if you do it after calling header() you will need to start your script with
ignore_user_abort(true);
Note that browsers are supposed to notify the user that their form is being redirected.

Categories