Send cURL requests through tor? - php

I have some code that sends curl requests to a website but it only has the one website in it at the moment and I don't want them wrongly banning my server IP. Is there anyway I can send those cURL requests through the tor network?
What software would I need to do it?
Running CentOS 6.5
public function checkLogin2($email, $password, $cookiefile){
$cookiefile = 'cookies/'.$cookiefile;
$handle = fopen($cookiefile, 'w+');
#$proxy = 'proxy-nl.privateinternetaccess.com:1080';
#$us = 'x9597458:Th3hXjVyuD';
$this->_curl->setCookieFile($cookiefile);
#$this->_curl->addOption(CURLOPT_PROXY, $proxy);
#$this->_curl->addOption(CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
#$this->_curl->addOption(CURLOPT_PROXYUSERPWD, $us);
$this->_curl->setUserAgent('FreshAndroidApp-1.3.1');
$this->_curl->addHeader('Content-Type', 'application/x-www-form-urlencoded');
$this->_curl->addHeader('Cookie', 'JSESSIONID=' . strtoupper(md5(time())));
$this->_curl->addHeader('Cookie2', '$Version=1');
try {
$HTML = $this->_curl->post("URL HERE",
array('password' => $password,
'emailAddress' => $email
));
if(!self::isJson($HTML)){
return '{"status":"uncheck", "msg":"<font color="red"><b>Uncheck</b></font> => ' .$email.'|'.$password.'"}';
}
$resp = json_decode($HTML);
if($resp->{'status'} == "success"){
$details = $this->_curl->get('URL HERE');
return $details;
} else if ($resp->{'status'} == "failure"){
return '{"status":"failure"}';
}
fclose($handle);
} catch (CurlWrapperException $e){
return '{"status":"socksfailure", "msg":"'.$proxy. ' => Die or timeout"}';
}
fclose($handle);
}

