PHP getting JSON data not working - php

Does anyone know how I can get the data from the JSON data
{
"data":{
"verify-purchase":{
"item_name":"Simplified PHP Invoice \/ Billing System",
"item_id":"11438884",
"created_at":"Sun May 31 07:49:31 +1000 2015",
"buyer":"aurysilva",
"licence":"Regular License"
}
},
"code":200,
"msg":"SUCCESS. Simplified PHP Invoice \/ Billing System License Activated. Purchase date: Sun May 31 07:49:31 +1000 2015"
}
If I do:
<?php
$LE = new License_Enforcer( 'http://www.rebootdigital.co.uk/verify.php');
$username = LICENSE_USERNAME;
$purchase_code = LICENSE_KEY;
$verified = $LE->verify($username, $purchase_code);
// save the result
$license_verified = $verified;
//$class = $LE->return_code >= 200 ? 'update' : 'error';
//echo sprintf("<div id='message' class='%s'><p>%s</p></div>", $class, $LE->msg);
echo $LE->msg;
echo $LE->data->item_name;
?>
$LE->msg returns the msg data, but I am not sure how to get the actual data.
JSON code:
// Make curl request
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (iPhone Simulator; U; CPU iPhone OS 4_3_2 like Mac OD X; en-us) AppleWebKit/535.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5");
$url = 'http://marketplace.envato.com/api/edge/'.$envato_author_username.'/'.$envato_author_apikey.'/verify-purchase:'.$envato_purchase_code.'.json';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$ch_data = curl_exec($ch);
curl_close($ch);
if ( empty( $ch_data ) ) { # no data returned - Timeout or similar
$result['code'] = 111;
$result['msg'] = 'FAILED to Activate License. Envato API request returned: ' . curl_error( $ch ) . " Please try again later.";
}
else {
$json_data = json_decode( $ch_data, true );
$result['data'] = $json_data;
if ( isset( $json_data['verify-purchase'] ) && count( $json_data['verify-purchase']) > 0 ) {
$license_type = $json_data['verify-purchase']['licence'];
$item_name = $json_data['verify-purchase']['item_name'];
$item_id = $json_data['verify-purchase']['item_id'];
$buyer = $json_data['verify-purchase']['buyer'];
$created_at = $json_data['verify-purchase']['created_at'];
if ( strcasecmp( $envato_username, $buyer ) === 0 ) {
$result['code'] = 200;
$result['msg'] = "SUCCESS. " . $item_name . " License Activated. Purchase date: " . $created_at;
}
else {
$result['code'] = 122;
$result['msg'] = "FAILED to Activate License for " . $item_name . ". Envato states this purchase code is owned by another user.";
}
} else if ( $json_data['error'] ) {
$result['code'] = 112;
$result['msg'] = 'FAILED to Activate License. Envato API request returned: ' . $json_data['error'];
} else {
$result['code'] = 121;
$result['msg'] = 'FAILED to Activate License. Envato states purchase code ' . $envato_purchase_code . ' is not valid.';
}
$result = str_replace('verify-purchase','verify_purchase',$data);
}
}
echo json_encode( $result );
echo "\n";
// update log file
$logfile = dirname(__FILE__) . '/' . basename(__FILE__, '.php') . '.log';
$fh = #fopen( $logfile ,"a" );
if ($fh) {
fwrite( $fh, date( 'Y-m-d H:i:s',time() ) . ' ');
fwrite( $fh, $envato_username . ' ' );
fwrite( $fh, $envato_purchase_code . ' ' );
fwrite( $fh, $website . ' ');
fwrite( $fh, isset( $item_name ) ? '"' . $item_name . '"' : '-' );
fwrite( $fh, ' ==> ' );
fwrite( $fh, $result['code'] . ' ' );
fwrite( $fh, '"' . $result['msg'] . '" ');
fwrite( $fh, "\n" );
fclose($fh);
}
?>

anant's anwer is missing quotes around the property name 'verify-purchase'. Try it again with quotes:
echo $LE->data->{'verify-purchase'}->item_name;

Related

Change proxy service on php file

