I made a PHP function that works with an API to show me the dollar balance of an account. This function is called: get_balance
function get_balance($account){
$url = 'http://mycompaniesurl.com/' . $account; // url of website
global $response;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
$response = curl_exec($ch);
curl_close($ch);
}
The function get_balance returns the output in the variable $response
I'm certain that the function works, so I have no questions on that part. However, I'm trying to process accountnumbers written down in a CSV file. I call the CSV file with the following code:
$file = new SplFileObject("test.csv");
$file->setFlags(SplFileObject::READ_CSV);
$data = call_user_func_array('array_merge', iterator_to_array($file));
$data = array_combine(range(1, count($data)), $data);
extract($data, EXTR_PREFIX_ALL, 'variable');
I'm testing my code with a csv file called test.csv, containing 4 addresses (first one has a balance of 0, other 3 have a balance of >0).
With the following code I get the balance with the accountnumber printed to my screen:
get_balance($data[2]);
if ($response > 0){
echo $response,"---------------",$data[2];
}
Because $data[1] has a balance of 0, nothing is printed. $data[2],$data[3] and $data[4] have a balance of more than 0, so they do return the balance together with the accountnumber.
Now what my question is; is there a way to 'automatically' do this? Something like
get_balance($data[]);
seems to not work. The CSV that this php file has to process is about ~1000 accountnumber and may have more in the future, so typing a get_balance($data[1]) up to get_balance($data[999]) will be a time consuming business.
Is there a (simple) way to apply the function to ALL the $data[] ?
Yes, there is, called array_map:
$balanced_data = array_map("get_balance", $data);
This will leave $balanced_data empty, because at the moment get_balance has no return, but uses a global variable. Change it to something like this
function get_balance($account){
$url = 'http://mycompaniesurl.com/' . $account; // url of website
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
If you don't want to or can't change get_balance, you will need a workaround like this
$max = count($data);
for ($i=0; $i<$max; $i++) {
$response = 0; // reset to make sure we get a new value
get_balance($data[$i]);
$balanced_data[$i] = $response;
}
Related
I am trying to integrate zoho with my web app. I am making an api call to get a particular invoice. The call as per documentation is
'https://books.zoho.com/api/v3/invoices/INV_ID?organization_id=XXXXXXXX'
This works fine as well. But when I set a variable for INVOICE ID, it returns all the invoices. (200 INVOICES) The call is below.
'https://books.zoho.com/api/v3/invoices/' .$inv_id. '?organization_id=XXXXXXXX';
where I am making the mistake? The method is below.
$zid = '';
if(isset($_POST['_zid'])){
$zid = $_POST['_zid'];
}
get_invoice($access_token, $zid);
function get_invoice($access_token, $zid){
$invid = $zid;
$service_url = $GLOBALS['service_url'] . 'https://books.zoho.com/api/v3/invoices/' .$invid. '?organization_id=XXXXXXXXX';
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $service_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Zoho-oauthtoken '. $access_token,
'Content-Type: "application/json"'));
$res = curl_exec($ch);
curl_close($ch);
$dec_res = array();
$dec_res = json_decode($res, true);
print_r($dec_res);
}
Everything is fine except a small thing. I didn't think of Array Declaration. The working call is straightly given an integer as the invoice_id. when I pass the variable declared as a string. so although the digits it is counted as a string which makes the call invalid.
//THIS WILL DO THE TRICK
$zid = 0;
if(isset($_POST['_zid'])){
$zid = $_POST['_zid'];
}
I am trying to senddata to a url by using curl with codeigniter. I have successfully implemented the code for sending the data as below.
function postToURL($reg_no, $data)
{
$url = 'http://localhost/abcSystem/Web_data/viewPage';
$send_array = array(
'reg_no' =>$reg_no,
'data' =>$data,
);
$fields_string = http_build_query($send_array);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 600);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_REFERER, $url);
$post_data = 'json='.urlencode(json_encode($send_array));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
if (curl_errno($ch)) {
die('Couldn\'t send request: ' . curl_error($ch));
} else {
$resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($resultStatus == 200) {
print_r('success'); // this is outputting
return $output;
} else {
die('Request failed: HTTP status code: ' . $resultStatus);
}
}
curl_close($ch);
}
The out put is success. I want to see if this post data can be retrieved. So I tried to change the above url controller file as below.
$fp = fopen('php://input', 'r');
$rawData = stream_get_contents($fp);
echo "<pre>";
print_r($rawData);
echo "</pre>";
But nothing is printing. I want to get the data of posting. Please help me on this.
Your Written code
$fp = fopen('php://input', 'r');
$rawData = stream_get_contents($fp);
echo "<pre>";
print_r($rawData);
echo "</pre>";
is not to Print or capture Posted Data . Because you are dealing with Current Page PHP INPUT Streaming , whereas you are posting data on Other URL . So what you need to do is just Put a log of posted data in File. Use below code after $output = curl_exec($ch)
file_put_contents("posted_data.txt", $post_data );
This way you will be able to write your each post in file Posted_data.txt File - Make sure you give proper File Permission. If you want to keep trace of each POST than just make the file name dynamic so per API Call it can write a log.
Another option is to save the $post_data in DATABASE - Which is not suggestable from Security point of view.
Where ever you are calling your postToURL() function, you need to output the result of it.
For example:
$output = postToURL('Example', array());
echo $output;
This is because you are returning the curl output rather outputting it.
I wants to create a php script for alerts from my work website when new notice is published, so following the page url
http://www.mahapwd.com/nit/ueviewnotice.asp?noticeid=1767
from this page i want a variable for Date & Time of Meeting (Date and time seperately two variables)
Place of Meeting and Published On
please help me to create a perfect php script.
I tried to create following script but it gives to many errors
<?php
$url1 = "http://www.mahapwd.com/nit/ueIndex.asp?district=12";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
preg_match("/href=(.*)\", $data, $urldata);
$url2 = "http://www.mahapwd.com/nit/$urldata[1];
curl_setopt($ch, CURLOPT_URL, $url2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data2 = curl_exec($ch);
preg_match("/Published On:</b>(.*)<\/font>", $data, $pubDt);
$PubDate = $pubDt[1];
preg_match("/Time of Meeting:</b>(.*) ", $data, $MtDt);
$MeetDate = $MtDt[1];
preg_match("/Time of Meeting:</b>$MtDt[1] (.*)</font>", $data, $MtTime);
$MeetTime = $MtTime[1];
preg_match("/Place of Meeting:</b>(.*)<\/font>", $data, $pubDt);
$PubDate = $pubDt[1];
?>
Hello i have done simple code for you. You can download simple_html_dom.php from http://simplehtmldom.sourceforge.net/
require_once "simple_html_dom.php";
$url='http://www.mahapwd.com/nit/ueviewnotice.asp?noticeid=1767';
//parse url
for ($i=0;$i<1;$i++) {
$html1 = file_get_html($url);
if(!$html1){ echo "no content"; }
else {
//here is parsed html
$string1 = $html1;
//now you need to find table
$element1=$html1->find('table');
//here is a table you need
$input=$element1[2];
//now you can select row from here
foreach($input->find('td') as $element) {
//in here you can find name than save it to database than check it
}
}
}
I was trying to download the results of a batch and was coding a program for this.
On an aspx file, I was able to write the following PHP code since the URL included the parameters:
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
for ($i=1; $i<15000; $i++) {
$url = "http://example.com/result.aspx?ClassId=342&TermId=95&StudentId=".$i;
$returned_content = get_data($url);
if (stripos($returned_content,'Roll') !== false) {
echo "Student ID:" . $i;
echo $returned_content;
}
}
However, when a result is queried on a .ASP file, the URL simply says 'results.asp' without any additional parameters. Is there a way to use CURL requests to run a for loop and download this data in a similar manner?
Thanks for any help!
Here is my code
$url = "partial_response.php";
$sac_curl = curl_init();
curl_setopt($sac_curl, CURLOPT_HTTPGET, true);
curl_setopt($sac_curl, CURLOPT_URL, $url);
curl_setopt($sac_curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($sac_curl, CURLOPT_HEADER, false);
curl_setopt($sac_curl, CURLOPT_TIMEOUT, 11);
$resp = curl_exec($sac_curl);
curl_close($sac_curl);
echo $resp;
Partial_response.php
header( 'Content-type: text/html; charset=utf-8' );
echo 'Job waiting ...<br />';
for( $i = 0 ; $i < 10 ; $i++ )
{
echo $i . '<br/>';
flush();
ob_flush();
sleep(1);
}
echo 'End ...<br/>';
From the about code am trying to get a partial response from partial_response.php. what I want is, I need curl to return me "Job waiting.." alone instead of waiting for the partial_response.php to complete the loop and return the entire data. so when I reduce CURLOPT_TIMEOUT below 11 i dont get any response at all. Kindly clarify my doubt.
Thanks in advance.
I later realized that cURL could not do what I want, I used stream_context_get_options
to achieve what I wanted. Here it is, http://www.php.net/manual/en/function.stream-context-get-options.php.
No, I'm afraid not. At least not that I know of any, this is simply because PHP is a synchronous language, meaning you cannot "skip" tasks. (I.e. curl_exec() will always - no matter what - be executed until the request is completed)
I'm not sure abut the timeout, but you can get partial response using cURL by using the CURLOPT_WRITEFUNCTION flag:
curl_setopt($ch, CURLOPT_WRITEFUNCTION, $callback);
Where $ch is the Curl handler, and $callback is the callback function name. This command will stream response data from remote site. The callback function can look something like:
$result = '';
$callback = function ($ch, $str) {
global $result;
//$str has the chunks of data streamed back.
$result .= $str;
// here you can mess with the stream data either with $result or $str.
// i.e. look for the "Job waiting" string and terminate the response.
return strlen($str);//don't touch this
};
If not interrupted at the end $result will contain all the response from remote site.
So combining everything will look something like:
$result = '';
$callback = function ($ch, $str) {
global $result;
//$str has the chunks of data streamed back.
$result .= $str;
// here you can mess with the stream data either with $result or $str.
// i.e. look for the "Job waiting" string and terminate the response.
return strlen($str);//don't touch this
};
$url = "partial_response.php";
$sac_curl = curl_init();
curl_setopt($sac_curl, CURLOPT_HTTPGET, true);
curl_setopt($sac_curl, CURLOPT_URL, $url);
curl_setopt($sac_curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($sac_curl, CURLOPT_HEADER, false);
curl_setopt($sac_curl, CURLOPT_TIMEOUT, 11);
curl_setopt($ch, CURLOPT_WRITEFUNCTION, $callback);
curl_exec($sac_curl); // the response is now in $result.
curl_close($sac_curl);
echo $result;