PHP newbie CURL and array - arrays

UPDATED: I've simplified the code (tried to)
I'm trying to download a series of images as set in an array, but something is clearly not right:
function savePhoto($remoteImage,$fname) {
$ch = curl_init();
curl_setopt ($ch, CURLOPT_NOBODY, true);
curl_setopt ($ch, CURLOPT_URL, $remoteImage);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 0);
$fileContents = curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($retcode==200) {
$newImg = imagecreatefromstring($fileContents);
imagejpeg($newImg, ".{$fname}.jpg",100);
}
return $retcode;
}
$filesToGet = array('009');
$filesToPrint = array();
foreach ($filesToGet as $file) {
if(savePhoto('http://pimpin.dk/jpeg/'.$file.'.jpg',$file)==200) {
$size = getimagesize(".".$file.".jpg");
echo $size[0] . " * " . $size[1] . "<br />";
}
}
I get the following errors:
Warning: imagecreatefromstring()
[function.imagecreatefromstring]:
Empty string or invalid image in
C:\inetpub\vhosts\dehold.net\httpdocs\ripdw\index.php
on line 15
Warning: imagejpeg(): supplied
argument is not a valid Image resource
in
C:\inetpub\vhosts\dehold.net\httpdocs\ripdw\index.php
on line 16
Warning: getimagesize(.009.jpg)
[function.getimagesize]: failed to
open stream: No such file or directory
in
C:\inetpub\vhosts\dehold.net\httpdocs\ripdw\index.php
on line 26
*

try this instead:
function get_file1($file, $local_path, $newfilename)
{
$err_msg = '';
echo "<br>Attempting message download for $file<br>";
$out = fopen($newfilename, 'wb');
if ($out == FALSE){
print "File not opened<br>";
exit;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_FILE, $out);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $file);
curl_exec($ch);
echo "<br>Error is : ".curl_error ( $ch);
curl_close($ch);
//fclose($handle);
}//end function
// taken from: http://www.weberdev.com/get_example-4009.html
or file_get_contents

You should try file_get_contents in replacement of CURL (simpler but it does the job):
function savePhoto($remoteImage,$fname) {
$fileContents = file_get_contents($remoteImage);
try {
$newImg = imagecreatefromstring($fileContents);
imagejpeg($newImg, ".{$fname}.jpg",100);
} catch (Exception $e) {
//what to do if the url is invalid
}
}

I finally got it to work, with help from you all and a bit of snooping around :-)
I ended up using CURL:
function savePhoto($remoteImage,$fname) {
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $remoteImage);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 0);
$fileContents = curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($retcode == 200) {
$newImg = imagecreatefromstring($fileContents);
imagejpeg($newImg, $fname.".jpg",100);
}
return $retcode;
}
$website = "http://www.pimpin.dk/jpeg";
$filesToGet = array('009');
$filesToPrint = array();
foreach ($filesToGet as $file) {
if(savePhoto("$website/$file.jpg",$file)==200) {
$size = getimagesize($file.".jpg");
echo $size[0] . " * " . $size[1] . "<br />";
} else {
echo "File wasn't found";
}
}

Related

Display Progress message after calling api url

