convert fopen to curl? - php

I have recently changed servers, and one of my scripts is not functioning on the new server, as fopen is not enabled?
Is it possible to change the following code to use the CURL function instead?
Hope someone can help!
<?php
$postToFileName = 'http://www.somesite.com/postfile.aspx';
$postArr = array(
'NM' => $row['Lead_Name'],
'EM' => $row['Lead_Email'],
'PH' => $row['Lead_Tel'],
);
$opts = array(
'http'=>array(
'method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'content' => http_build_query($postArr)
)
);
$context = stream_context_create($opts);
$fp = fopen($postToFileName, 'r', false, $context);
$returnedMessage = '';
while (!feof($fp)) {
$returnedMessage .= fgets($fp);
}
fclose($fp);
if ($returnedMessage == '') {
$returnedMessage = 'No Message';
} else if (strlen($returnedMessage) > 250) {
$returnedMessage = substr($returnedMessage,0,250);
}
$returnedMessage = preg_replace("/[\r\n]/", '', $returnedMessage);
$returnedMessage = mysql_real_escape_string($returnedMessage, $sql);
$q = "UPDATE leads SET Data_Sent = '$returnedMessage' WHERE Lead_ID = $id";
mysql_query($q, $sql);
array_push($leadsSent, $id);
}
}
mysql_close($sql);
return $leadsSent;
}
?>

Yes, it's quite possible. See the examples here:
http://us.php.net/manual/en/curl.examples-basic.php

Sure. It should probably look like this (not tested of course, might need some minor changes) :
$postToFileName = 'http://www.somesite.com/postfile.aspx';
$postArr = array(
'NM' => $row['Lead_Name'],
'EM' => $row['Lead_Email'],
'PH' => $row['Lead_Tel'],
);
$ch = curl_init($postToFileName);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postArr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$returnedMessage = curl_exec($ch);
curl_close($ch);

Related

Unable to upload file to box using Api in php

I'm unable to upload file on box using php. I've tried all the contents which I've found on stackOverflow but never got success. Even I've tried https://github.com/golchha21/BoxPHPAPI/blob/master/README.md Client but still got failure. Can anyone help me how to upload file on box using php curl.
$access_token = 'xGjQY2XU0bmOEwVAdkqiZTsGuFyFuqzU';
$url = 'https://upload.box.com/api/2.0/files/content';
$headers = array("Authorization: Bearer $access_token"
. "Content-Type:multipart/form-data");
$filename = 'file.jpg';
$name = 'file.jpg';
$parent_id = '0';
$post = array('filename' => "#" . realpath($filename), 'name' => $name,
'parent_id' => $parent_id);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);
var_dump($response);
Even I've used this request too...
$localFile = "file.jpg";
$fp = fopen($localFile, 'r');
$access_token = '00hsilvu9LrAsKQ8iDzXZAAieSLrjzX9';
$url = 'https://upload.box.com/api/2.0/files/content';
$curl = curl_init();
$cfile = new CURLFILE($localFile, 'jpg', 'Test-filename.jpg');
$data = array();
//$data["TITLE"] = "$noteTitle";
//$data["BODY"] = "$noteBody";
//$data["LINK_SUBJECT_ID"] = "$orgID";
//$data["LINK_SUBJECT_TYPE"] = "Organisation";
$data['filename'] = "file.jpg";
$data['parent_id'] = 0;
curl_setopt_array($curl, array(
CURLOPT_UPLOAD => 1,
CURLOPT_INFILE => $fp,
CURLOPT_NOPROGRESS => false,
CURLOPT_BUFFERSIZE => 128,
CURLOPT_INFILESIZE => filesize($localFile),
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer 00hsilvu9LrAsKQ8iDzXZAAieSLrjzX9",
"Content-Type:multipart/form-data"
),
));
$response = curl_exec($curl);
$info = curl_getinfo($curl);
$err = curl_error($curl);
curl_close($curl);
var_dump($info);
$req_dump = print_r($response, true);
file_put_contents('box.txt', $req_dump, FILE_APPEND);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
And in response I always got an empty string.
Please tell me what am I doing wrong?
I'm using Box PHP Client for creation of folders, uploading of files and then sharing of uploaded files using this client.
https://github.com/golchha21/BoxPHPAPI
But this client's uploading file wasn't working... then I dig into it and I found something missing into this method.
/* Uploads a file */
public function put_file($filename, $name ,$parent_id) {
$url = $this->build_url('/files/content', array(), $this->upload_url);
if(isset($name)){
$name = basename($filename);
}
$params = array('filename' => "#" . realpath($filename), 'name' => $name , 'parent_id' => $parent_id, 'access_token' => $this->access_token);
return json_decode($this->post($url, $params), true);
}
Just put forward slash after # sign. Like this, Then I'll start working
/* Uploads a file */
public function put_file($filename, $name ,$parent_id) {
$url = $this->build_url('/files/content', array(), $this->upload_url);
if(isset($name)){
$name = basename($filename);
}
$params = array('filename' => "#/" . realpath($filename), 'name' => $name , 'parent_id' => $parent_id, 'access_token' => $this->access_token);
return json_decode($this->post($url, $params), true);
}