I have this code that I need to edit by replacing PhantomJsCloud services with brightdata service
function ms_getUrl($url){
$json = urlencode('{url:"' . $url . '",renderType:"plainText",outputAsJson:true}');
$res = getUrl('https://PhantomJsCloud.com/api/browser/v2/ak-4sr84-tyab5-0iyd6-d9w6h-6pw35/?request=' . $json);
$res = json_decode('[' . $res . ']' , 1);
$res = $res[0]['pageResponses'][0]['frameData']['content'];
return $res;
echo '<pre>' . print_r( json_decode('[' . $res . ']' , 1) , 1 ) . '</pre>';exit;
}
This is brightdata example provided by them
<?php
echo 'To enable your free eval account and get CUSTOMER, YOURZONE and '
.'YOURPASS, please contact sales#brightdata.com';
$curl = curl_init('http://lumtest.com/myip.json');
curl_setopt($curl, CURLOPT_PROXY, 'http://zproxy.lum-superproxy.io:22225');
curl_setopt($curl, CURLOPT_PROXYUSERPWD, 'brd-customer-hl_2bevke7f-zone-static:0vavfolixyu6q');
curl_exec($curl);
?>
I tried this but it doesn't use brightdata proxies
function ms_getUrl($url){
$json = urlencode('{url:"' . $url . '",renderType:"plainText",outputAsJson:true"}');
$res = getUrl('http://brd-customer-hl_2bjki87f-zone-static:0vavfkjkyu6a#zproxy.lum-superproxy.io:22225' . $json);
$res = json_decode('[' . $res . ']' , 1);
$res = $res[0]['pageResponses'][0]['frameData']['content'];
return $res;
echo '<pre>' . print_r( json_decode('[' . $res . ']' , 1) , 1 ) . '</pre>';exit;
}

curl response content not complete

I am working with api ( using curl and php ) that is supposed to return a batch of csv records based on a date. First, you make a request that returns the number of records that will be in the batch. The second request is to actually retrieve the records. My problem is when I make the second request I do NOT get the number of records that the first request indicates I am to get. Regardless of the date selected I ALWAYS get 7167 records ( the number of records for any particular day will be over 8000 ). The content length I received is what the header states I am to get. I do not get any errors. Here is the rub, if I put the url request in a browser's address bar I get ALL the records I am supposed to get.
The script runs on a linux platform. In fact, I have tried it on another linux server with the same results. I have tried changing execution time and timeout setting. I am really baffled. Thank you in advance for your suggestions.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
set_time_limit(0); // no limit
$username = "*********";
$pwd = "*********";
$urlCount = "https://*********&fromDate=". $today . "&toDate=" . $tomorrow";
$TotalPages = 0;
$CurrentPage = 0;
$PageSize = 1;
$RecordCount = 0;
$TotalRecordsProcessed = 0;
$today = date( "Y-m-d" );
$tomorrow = date( 'Y-m-d', strtotime( "+1 days" ) );
echo "today " . $today . "<br>";
echo "tomorrow: " . $tomorrow . "<br>";
$urlCount = "https://*********&fromDate=". $today . "&toDate=" . $tomorrow;
$headers = array("Content-Type:text/plain", 'Connection: Keep-Alive');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $urlCount );// Get the count of the records we asked for
curl_setopt($ch, CURLOPT_HEADER, true );
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true );
curl_setopt($ch, CURLOPT_TIMEOUT, 6000);
curl_setopt($ch, CURLOPT_VERBOSE, true );
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $pwd );
$result = curl_exec( $ch ); // execute the curl function
$lines = explode( "\r\n", $result );
$idx = 0;
while( $lines[ $idx ] != null ) $idx++; // find the empty line
$RecordCount = $lines[ $idx + 1 ]; // This is the index to the number of records in the set
$PageSize = $RecordCount;
echo "Records in set: " . $RecordCount . "<br>";
$url = "https://***********&fromDate=2015-10-19&toDate=2015-10-20&pageSize=" . $PageSize . "&pageNumber=" . $CurrentPage . "&timezone=Eastern&outputType=csv";
curl_setopt($ch, CURLOPT_URL, $url ); // set the url for getting the records
$result = curl_exec( $ch ); // execute the function
$info = curl_getinfo($ch);
curl_close( $ch );
$size_download = $info["size_download"];
echo "Http Code: " . $info['http_code'] . "<br>";
echo "Size download: " . $info["size_download"] . "<br>";
// Make sure the length of the content received is the same as the "size_download" from the http header
$pos = strpos( $result, "UUID" ) - 2; // find the begining of the content
$result = substr( $result , $pos, -1 ); // remove the header data...keep just the content
$len = strlen( $result ); // get the length of the received content
if( $len != $size_download )
{
echo "length:" . strlen( $result ) . "<br>";
echo "Content recieved not = size_download<br>";
}
// Check to make sure records downloaded match the number of records that the first curl request says there are
// Records are in csv format
$lines = explode( "\r\n", $result );
$RecordsReceived = count( $lines );
if( $RecordsReceived != $RecordCount )
{
echo "Record Count = " . $RecordCount . " RecordsReceived = " . $RecordsReceived . "<br>";
}
?>