we select checbox & onclick button "Show Status" , I am calling external webservice api url & updating the "status" column [4th in below image] values in Database.....
once we got success response we are displaying alert message....
Requirement :
but now i want to display Progress like "1% completed , 2 % completed" , so on.... :
status page
<button type= "button" id="show_status" >Show Status</button>
script
$('#show_status').click(function()
{
var selected = [];
$('.assigneeid-order:checked').each(function()
{
selected.push($(this).val());
$('.assigneeid-order').prop('checked', false);
});
var jsonString = JSON.stringify(selected);
$.ajax
({
type: "POST",
url: "api.php",
data: {data : jsonString},
success: function(response)
{
response = $.parseJSON(response);
alert("completed");
$.each(response, function(index, val)
{
$("#"+index+"").html(val);
$("#"+index+"").html(val.status);
});
}
});
});
api.php
<?php
$data = json_decode(stripslashes($_POST['data']));
$response = array();
foreach($data as $id){
$post_data['username']='a';
$url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/';
$ch = curl_init();
curl_close($ch);
$orderResults=$xml=simplexml_load_string($output);
//print_r($orderResults); die;
foreach($orderResults->object as $child)
{
$status=(string)$child->field[10];
break;
}
$statusfinal = str_replace('<field type="CharField" name="status">','',$status);
if($statusfinal!='')
{
$sqlecom = "UPDATE do_order set in_transit='".$status."' where tracking_id=".$orderid;
//echo $sqlecom;
$db_handleecom = new DBController();
$resultecom = $db_handleecom->executeUpdate($sqlecom);
}
$response[$orderid] = [ 'status' => $status ];
}
echo json_encode($response);
?>
Please try this script and code
$('#show_status').click(function()
{
var selected = [];
$('.assigneeid-order:checked').each(function(){
selected.push($(this).val());
$('.assigneeid-order').prop('checked', false);
});
var count = selected.length
var perPlush = 100/count;
var per = 0;
for (var i = 0; i <= count; i++) {
$.ajax
({
type: "POST",
url: "api.php",
data: {id : selected[i]},
success: function(response)
{
response = $.parseJSON(response);
$.each(response, function(index, val)
{
$("#"+index+"").html(val);
$("#"+index+"").html(val.status);
});
per = per + perPlush;
console.log(Math.round(per) + " % Complated");
$("#progress").html(Math.round(per) + " % Complated");
}
});
}
});
Your api.php file
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ALL & ~MYSQLI_REPORT_INDEX);
require_once("dbcontroller.php");
$db_handle = new DBController();
$id = $_POST['id']; //960856092
$response = array();
$orderid = $id;
$hide = '';
$post_data['awb']=$orderid;
$url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, "http://plapi.ecomexpress.in/track_me/api/mawbd/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
$output = curl_exec ($ch);
curl_close($ch);
$orderResults=$xml=simplexml_load_string($output);
if($orderResults){
foreach($orderResults->object as $child)
{
$status=(string)$child->field[10];
break;
}
$statusfinal = str_replace('<field type="CharField" name="status">','',$status);
if($statusfinal!='')
{
$sqlecom = "UPDATE do_order set in_transit='".$status."' where tracking_id=".$orderid;
//echo $sqlecom;
$db_handleecom = new DBController();
$resultecom = $db_handleecom->executeUpdate($sqlecom);
}
$response[$orderid] = [ 'status' => $status ];
}
else{
$response[$orderid] = ['status' => 'Order already placed'];
}
echo json_encode($response);
?>

file_get_contents gives error in codeigniter

$scope.formatfilename = response.fileformat[0].FileName;
// it contains filename = abcd
$filename1 ='{{formatfilename}}'; // now I have taken into phpvariable
$siteaddr = "http://localhost:8080/demoproject/document/".$filename1.".html";
echo file_get_contents($siteaddressAPI);
it gives me Failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
if I assign full url static to $siteaddressAPI then it gives the result.
how to solve in codeigniter ??
Option 1:
change in php.ini
allow_url_fopen = On
Option 2: use cURL
You might want to try using curl to retrieve the data instead of file_get_contents. curl has better support for error handling:
$filename1 ='{{formatfilename}}'; // now I have taken into phpvariable
$siteaddr = "http://localhost:8080/demoproject/document/".$filename1.".html";
// make request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $siteaddr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
// convert response
$output = json_decode($output);
// handle error; error output
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {
var_dump($output);
}
curl_close($ch);
Working Example
<?php
$siteaddr = "https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_API_KEY";
// make request
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL, $siteaddr);
// Execute
$output = curl_exec($ch);
// convert response
$output = json_decode($output);
// handle error; error output
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {
var_dump($output);
}
curl_close($ch);
echo "<pre>", print_r($output), "</pre>";
die();
?>
Output
stdClass Object
(
[error_message] => The provided API key is invalid.
[results] => Array
(
)
[status] => REQUEST_DENIED
)

CakePHP push notifications are repeating?