Invisible recaptcha siteverify - error codes

I'm trying to verify my $_POST['g-recaptcha-response'] on https://www.google.com/recaptcha/api/siteverify but i keep getting the following result:
"success": false,
"error-codes": [
"missing-input-response",
"missing-input-secret"
]
My code:
if($has_errors == false) {
$result = file_get_contents( 'https://www.google.com/recaptcha/api/siteverify', false, stream_context_create( array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query( array(
'response' => $_POST['g-recaptcha-response'],
'secret' => variable_get('google_recaptcha_secret', '')
) ),
),
) ) );
var_dump($result);
$result = json_decode($result);
if($result->success == false) {
form_set_error('name', t('Submission blocked by Google Invisible Captcha.'));
}
}
I checked my variable google_recaptcha_secret, it is correct.
I've never seen file_get_contents used to post data like that, I'm not saying it's not possible but I would recommend trying with cURL:
if ($has_errors == false) {
$data = [
'response' => $_POST['g-recaptcha-response'],
'secret' => variable_get('google_recaptcha_secret', ''),
];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($curl);
$error = !$result ? curl_error($curl) : null;
curl_close($curl);
var_dump($result);
$result = json_decode($result);
if ($error || $result->success == false) {
form_set_error('name', t('Submission blocked by Google Invisible Captcha.'));
}
}

Make a web service call in php