CSV not generated in php

We are trying to generate a CSV file using PHP. But its not generating. We gave 777 permission to the folder and gave hard coded path in header. but its not generating.
Can any body tell me whats i am doing wrong?
if ($ext === 'csv') {
if (($handle = fopen($tmpName, 'r')) !== FALSE) {
// necessary if a large csv file
set_time_limit(0);
$row = 1;
$file = fopen('ids.txt', 'w');
$num_records =count(file($tmpName));
// $calc = 100/$num_records;
$calc=100/ $num_records;
echo "Total ".$num_records." records found.<br/>";
$p = new ProgressBar();
$output = fopen("php://output",'w') or die("Can't open php://output");
header("Content-Type:application/csv");
header("Content-Disposition:attachment;filename=pressurecsv.csv");
while ((($data = fgetcsv($handle, 1000, ',')) !== FALSE) && $row != 30) {
// number of fields in the csv
$address = implode(",", $data);
$p->setProgressBarProgress($x);
usleep(1000000*0.1);
$cityclean = str_replace(" ", "+", $address);
$details_url = "https://maps.googleapis.com/maps/api/geocode/json?address=" . $cityclean . "&sensor=false&key=".$api_array[$api_key_status];
// echo $details_url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $details_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$geoloc = json_decode(curl_exec($ch), true);
// print_r($geoloc);
if ( $geoloc['status'] === "OVER_QUERY_LIMIT" )
{
echo "OVER QUERY LIMIT. Using another key.";
$api_key_status++;
}
//print_r(address_reformat($geoloc['results'][0]));
//convert_to_csv(address_reformat($geoloc['results'][0]), 'report.csv', ',');
$address_tmp=address_reformat($geoloc['results'][0]);
if(isset($geoloc['results'][0]['geometry']['location']['lat']))
// foreach($address_tmp as $product)
{
//print_r($address_tmp);
fputcsv($output, $address_tmp);
}
$lat = $geoloc['results'][0]['geometry']['location']['lat'];
$lng = $geoloc['results'][0]['geometry']['location']['lng'];
// echo $address . "------Latitude: " . $lat . " ---- Longitude: " . $lng;
fwrite($file, $address . "; " . $lat . " ; " . $lng . "\n");
// echo $row." address coordinate fetched.";
$p->getContent();
// echo $address;
echo "<br/>";
// echo $details_url;
$x += $calc;
//$x++;
$row++;
}
$p->setProgressBarProgress(100);
fclose($file);
fclose($handle);
fclose($output) or die("Can't close php://output");
echo "\n To download generated file <a href='ids.txt'>Click Here</a> . \n";
echo " <iframe src='data.php' height='100%' width='100%' frameBorder='0'></iframe>";
}
}
}

Write from WordPress plugin to text file with PHP