I'm trying send push notifications with CakePHP. The notifications are send but the problem is that all notifications are repeating. I cant understand why this problem.
I have a table to add devices of GCM (Google Cloud Messaging). After save the Model I do a SELECT in this table to get all devide_id of GCM saved and send the push notifications. The field device_id is unique in table. After to select I do a foreach to get devices and send the notifications, but this always repeating and send a lot of push to the same device_id.
How could I solve it ?
Push Notification Class
<?php
class Pusher{
const GOOGLE_GCM_URL = 'https://android.googleapis.com/gcm/send';
private $apiKey;
private $proxy;
private $output;
public function __construct($apiKey, $proxy = null)
{
$this->apiKey = $apiKey;
$this->proxy = $proxy;
}
/**
* #param string|array $regIds
* #param string $data
* #throws \Exception
*/
public function notify($regIds, $data)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::GOOGLE_GCM_URL);
if (!is_null($this->proxy)) {
curl_setopt($ch, CURLOPT_PROXY, $this->proxy);
}
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->getHeaders());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->getPostFields($regIds, $data));
$result = curl_exec($ch);
if ($result === false) {
throw new \Exception(curl_error($ch));
}
curl_close($ch);
$this->output = $result;
}
/**
* #return array
*/
public function getOutputAsArray()
{
return json_decode($this->output, true);
}
/**
* #return object
*/
public function getOutputAsObject()
{
return json_decode($this->output);
}
private function getHeaders(){
return [
'Authorization: key=' . $this->apiKey,
'Content-Type: application/json'
];
}
private function getPostFields($regIds, $data){
$fields = [
'registration_ids' => is_string($regIds) ? [$regIds] : $regIds,
'data' => is_string($data) ? ['message' => $data] : $data,
];
return json_encode($fields, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);
}
}
Controller
<?php
App::uses('AppController', 'Controller');
App::uses('Pusher', 'Plugin/Push');
class NoticiasController extends AppController {
public function add() {
if ($this->request->is('post')) {
$this->Noticia->create();
if($this->Noticia->save($this->request->data)){
$this->Session->setFlash(__("Save ok!"));
$this->sendPush();
return $this->redirect(array('action' => 'index'));
}else{
$this->Session->setFlash(__("Not save :("));
}
}
}
/***************** push notifications ****************/
private function sendPush(){
$apiKey = "AIzaSyCMZ6roIEpHsj5P8cgErgceerljerhaljh";
//msg de push
$message = array("title"=>"Title",
"message"=>"Post a news",
"tickerText"=>"Post a news",
"url"=>"News");
$this->loadModel('Device');
$devices = $this->Device->query("SELECT device_id, status FROM devices Device WHERE status = 1");
$pusher = new Pusher($apiKey);
foreach ($devices as $device){
$pusher->notify($device["Device"]["device_id"], $message);
}
}
}

Paypal DoCapture batch process loop

I am trying to implement a batch process for the doCapture API from paypal. I have the code below and it only processes the first record of the database...Help!!
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
<?php
include("xxxxx.php");<---- this is just the database connection
$query2="SELECT *
FROM x where payment_status = 'Pending'";
// WHERE custom IN (
// SELECT custom
// FROM x
// GROUP BY custom
// HAVING count(custom) > 1
// )
//ORDER BY custom";
$results=mysql_query($query2);
$row2 = mysql_fetch_array($results);
$row_count=mysql_num_rows($results);
echo $row_count;
//$auth=$row2['auth_id'];
//while($row2 =mysql_fetch_array($results)){
$arrSize=sizeof($row_count);
for ($number = 0; $number < $arrSize; $number++) {
//for($i=0; $i<$row_count; $i++){
echo $row2['auth_id']; // prints hello
//echo $row2['auth_id'];
/** DoCapture NVP example; last modified 08MAY23.
*
* Capture a payment.
*/
$environment = 'sandbox'; // or 'beta-sandbox' or 'live'
/**
* Send HTTP POST Request
*
* #param string The API method name
* #param string The POST Message fields in &name=value pair format
* #return array Parsed HTTP Response body
*/
function PPHttpPost($methodName_, $nvpStr_) {
//for($i=0; $i<$row_count; $i++){
global $environment;
// Set up your API credentials, PayPal end point, and API version.
$API_UserName = urlencode('');
$API_Password = urlencode('');
$API_Signature = urlencode('.');
$API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
if("sandbox" === $environment || "beta-sandbox" === $environment) {
$API_Endpoint = "https://api-3t.$environment.paypal.com/nvp";
}
$version = urlencode('51.0');
// Set the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// Turn off the server and peer verification (TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
// Set the API operation, version, and API signature in the request.
$nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";
// Set the request as a POST FIELD for curl.
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
// Get response from the server.
$httpResponse = curl_exec($ch);
if(!$httpResponse) {
exit("$methodName_ failed: ".curl_error($ch).'('.curl_errno($ch).')');
}
// Extract the response details.
$httpResponseAr = explode("&", $httpResponse);
$httpParsedResponseAr = array();
foreach ($httpResponseAr as $i => $value) {
$tmpAr = explode("=", $value);
if(sizeof($tmpAr) > 1) {
$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
}
}
if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
}
return $httpParsedResponseAr;
}
// Set request-specific fields.
$authorizationID = urlencode($row2['auth_id']);
$amount = urlencode('1.99');
$currency = urlencode('USD'); // or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
$completeCodeType = urlencode('Complete'); // or 'NotComplete'
$invoiceID = urlencode('example_invoice_id');
$note = urlencode('example_note');
// Add request-specific fields to the request string.
$nvpStr="&AUTHORIZATIONID=$authorizationID&AMT=$amount&COMPLETETYPE=$completeCodeType&CURRENCYCODE=$currency&NOTE=$note";
// Execute the API operation; see the PPHttpPost function above.
$httpParsedResponseAr = PPHttpPost('DoCapture', $nvpStr);
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
exit('Capture Completed Successfully: '.print_r($httpParsedResponseAr, true));
} else {
exit('DoCapture failed: ' . print_r($httpParsedResponseAr, true));
//}
}}
//}
?>
You're only fetching one row out of the database, because your $row2 = mysql_fetch_array($results); line is outside of your for loop. Essentially, you're trying to capture the same payment over and over again, and I'm willing to bet that only the first one is succeeding. Move the fetch statement to just inside the for loop.