So i have this working in ruby and i want to be able to do this in php. I am using the wamp server if that matters.
Here's the ruby method:
def response(url, body)
uri = URI(url)
request = Net::HTTP::Post.new(uri.request_uri)
request.body = body
http_session = Net::HTTP.new(uri.hostname, uri.port)
http_session.use_ssl = (uri.scheme == "https")
http_session.verify_mode = OpenSSL::SSL::VERIFY_NONE
response = http_session.request(request)
return response.body
end
I tried looking up other questions and this is where that got me:
$request_info = array();
$REQUEST_BODY = 'request body';
$full_response = #http_post_data(
'url',
$REQUEST_BODY,
array(
'headers' => array(
'Content-Type' => 'text/xml; charset=UTF-8',
'SOAPAction' => 'HotelAvail',
),
'timeout' => 60,
),
$request_info
);
$response_xml = new SimpleXMLElement(strstr($full_response, '<?xml'));
foreach ($response_xml->xpath('//#HotelName') as $HotelName) {
echo strval($HotelName) . "\n";
}
http_post_data depends on pecl_http. Unless you must use http_post_data, cURL is probably installed by default on your WAMP server.
The code below is just an example; I haven't tested it but you get the idea:
$headers = array(
'Content-Type' => 'text/xml; charset=UTF-8',
'SOAPAction' => 'HotelAvail',
);
$ch = curl_init($server_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$full_response = curl_exec($ch);
curl_close($ch);

Wrong header with cURL in PHP with Redmine's REST API

I'm currently trying to create an issue in Redmine via the REST API. I export the issues from Redmine in a CSV file. Then, I'm creating an xml file from the CSV, then send it to the API with cURL. I'm setting some options :
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_URL => URL_REDMINE,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/xml; charset=utf-8',
'X-Redmine-API-Key: '.KEY_API),
CURLOPT_BINARYTRANSFER => TRUE,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $dataXML,
CURLOPT_SAFE_UPLOAD => TRUE,
CURLOPT_ENCODING => "utf-8"
));
curl_exec($curl);
echo json_encode(curl_getinfo($curl));
So, I'm clearly saying that the encoding should be UTF-8. But when I print the informations (with curl_getinfo), here's what I get :
{"url":"[URL I was targeting]",
"content_type":"text\/html; charset=iso-8859-1", [...]}
(I erased some irrelevant informations, but if someone wants it entirely, I can paste it.)
So, it says the content_type is text\/html; charset=iso-8859-1 when I set it as application/xml; charset=utf-8. Is there something I didn't understand with REST API?
Following is simple curl call for php with redmine.
**flie class file in redmine/redmine_curl.php**
<?php # Redmine Api
class class_redmine{
function get_upload_token($filecontent){
global $redmine_url , $redmine_key;
$upload_url = $redmine_url.'uploads.json?key='.$redmine_key;
$request['type'] = 'post';
$request['content_type'] = 'application/octet-stream';
//$filecontent = file_get_contents('test.php');
return $token = $this->curl_redmine($upload_url,$request,$filecontent);
//$token->upload->token;
}
#Issue
function create_issue($post_data){
global $redmine_url , $redmine_key;
$issue_url = $redmine_url.'issues.json?key='.$redmine_key;
$request['type'] = 'post';
$request['content_type'] = 'application/json';
return $this->curl_redmine($issue_url,$request,$post_data);
}
function get_issue($issue_id='',$project_id=''){
global $redmine_url , $redmine_key;
if($project_id!=''){
$issue_url = $redmine_url.'issues.json?key='.$redmine_key.'&project_id='.$project_id;
}else{ $issue_url = ($issue_id=='')?$redmine_url.'issues.json?key='.$redmine_key : $redmine_url.'issues/'.$issue_id.'.json?key='.$redmine_key;
}
return $this->curl_redmine($issue_url,'','');
}
#Projects
function get_projects($project_id=''){
global $redmine_url , $redmine_key;
$proj_url = ($project_id=='')?$redmine_url.'projects.json?key='.$redmine_key : $redmine_url.'projects/'.$project_id.'.json?key='.$redmine_key;
return $this->curl_redmine($proj_url,'','');
}
#Curl
function curl_redmine($redmine_url,$request='',$post_data=''){
if(!isset($request['type'])){ $request['type']=null; }
if(!isset($request['content_type'])){ $request['content_type']=null; }
//Create a curl object
$ch = curl_init();
//Set the useragent
$agent = $_SERVER["HTTP_USER_AGENT"];
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
//Set the URL
curl_setopt($ch, CURLOPT_URL, $redmine_url );
if($request['type'] == 'post'){
//This is a POST query
curl_setopt($ch, CURLOPT_POST,1);
// curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
//Set the post data
curl_setopt($ch, CURLOPT_POSTFIELDS,$post_data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: '.$request['content_type'],
'Content-Length: ' . strlen($post_data))
);
}
//We want the content after the query
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//Follow Location redirects
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
/*
Set the cookie storing files
Cookie files are necessary since we are logging and session data needs to be saved
*/
//curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
//curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
//Execute the action to login
$postResult = curl_exec($ch);
//if($postResult == false){ return $info = curl_getinfo($ch);}
$response = json_decode($postResult);
//echo '<pre>'; print_r($response); echo '</pre>';
return $response;
}
}//class_redmine
?>
Example file example.php
<?php
//code for class_settting.php
function get_redmine($methodName='',$data=''){
global $redmine_url , $redmine_key;
//$query='select * from '.VIS_TABLE_PREFIX.'integration where integration_type=37 and is_enabled=1 and domain_id='.VIS_DOMAIN;
//$res = $this->database->query_exec($query);
//$login_integrate=$this->database->fetch_result_array($res);
/*if($login_integrate==-1){ return $login_integrate; }
if(count($login_integrate)>0 && $login_integrate!=-1){
$redmine_url = $login_integrate[0]['billing_url'];
$redmine_username = $login_integrate[0]['admin_user'];
$redmine_password = $login_integrate[0]['admin_password'];
$redmine_key = $login_integrate[0]['api_key'];
}*/
$redmine_url = 'http://localhost/redmine/';
$redmine_key = '41f132773cc29887bc2e4566863aedc01cde6e2b';
include_once('redmine/redmine_curl.php');
$obj_redmine = new class_redmine();
#check Auth
$res = $obj_redmine->get_projects();
if(!isset($res->projects) || (isset($res->total_count) && ($res->total_count)==0)){ return -1; }
switch($methodName){
case 'check_status' : return $login_integrate; ##check redmine integration in vision
break;
##Trackers
//
##Issue statuses
//
##Project
case 'projectAll' : return $obj_redmine->get_projects(); #used
break;
case 'projectById' : return $obj_redmine->get_projects($data['project_id']);
break;
##Users
//
##Issues
case 'showIssue' : return $obj_redmine->get_issue($data['issue_id']);
break;
case 'issueAll' : return $obj_redmine->get_issue();
break;
case 'issueByProjectId' : return $obj_redmine->get_issue('',$data['project_id']);
break;
case 'createIssue' : return $obj_redmine->create_issue($data);
break;
case 'uploadFileToIssue' : return $obj_redmine->get_upload_token($data);
break;
default: return 0;
}
}
$filecontent = file_get_contents('test.php');
$token = get_redmine('uploadFileToIssue',$filecontent);
$filecontent = file_get_contents('Picture.jpg');
$token2 = get_redmine('uploadFileToIssue',$filecontent);
$uploads = array(
array(
'token' => $token->upload->token,
'filename' => 'MyFile.php',
'description' => 'MyFile is better then YourFile...',
'content_type' => 'application/txt',
),
array(
'token' => $token2->upload->token,
'filename' => 'Picture.jpg',
'description' => 'MyFile is better then YourFile...',
'content_type' => 'application/image',
),
);
$custom_fields = array(
array(
'id' => 1,
'name' => 'Phone',
'value' => '1234265689'
),
array(
'id' => 2,
'name' => 'Proj sub name',
'value' => 'Test'
),
);
$post_data = array('issue'=>array(
'project_id' => 4,
'subject' => 'ABCDEFG',
'description' => 'Test',
'uploads' => $uploads,
'custom_fields' => $custom_fields,
),);
$post_data = json_encode($post_data);
#all proj
//$res = get_redmine('projectAll');
#proj by id
//$res = get_redmine('projectById',array('project_id'=>'4'));
#get all issue
//$res = get_redmine('issueAll');
#get issue by id
//$res = get_redmine('showIssue',array('issue_id'=>'85'));
#get issue by project id
//$res = get_redmine('issueByProjectId',array('project_id'=>'5'));
#create issue
$res = get_redmine('createIssue',$post_data);
echo '<pre>';print_r($res);
?>