I am trying to write date to a text file from a WordPress plugin. While this works for a single PHP file it doesn't write when I add the code to the plugin. The TXT file has permission 777 and is in the same directory as the plugin file.
What am I doing wrong?
This is the plugin and the lines I have added are in the block //log 404s to text file:
<?php
/*
Plugin Name: Mail me 404 errors
Plugin URI: http://me.com
Description: A 404 status triggers an email with details.
Version: 1.0
Author: Me
Author URI: http://me.com
*/
//SENDS 404 EMAIL TO ADMIN
function email_admin($location){
// ip address
$ipaddress = $_SERVER['REMOTE_ADDR'];
if (!empty($_SERVER['X_FORWARDED_FOR'])) {
$X_FORWARDED_FOR = explode(',', $_SERVER['X_FORWARDED_FOR']);
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$X_FORWARDED_FOR = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
}
else {$ipaddress = "undefined";}
if (!empty($X_FORWARDED_FOR)) {
$ipaddress = trim($X_FORWARDED_FOR[0]);
}
// site info
$blname=get_option('blogname');
$admemail = get_option('admin_email');
$honeypot = "http://www.projecthoneypot.org/ip_".$ipaddress;
// time log
$time = date("F jS Y, H:i", time()+25200);
//referrer
function current_page_url(){
$page_url = 'http';
if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'){
$page_url .= 's';
}
return $page_url.'://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
}
if(isset($_SESSION['referrer'])){
$referrer = $_SESSION['referrer'];
} elseif(isset($_SERVER['HTTP_REFERER'])){
$referrer = $_SERVER['HTTP_REFERER'];
} else {$referrer = "undefined";}
$_SESSION['referrer'] = current_page_url();
// query string
if (isset($_SERVER['QUERY_STRING'])) {
$string = $_SERVER['QUERY_STRING'];
} else {
$string = "undefined";
}
// request URI
if (isset($_SERVER['REQUEST_URI']) && isset($_SERVER["HTTP_HOST"])) {
$request = 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
} else {
$request = "undefined";
}
// identity
if (isset($_SERVER['REMOTE_IDENT'])) {
$remote = $_SERVER['REMOTE_IDENT'];
} else {
$remote = "undefined";
}
// user agent
if (isset($_SERVER['HTTP_USER_AGENT'])) {
$agent = $_SERVER['HTTP_USER_AGENT'];
} else {
$agent = "undefined";
}
//log 404s to txt file
$ipad = $_SERVER['REMOTE_ADDR'];
$ban = "#$time\r\n$ipad\r\n";
$file = "errors.txt";
$open = #fopen($file, "a");
$write = #fputs($open, $ban);
#fclose($open);
//log 404s to txt file
$mailhead = "MIME-Version: 1.0\r\n";
$mailhead .= "Content-type: text/plain; charset=UTF-8\r\n";
$mailhead .= 'From: "' . $blname . '" <' .$admemail. ">\r\n";
$mailsubj= $blname.': 404 error';
$mailintro = "Someone wanted to go to ".$request.", but it doesn't exist. Maybe you can have a look and see if anything needs to be fixed.\r\n";
$mailbody=
$mailintro . "\n" .
"TIME: " . $time . "\n" .
"*404: " . $request . "\n" .
"REFERRER: " . $referer . "\n" .
"QUERY STRING: " . $string . "\n" .
"REMOTE ADDRESS: " . $ipaddress . "\n" .
"REMOTE IDENTITY: " . $remote . "\n" .
"USER AGENT: " . $agent . "\n" .
"CHECK WHOIS: https://who.is/whois-ip/ip-address/". $ipaddress . "\n" .
"CHECK IP ADDRESS: " . $honeypot . "\n\n\n";
#mail($admemail,$mailsubj,$mailbody,$mailhead);
}
function mail_me_errors(){
global $wp_query;
$location=$_SERVER['REQUEST_URI'];
if ($wp_query->is_404){
email_admin($location);
}
}
add_action('get_header', 'mail_me_errors');
?>
Pass the full path of the file /wp-content/plugins/your-plugin/errors.txt to fopen with plugin_dir_path():
$file = plugin_dir_path( __FILE__ ) . '/errors.txt';
$open = fopen( $file, "a" );
The following is a minimum example:
add_action( 'get_header', 'mail_me_errors' );
function mail_me_errors() {
if ( is_404() ) {
email_admin( $_SERVER['REQUEST_URI'] );
}
}
function email_admin( $location ) {
$time = date( "F jS Y, H:i", time()+25200 );
$ban = "#$time\r\n$location\r\n";
$file = plugin_dir_path( __FILE__ ) . '/errors.txt';
$open = fopen( $file, "a" );
$write = fputs( $open, $ban );
fclose( $open );
}

Using fgetcsv and fopen issue with looping never exiting

There's an issue with this piece of code it never gets to the "Done" echo.
for($current_day=1;$current_day<=10;$current_day++){
echo("lists/Day ".$current_day.".csv </br>");
$person_data = "";
if ( ( $handle = fopen( "lists/Day ".$current_day.".csv", "r" ) ) !== FALSE ) {
while ( ( $data = fgetcsv( $handle, 1000, ",", "//" ) ) !== FALSE ) {
if ( $data[2]!="Grade" ) {
$collection = $db->students;
$person_data['last_name'] = trim( $data[0] );
$person_data['first_name'] = trim( $data[1] );
$person_data['fullname'] = $person_data['first_name'].' '.$person_data['last_name'];
//var_dump($person_data);
$cursor = $collection->findOne(array('fullname'=>$person_data['first_name'].' '.$person_data['last_name']));
if($cursor!=null){
echo("UPDATE");
if($cursor['frees'][$current_day-1] != 1){
$cursor['frees'][$current_day-1] = 1;
echo 'Updated: '.$data[0] . " - ". $data[1] . " - ". $data[2] . "</br>" ;
$collection->save($cursor);
}
}
else{
echo("ADD");
//addperson($data,$current_day);
}
}
// do something with the data here
//echo $data[0] . " - ". $data[1] . " - ". $data[2] . "</br>" ;
}
fclose( $handle );
echo("Done");
}
else{
echo "FALSE";
}
}
outputs
1
lists/Day 1.csv
ADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADDADD
Which is correct but never loops to the second csv

Categories