How to parse the data from Google Alerts?

Firstly, How would you get Google Alerts information into a database other than to parse the text of the email message that Google sends you?
It seems that there is no Google Alerts API.
If you must parse text, how would you go about parsing out the relevant pieces of the email message?
When you create the alert, set the "Deliver To" to "Feed" and then you can consume the feed XML as you would any other feed. This is much easier to parse and digest into a database.
class googleAlerts{
public function createAlert($alert){
$USERNAME = 'XXXXXX#gmail.com';
$PASSWORD = 'YYYYYY';
$COOKIEFILE = 'cookies.txt';
$ch = curl_init();
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, $COOKIEFILE);
curl_setopt($ch, CURLOPT_COOKIEFILE, $COOKIEFILE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_URL,
'https://accounts.google.com/ServiceLogin?hl=en&service=alerts&continue=http://www.google.com/alerts/manage');
$data = curl_exec($ch);
$formFields = $this->getFormFields($data);
$formFields['Email'] = $USERNAME;
$formFields['Passwd'] = $PASSWORD;
unset($formFields['PersistentCookie']);
$post_string = '';
foreach($formFields as $key => $value) {
$post_string .= $key . '=' . urlencode($value) . '&';
}
$post_string = substr($post_string, 0, -1);
curl_setopt($ch, CURLOPT_URL, 'https://accounts.google.com/ServiceLoginAuth');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
$result = curl_exec($ch);
if (strpos($result, '<title>') === false) {
return false;
} else {
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/alerts');
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, null);
$result = curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/alerts/create');
curl_setopt($ch, CURLOPT_POST, 0);
$result = curl_exec($ch);
//var_dump($result);
$result = $this->getFormFieldsCreate($result);
$result['q'] = $alert;
$result['t'] = '7';
$result['f'] = '1';
$result['l'] = '0';
$result['e'] = 'feed';
unset($result['PersistentCookie']);
$post_string = '';
foreach($result as $key => $value) {
$post_string .= $key . '=' . urlencode($value) . '&';
}
$post_string = substr($post_string, 0, -1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
$result = curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/alerts/manage');
$result = curl_exec($ch);
if (preg_match_all('%'.$alert.'(?=</a>).*?<a href=[\'"]http://www.google.com/alerts/feeds/([^\'"]+)%i', $result, $matches)) {
return ('http://www.google.com/alerts/feeds/'.$matches[1][0]);
} else {
return false;
}
}
}
private function getFormFields($data)
{
if (preg_match('/(<form.*?id=.?gaia_loginform.*?<\/form>)/is', $data, $matches)) {
$inputs = $this->getInputs($matches[1]);
return $inputs;
} else {
die('didnt find login form');
}
}
private function getFormFieldsCreate($data)
{
if (preg_match('/(<form.*?name=.?.*?<\/form>)/is', $data, $matches)) {
$inputs = $this->getInputs($matches[1]);
return $inputs;
} else {
die('didnt find login form1');
}
}
private function getInputs($form)
{
$inputs = array();
$elements = preg_match_all('/(<input[^>]+>)/is', $form, $matches);
if ($elements > 0) {
for($i = 0; $i < $elements; $i++) {
$el = preg_replace('/\s{2,}/', ' ', $matches[1][$i]);
if (preg_match('/name=(?:["\'])?([^"\'\s]*)/i', $el, $name)) {
$name = $name[1];
$value = '';
if (preg_match('/value=(?:["\'])?([^"\'\s]*)/i', $el, $value)) {
$value = $value[1];
}
$inputs[$name] = $value;
}
}
}
return $inputs;
}
}
$alert = new googleAlerts;
echo $alert->createAlert('YOUR ALERT');
It will return link to rss feed of your newly created alert
I found a Google Alerts API here. It's pretty minimal and I haven't tested it.

Resources