You would need to install and run TOR, as explained in this link: https://www.torproject.org/docs/rpms.html.en
Then, if your code is right (I don't know much of PHP), just do:
$this->_curl->addOption(CURLOPT_PROXY, 127.0.0.1:9050);
$this->_curl->addOption(CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
Because TOR proxy runs by default on port 9050.
You can also put another IP instead of 127.0.0.1, if you are running TOR in another machine.
I think this should work

Related

How to select documentDB database azure using php?

I am trying to connect with documentDB Azure using php but I didn't get it to work. Now I am using the code given here but even that is not working. I can connect to the documentDB account but the problem is I can't select the database in my account. This is the selectDB function I am using
public function selectDB($db_name)
{
$rid_db = false;
$object = json_decode($this->listDatabases());
$db_list = $object->Databases;
foreach ($db_list as $value)
{
if ($value->id === $db_name)
{
$rid_db = $value->_rid;
}
}
if (!$rid_db)
{
$object = json_decode($this->createDatabase('{"id":"' . $db_name . '"}'));
$rid_db = $object->_rid;
}
if ($rid_db)
{
return new DocumentDBDatabase($this, $rid_db);
}
else
{
return false;
}
}
I tried to debug it and find that listDatabases() function is not working (not selecting the databases in account) Here is the listDatabase() function:
public function listDatabases()
{
$headers = $this->getAuthHeaders('GET', 'dbs', '');
$headers[] = 'Content-Length:0';
$options = array(
CURLOPT_HTTPHEADER => $headers,
CURLOPT_HTTPGET => true,
);
return $this->request("/dbs", $options);
}
Can someone help me with this issue?
Regarding to your issue, you can add var_dump(curl_error($curl)); in the request function in phpdocumentdb.php you required for troubleshooting the curl issues.
If you are developing on local or some dev environment, you may occur the SSL certificate issue. The curl error may output the message: SSL certificate problem: unable to get local issuer certificate.
And for developing, you can simple add sentence curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); in the request function in phpdocumentdb.php to bypass the SSL verification.
If you are in prod env, you should create SSL certificate in your PHP runtime. Refer to https://blogs.msdn.microsoft.com/azureossds/2015/06/12/verify-peer-certificate-from-php-curl-for-azure-apps/ for more.

php variable $_SERVER['SERVER_ADDR'] is blank when using crontab

I have a small script which gets basic information like the server IP-, and the MAC-address of the server the script is running on, I am then posting the results to a mysql database, this works fine and the code is shown below. However when I use a cronjob to execute the script everything but the IP address is being stored, for some reason the $_SERVER['SERVER_ADDR'] is blank when being executed as a cronjob.
This script runs every min, and is run on multi Raspberry PI's so I can tell which is connected to share job requests.
$mac_address = getMacLinux();
$server_ip = $config['server_ip'];
$client_ip = $_SERVER['SERVER_ADDR'];
$client_name = $config['client_name'];
$ch = curl_init();
$url = "{$server_ip}/checkin0.php";
echo "url = {$url}"."<br>";
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "client_ip={$client_ip}&client_name={$client_name}&client_mac={$mac_address}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch); // Execute
curl_close ($ch); // Close cURL handle
var_dump($output); // Show output
i found the following
function getServerAddress() {
if(isset($_SERVER["SERVER_ADDR"]))
return $_SERVER["SERVER_ADDR"];
else {
// Running CLI
if(stristr(PHP_OS, 'WIN')) {
// Rather hacky way to handle windows servers
exec('ipconfig /all', $catch);
foreach($catch as $line) {
if(eregi('IP Address', $line)) {
// Have seen exec return "multi-line" content, so another hack.
if(count($lineCount = split(':', $line)) == 1) {
list($t, $ip) = split(':', $line);
$ip = trim($ip);
} else {
$parts = explode('IP Address', $line);
$parts = explode('Subnet Mask', $parts[1]);
$parts = explode(': ', $parts[0]);
$ip = trim($parts[1]);
}
if(ip2long($ip > 0)) {
echo 'IP is '.$ip."\n";
return $ip;
} else
; // TODO: Handle this failure condition.
}
}
} else {
$ifconfig = shell_exec('/sbin/ifconfig eth0');
preg_match('/addr:([\d\.]+)/', $ifconfig, $match);
return $match[1];
}
Look in the manual
$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server
PS. Also you can use your script as CGI script (and $_SERVER['SERVER_ADDRESS'] will be correct). You may try fetch, wget, curl... and call script from crontab i.e. (server-IP is 192.168.0.1):
1 * * * * fetch http://192.168.0.1/my_script.php

enabling curl extension in php for 000webhost.com

So I'm trying to integrate my app with facebook and I'm using the default example.php's code as my index.php. I've changed the appID and appSecret to match my app's id and secret, whenever I test the code on facebook, it will throw an exception namely UnhandledCurlException. Wraping the code with try and catch will only return 0 whenever I call the getUser() method.
I'm aware that I could enable the curl extension on php.ini, but I can only find that on my localhost but not on the server(000webhost.com) which I used to deploy my app.
I've also heard that it's possible to use .htaccess file to explicitly modify the php configurations and hence enable the curl extension, anyone knows how to do that? or are there any other alternatives which I missed?
This is the function that throws error:
protected function makeRequest($url, $params, $ch=null) {
if (!$ch) {
$ch = curl_init();
}
$opts = self::$CURL_OPTS;
if ($this->getFileUploadSupport()) {
$opts[CURLOPT_POSTFIELDS] = $params;
} else {
$opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
}
$opts[CURLOPT_URL] = $url;
// disable the 'Expect: 100-continue' behaviour. This causes CURL to wait
// for 2 seconds if the server does not support this header.
if (isset($opts[CURLOPT_HTTPHEADER])) {
$existing_headers = $opts[CURLOPT_HTTPHEADER];
$existing_headers[] = 'Expect:';
$opts[CURLOPT_HTTPHEADER] = $existing_headers;
} else {
$opts[CURLOPT_HTTPHEADER] = array('Expect:');
}
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);
$errno = curl_errno($ch);
// CURLE_SSL_CACERT || CURLE_SSL_CACERT_BADFILE
if ($errno == 60 || $errno == 77) {
self::errorLog('Invalid or no certificate authority found, '.
'using bundled information');
curl_setopt($ch, CURLOPT_CAINFO,
dirname(__FILE__) . DIRECTORY_SEPARATOR . 'fb_ca_chain_bundle.crt');
$result = curl_exec($ch); //the line 1003
}
// With dual stacked DNS responses, it's possible for a server to
// have IPv6 enabled but not have IPv6 connectivity. If this is
// the case, curl will try IPv4 first and if that fails, then it will
// fall back to IPv6 and the error EHOSTUNREACH is returned by the
// operating system.
if ($result === false && empty($opts[CURLOPT_IPRESOLVE])) {
$matches = array();
$regex = '/Failed to connect to ([^:].*): Network is unreachable/';
if (preg_match($regex, curl_error($ch), $matches)) {
if (strlen(#inet_pton($matches[1])) === 16) {
self::errorLog('Invalid IPv6 configuration on server, '.
'Please disable or get native IPv6 on your server.');
self::$CURL_OPTS[CURLOPT_IPRESOLVE] = CURL_IPRESOLVE_V4;
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$result = curl_exec($ch);
}
}
}
if ($result === false) {
$e = new FacebookApiException(array(
'error_code' => curl_errno($ch),
'error' => array(
'message' => curl_error($ch),
'type' => 'CurlException',
),
));
curl_close($ch);
throw $e;
}
curl_close($ch);
return $result;
}
First of all make sure if cURL extension is really configured or not by using this code.
<?php
echo function_exists('curl_version') ? 1:0; // 1 = enabled , 0 = disabled.
If it is disabled, Kindly ask your webhosting provider to enable the extension. [I don't think that's a hard thing to do , instead of playing around .htaccess and other means to enable cURL without their knowledge. ]

Attempting to make POST request from one page on my site to another with PHP and Curl

Hey all I have seen several questions on the topic here, but none of them have solved my problem. I have a script on my site which I want to use to generate several different types of emails to my users. I wanted a way to be able to create template files for the different emails which accept $_POST variables to fill in relevant information, and to simply make a post request to these templates and get back the response to place as the body of the email. I am attempting to write a function which would accept the location of the template file (either relative or absolute would work, but I would prefer relative honestly), and an array of parameters that I would like to send to the template via post. So far I have had no luck. Here is my code so far:
private function post_request($url, $data) {
$output = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
curl_close($ch);
if ($result) {
$output['status'] = "ok";
$output['content'] = $result;
} else {
$output['status'] = "failure";
$output['error'] = curl_error($ch);
}
curl_close($ch);
return $output;
}
I have been getting the error "couldn't connect to host" from curl, but after outputting my url to an error log I have been able to verify that copying and pasting the URL into firefox results in seeing the page correctly.
Any ideas? I am not married to the idea of using curl, so if there is a better option I would be more than happy to use it instead. Thanks for the help all!
You should be able to use file_get_contents() for this, so long as your host has not prevented it from accessing remote locations (and the $url script is not looking exclusively for POST data).
private function post_request($url, $data) {
$output = array();
$url_with_data = '';
foreach ( $data as $k=>$v ){ // Loop through data and create request string
$url_with_data .= '&' . $k . '=' . $v;
}
// Remove first ampersand and encode the data
$url_with_data = urlencode( substr( $url_with_data, 1 ) );
// Request file
// Format will be http://url.com?var1=data&var2=data&var3=data
$result = file_get_contents( $url . '?' . $url_with_data );
if ($result) {
$output['status'] = "ok";
$output['content'] = $result;
} else {
$output['status'] = "failure";
$output['error'] = 'Could not open remote file';
}
return $output;
}
Another option: You say that both files reside on the same server. If that is the case, you could simply require() the template builder.
private function post_request($url, $data) {
$output = array();
#require_once('./path/to/template_builder.php');
if ($result) {
$output['status'] = "ok";
$output['content'] = $result;
} else {
$output['status'] = "failure";
$output['error'] = 'Could not open remote file';
}
return $output;
}
Then in template_builder.php:
<?php
unset( $result );
if ( is_array( $data ) ){
// Parse $data ...
$result = $email_template;
}
As it turns out, the issue ended up being a server configuration error. The server was timing out while attempting to contact the file because it was hitting the wrong DNS server. Fixing that solved my problem!

Fsockopen and proxy authentication in PHP

I'm trying to integrate proxy usage (with authentication) into a script that queries whois data.
What I'm trying to do is
1) Connect to the proxy IP and port
2) authenticate a username and password
3) connect to the whois server and send domain details, receiving the request in return.
I have the script working without proxies
private function whois($domeinnaam, $whoisrule)
{
list ($server, $poort, $domein, $vrij) = $whoisrule;
$domein = str_replace("{domein}", $domeinnaam, $domein);
$fp = fsockopen($server, $poort);
if($fp)
{
fputs($fp, $domein."\r\n");
$data = "";
while(!feof($fp))
{
$data .= fread($fp, 1000);
}
fclose($fp);
}
else
{
$data = "error";
}
// Cache whois data
$this->_whoisdata[$domein] = $data;
return $data;
}
But does anyone how I would integrate a proxy server and authentication into this code?
cURL has some handy CURLOPT_PROXY* options. This answer shows how to use them.

Categories