POST and GET without cURL PHP

I tried some times release POST and GET in this site http://www.sefaz.pe.gov.br/sintegra, but it doesn´t work
// POST
$data = array('CNPJ' => '02340534000192', 'consulta' => 'OK', 'vazio' => '');
$html = $this->HTTP_Post('http://www.sefaz.pe.gov.br/sintegra/consulta/consulta.asp', $data, $cookie);
$arr = split("Set-Cookie:", $html);
$cookie="";
$count=1;
while ($count < count($arr))
{
$cookie.=substr($arr[$count].";", 0, strpos($arr[$count].";",";")+1);
$count++;
}
// GET after POST
echo $this->get_url('http://www.sefaz.pe.gov.br/sintegra/consulta/exibirResultado.asp', $cookie);
I tried file_get_contents and curl too... both without success
function get_url($url,$cookie=false)
{
$url = parse_url($url);
$query = $url[path]."?".$url[query];
echo "Query:".$query;
$fp = fsockopen( $url[host], $url[port]?$url[port]:80 , $errno, $errstr, 30);
if (!$fp)
{
return false;
}
else
{
$request = "GET $query HTTP/1.1\r\n";
$request .= "Host: $url[host]\r\n";
$request .= "Connection: Keep-Alive\r\n";
if($cookie) $request.="Cookie: $cookie\n";
$request.="\r\n";
fwrite($fp,$request);
while (!feof($fp))
{
$result .= fgets($fp, 128);
}
fclose($fp);
return $result;
}
}
function HTTP_Post($URL,$data,$cookie, $referrer="")
{
$URL_Info=parse_url($URL);
if($referrer=="") $referrer="111";
foreach($data as $key=>$value)
$values[]="$key=".urlencode($value);
$data_string=implode("&",$values);
if(!isset($URL_Info["port"]))
$URL_Info["port"]=80;
$request.="POST ".$URL_Info["path"]." HTTP/1.1\n";
$request.="Host: ".$URL_Info["host"]."\n";
$request.="Referer: $referer\n";
$request.="Content-type: application/x-www-form-urlencoded\n";
$request.="Content-length: ".strlen($data_string)."\n";
$request.="Connection: Keep-Alive\n";
$request.="Cookie: $cookie\n";
$request.="\n";
$request.=$data_string."\n";
$fp = fsockopen($URL_Info["host"],$URL_Info["port"]);
fputs($fp, $request);
while(!feof($fp))
{
$result .= fgets($fp, 1024);
}
fclose($fp);
return $result;
}
functions GET and POST with fsocket.
any ideas are welcome
Thanks
EDIT 1:
Thank you, but it doesn´t work. I tried 20 times, but this website doesn´t work...
The browser message appears: Atenção: Acesso negado! Favor selecionar algum parâmetro de consulta.
Caution: Access Denied! Please select a query parameter.
my code with your code
function POST()
{
$postdata = http_build_query(
array(
'CNPJ' => '02340534000192',
'consulta' => 'OK',
'vazio' => '',
'CPF' => '',
'IE' => '',
'razaosocial' => ''
));
$headers = array(
'Content-type: application/x-www-form-urlencoded',
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => implode("\r\n", $headers),
'content' => $postdata,
));
$context = stream_context_create($opts);
$result = file_get_contents('http://www.sefaz.pe.gov.br/sintegra/consulta/consulta.asp', false, $context);
return $result;
}
I think you can do file_get_contents for GET
or http://php.net/manual/en/context.http.php for POST
Example from php.net website
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/submit.php', false, $context);
Your IP is probably blocked by the website.

Categories