Can be found there many resources on Internet with the same code and instructions about how to show your MailChimp subscriber count in WordPress. I used that code without problems until today, when received an PHP Warning:
PHP Warning: Missing argument 2 for Mailchimp::call(), called in
/.../mc-subscriber-count/mc-subscriber-count.php on line 19 and
defined in /.../mc-subscriber-count/Mailchimp.php on line 192
The mc-subscriber-count.php full code:
function wpb_mc_sub_count() {
include "Mailchimp.php";
$lastRunLog = __DIR__ . '/logs/lastrun.log';
$subfile = __DIR__ . '/logs/subcount.log';
$lastRun = file_get_contents( $lastRunLog );
if ( time() - $lastRun >= 86400 ) {
$MailChimp = new MailChimp( 'Your_MailChimp_API_Key' );
$mc = $MailChimp->call( 'lists/list' ); // THE LINE 19
/*****************************************************/
$subscriber_count .= $mc[data][0][stats][member_count];
file_put_contents( $lastRunLog, time() );
file_put_contents( $subfile, $subscriber_count );
} else {
$subscriber_count .= file_get_contents( $subfile );
}
return number_format( $subscriber_count );
}
add_shortcode( 'mc-subscribers', 'wpb_mc_sub_count' );
add_filter( 'widget_text', 'do_shortcode' );
The Mailchimp.php code (only the function from the line 192 - full code here):
public function call($url, $params) {
$params['apikey'] = $this->apikey;
$params = json_encode($params);
$ch = $this->ch;
curl_setopt($ch, CURLOPT_URL, $this->root . $url . '.json');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_VERBOSE, $this->debug);
$start = microtime(true);
$this->log('Call to ' . $this->root . $url . '.json: ' . $params);
if($this->debug) {
$curl_buffer = fopen('php://memory', 'w+');
curl_setopt($ch, CURLOPT_STDERR, $curl_buffer);
}
$response_body = curl_exec($ch);
$info = curl_getinfo($ch);
$time = microtime(true) - $start;
if($this->debug) {
rewind($curl_buffer);
$this->log(stream_get_contents($curl_buffer));
fclose($curl_buffer);
}
$this->log('Completed in ' . number_format($time * 1000, 2) . 'ms');
$this->log('Got response: ' . $response_body);
if(curl_error($ch)) {
throw new Mailchimp_HttpError("API call to $url failed: " . curl_error($ch));
}
$result = json_decode($response_body, true);
if(floor($info['http_code'] / 100) >= 4) {
throw $this->castError($result);
}
return $result;
}
How to solve that warning?
UPDATE
I forgot to mention that I see that there is missing a second argument, but I don't understand what this second argument can be.
P.S. I am not a PHP coder, so don't beat me.
After the received comments I analysed repeatedly the above two functions and decided to add as a second parameter to the line 19 the `$params` variable, so it looks now like this:
$mc = $MailChimp->call( 'lists/list', $params );
I don't know if this is the correct way, but I will wait now for errors, if will be some there.
UPDATE
Because I received here only downvotes instead of help (but it doesn't matter) and my first solution doesn't worked (see the deleted text), I googled again and finally I found a better one (I hope) to display the MailChimp subscribers count in Wordpress. I just wrapped the recommended code in a shortcode like this:
function wpb_mc_sub_count() {
$api['key']= 'INSERT-YOUR-API-KEY-HERE';
$url='https://INSERT-YOUR-US-DOMAIN-KEY.api.mailchimp.com/3.0//lists/INSERT-YOUR-LISTID-HERE/?apikey=INSERT-YOUR-API-KEY-HERE';
$lastRunLog = '/logs/lastrun.log';
$subfile = '/logs/subcount.log';
$lastRun = file_get_contents($lastRunLog);
if (time() - $lastRun >= 3600) {
// it's been more than one hour so we will connect to the API
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
$json = json_decode($result, true);
$total= $json['stats']['member_count'];
// update lastrun.log with current time
file_put_contents($lastRunLog, time());
file_put_contents($subfile, $total);
} else {
$total = file_get_contents($subfile);
}
//echo $total;
return $total;
}
add_shortcode( 'mc-subscribers', 'wpb_mc_sub_count' );
//add_filter( 'widget_text', 'do_shortcode' );
Just put the [mc-subscribers] shortcode where you want to display your MailChimp subscribers count.
Related
Currently i can fetch as per shopify's API limit of 250 products per call and echo this out. I have done some research and found that i need to paginate the request on the overall count of products [5000 products / 250 products per page = 20 pages] in the store.
I want get all products in shopify
so I tried to solved.
but i can not get all products.
the result is always 'error.....'.what is problem?
$pages = ceil($products_cnt->count/250); // Count products / 250
for($i = 0; $i < $pages; $i++){
$api_url = 'https://apikey:password#store.myshopify.com';
$get_url = $api_url . '/admin/products.json?limit=250&page='.($i+1);
$products_content = #file_get_contents( $get_url );
if (!empty($products_all)) {
print_r('ok');
} else {
print_r('error.....');
}
$products_json = json_decode( $products_content, true );
$products = $products_json['products'];
I guess you have a problem with Shopify API rate limit. But to be sure of this need to check the response from the Shopify API. For the HTTP request better to use the curl or some HTTP client package for example the Guzzle.
Try instead of the #file_get_contents($get_url) use this code:
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 30);
$products_content = curl_exec($ch);
if(curl_errno($ch)){
print_r('Curl error.' . curl_error($ch));
}
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if(in_array($status_code, [200, 201])){
print_r('ok');
} else {
print_r(
'Shopify API error. ' .
'HTTP Code: ' . curl_getinfo($ch, CURLINFO_HTTP_CODE) . '; '
'Error: ' . $products_content
);
}
curl_close($ch);
The Pagination method you are trying to use has been deprecated. Shopify introduced new cursor based pagination from API version 2019-07. To read more about Cursor based pagination, head over to Shopify Docs for Cursor based Pagination. It is better if you use some PHP library that offers rate limiting and other things. However, a sample implementation using cURL would look something like below. Check code comments for details.
<?php
// username and password for API
$username = "";
$password = "";
$nextPage = NULL;
$curl = curl_init();
// set result limit and Basic auth
curl_setopt_array(
$curl,
array(
CURLOPT_URL => "https://store-name.myshopify.com/admin/api/2020-07/products.json?limit=50",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_USERPWD => $username . ":" . $password
)
);
// call back function to parse Headers and get Next Page Link
curl_setopt(
$curl,
CURLOPT_HEADERFUNCTION,
function($curl, $header) use (&$nextPage) {
$len = strlen($header);
$header = explode(':', $header, 2);
if (count($header) < 2) // ignore invalid headers
return $len;
if (trim($header[0]) === "Link" && strpos($header[1], 'next') !== false) {
$links = explode(',', $header[1], 2);
$link = count($links) === 2 ? $links[1] : $links[0];
if (preg_match('/<(.*?)>/', $link, $match) === 1) $nextPage = $match[1];
}
return $len;
}
);
// First request
$response = curl_exec($curl);
if (curl_errno($curl)) {
$error_msg = curl_error($curl);
print_r($error_msg);
}
$parsedResponse = json_decode($response);
$result = $parsedResponse->products;
// generate new requests till next page is available
while ($nextPage !== NULL) {
curl_setopt($curl, CURLOPT_URL, $nextPage);
$parsedResponse->products = [];
$nextPage = NULL;
$response = curl_exec($curl);
$parsedResponse = json_decode($response);
if (curl_errno($curl)) {
$error_msg = curl_error($curl);
} else {
$result = array_merge($result, $parsedResponse->products);
sleep(2);
}
};
echo "Products Count: ";
echo count($result);
curl_close($curl);
Response Headers parsing function by Geoffrey
here i am trying to fetch all issues from Redmine by using curl php below is the code which i used.
my CURL.php:
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
?>
here is my example.php
<?php
function get_redmine($methodName='',$data=''){
global $redmine_url , $redmine_key;
$redmine_url = 'http://192.168.12.231:80/';
$redmine_key = 'API KEY';
include_once('curlcall.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;
##Project
case 'projectAll' : return $obj_redmine->get_projects(); #used
break;
case 'projectById' : return $obj_redmine->get_projects($data['project_id']);
break;
##Issues
case 'issueAll' : return $obj_redmine->get_issue();
break;
case 'issueByProjectId' : return $obj_redmine->get_issue('',$data['project_id']);
break;
case 'uploadFileToIssue' : return $obj_redmine->get_upload_token($data);
break;
default: return 0;
}
}
#get all issue
$res = get_redmine('issueAll');
echo '<pre>';print_r($res);
?>
This code is giving only 25 records.at the end of my output it is saying like
total:201
offset:0
limit:25
I can't understand how to get all issues please help anybody, i am new for php.
the answer is all in the API docs, if you'd just bother to read it. use the limit parameter to get more results, and the offset parameter to load more
/issues.json?offset=0&limit=100 would fetch the first 100 issues
/issues.json?offset=100&limit=100 would fetch the next 100 issues, and so on.
... but the first thing you should do is get your code formatted, because that unformatted thing is very annoying to read. then get rid of this line 'Content-Length: ' . strlen ( $post_data ) because curl will add that header automatically if you don't, and curl won't make any typos, nor will it calculate the length incorrectly, unlike us the progammers (curl has automated tests ran on every commit to make sure content-length is correct, i bet that's not part of your test suite), then get rid of this
if (! isset ( $request ['content_type'] )) {
$request ['content_type'] = null;
}
because it should never be null. for future reference, if you literally have no idea what it's supposed to be, set it to application/octet-stream, but even that is wrong in this case, because the API docs says the only supported POST encodings are application/json and application/xml, so the correct thing to do here would be:
if (isset ( $request ['content_type'] ) && $request ['content_type'] !== 'application/json' && $request ['content_type'] !== 'application/xml') {
throw new \InvalidArgumentException ( 'invalid content-type specified. supported types are "application/json" and "application/xml"' );
}
if($request ['type'] === 'post' && !isset($request ['content_type'])){
throw new \LogicException('no content-type was specified for this POST request, which is required. supported types are "application/json" and "application/xml"');
}
as for fetching all the issues, make a request first to see how many issues there are, then make a second request with limit=number_of_issues, like this
if (! $issue_id) {
// first we check how many issues there are (OPTIMIZEME: there is probably a more efficient way to do this, for example limit=0 ?)
$issues_url .= '&limit=1';
$number_of_issues = $this->curl_redmine ( $issue_url, '', '' ) ['total_count'];
$issue_url = substr ( $issues_url, 0, - 1 ) . $number_of_issues;
}
putting it all together, and you get this
<?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;
}
if (! $issue_id) {
// first we check how many issues there are (OPTIMIZEME: there is probably a more efficient way to do this, for example limit=0 ?)
$issues_url .= '&limit=1';
$number_of_issues = $this->curl_redmine ( $issue_url, '', '' ) ['total_count'];
$issue_url = substr ( $issues_url, 0, - 1 ) . $number_of_issues;
}
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'] !== 'application/json' && $request ['content_type'] !== 'application/xml') {
throw new \InvalidArgumentException ( 'invalid content-type specified. supported types are "application/json" and "application/xml"' );
}
if ($request ['type'] === 'post' && ! isset ( $request ['content_type'] )) {
throw new \LogicException ( 'no content-type was specified for this POST request, which is required. supported types are "application/json" and "application/xml"' );
}
// 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']
) );
}
// 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
(which is completely untested on my part, by the way.)
another issue you should fix is that your curl code is executed completely without error detection. for example, curl_setopt returns bool(false) if there was a problem setting your option, and curl_exec() returns bool(false) if there was a problem with during the transfer, add error detection for that. these functions should make that rather easy:
function ecurl_setopt ( /*resource*/$ch , int $option , /*mixed*/ $value ):bool{
$ret=curl_setopt($ch,$option,$value);
if($ret!==true){
//option should be obvious by stack trace
throw new RuntimeException ( 'curl_setopt() failed. curl_errno: ' . return_var_dump ( curl_errno ($ch) ).'. curl_error: '.curl_error($ch) );
}
return true;
}
function ecurl_exec ( /*resource*/$ch):bool{
$ret=curl_exec($ch);
if($ret===false){
throw new RuntimeException ( 'curl_exec() failed. curl_errno: ' . return_var_dump ( curl_errno ($ch) ).'. curl_error: '.curl_error($ch) );
}
return $ret;
}
function return_var_dump(/*...*/){
$args = func_get_args ();
ob_start ();
call_user_func_array ( 'var_dump', $args );
return ob_get_clean ();
}
and to be sure you're not leaking any memory, you can wrap it all around a try{...curl...}finally{curl_close($ch);}, making sure curl_close would always be called, regardless of which curl function throws an exception. (this prevents memory leaks)
I am developing my custom theme and I noticed that some of the links result in showing me plain text HTML instead of normal webpage. I tracked down the issue and found out that this happens when I include one custom php file inside my functions.php. I found that code on one of the tutorial on how to create social share buttons. If I comment include out everything works like a charm. I tried to investigate the file but I couldn't find anything wrong with it, could you please have a look what might be wrong?
<?php
function get_likes($url) {
$json_string = file_get_contents('https://api.facebook.com/method/links.getStats?urls=' . $url . '&format=json');
$json = json_decode($json_string, true);
if(isset($json[0]['total_count'])){
return intval( $json[0]['total_count'] );
} else { return 0;}
}
function get_tweets($url) {
$json_string = file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url=' . $url);
$json = json_decode($json_string, true);
if(isset($json['count'])){
return intval( $json['count'] );
} else {return 0;}
}
function get_plusones($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://clients6.google.com/rpc");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"' . $url . '","source":"widget","userId":"#viewer","groupId":"#self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
$curl_results = curl_exec ($curl);
curl_close ($curl);
$json = json_decode($curl_results, true);
if(isset($json[0]['result']['metadata']['globalCounts']['count'])){
return intval( $json[0]['result']['metadata']['globalCounts']['count'] );
} else {return 0;}
}
function get_stumble($url) {
$json_string = file_get_contents('http://www.stumbleupon.com/services/1.01/badge.getinfo?url='.$url);
$json = json_decode($json_string, true);
if (isset($json['result']['views'])) {
return intval($json['result']['views']);
} else {return 0;}
}
if(isset($_GET["thisurl"])){
$thisUrl=$_GET["thisurl"];
$firstpart = substr("$thisUrl", 0, 22);
// Change http://medialoot.com to your own domain!
if ($firstpart == 'http://mdbootstrap.com') {
$data = "{";
$data .= '"facebook": '. json_encode(get_likes($thisUrl)) . ", ";
$data .= '"twitter": ' . json_encode(get_tweets($thisUrl)) . ", ";
$data .= '"gplus": ' . json_encode(get_plusones($thisUrl)) . ", ";
$data .= '"stumble": ' . json_encode(get_stumble($thisUrl)) . "}";
} else {
//throw error
$data = 'ERROR - you are trying to use this script for something outside of the allowed domain';
}
} else {
$data = '';
}
header('Content-Type: application/json');
echo $data;
?>
You are echoing the contents of $data – I guess thats also what you are seeing if I understood that correctly.
If the code is included in your functions.php like this, it probably gets executed as soon as the functions.php file is loaded, which might be too late or too early.
To be able to control when the code executes, you should have a look into WordPress Hooks and hook your code into this mechanism.
If you can tell me more about what exactly you are trying to do, I might be able to give a more detailed answer.
Just as a sidenote: Take care not to cross over into Plugin territory with your theme. As soon as you are trying to do anything more than modifying the look of something, it doesn't belong into functions.php anymore but a separate plugin.
This question already has answers here:
What is the best way to check if a URL exists in PHP?
(5 answers)
Closed 7 years ago.
I'm trying to make broken link checker with php.
I modified some php code i found online i'm not php programmer.
It let's in some unbroken link's but thats ok.
However I have problem with all presentation, zips and so on...
Basicly if it is downlaod then algorithm thinks it's a dead link.
<?php
set_time_limit(0);
//ini_set('memory_limit','512M');
$servername = "localhost";
$username = "";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=test", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully" . "<br />";
echo "----------------------------------------------------<br />";
}
catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$sql = "SELECT object,value FROM metadata where xpath = 'lom/technical/location'";
$result = $conn->query($sql)->fetchAll(PDO::FETCH_ASSOC);
//print_r($result);
$array_length = sizeof($result); //26373
//$array_length = 26373;
$i = 0;
$myfile = fopen("Lom_Link_patikra1.csv", "w") or die("Unable to open file!");
$menu_juosta = "Objektas;Nuoroda;Klaidos kodas;\n";
//fwrite($myfile,$menu_juosta);
for ($i; $i < $array_length; $i++) {
$new_id = $result[$i]["object"];
$sql1 = "SELECT published from objects where id ='$new_id'";
$result_published = $conn->query($sql1)->fetchAll(PDO::FETCH_ASSOC);
//print_r ($result_published);
if ($result_published[0]["published"] != 0) {
$var1 = $result[$i]["value"];
$var1 = str_replace('|experience|902', '', $var1);
$var1 = str_replace('|packed_in|897', '', $var1);
$var1 = str_replace('|packed_in|911', '', $var1);
$var1 = str_replace('|packed_in|895', '', $var1);
$request_response = check_url($var1); // Puslapio atsakymas
if ($request_response != 200) {
$my_object = $result[$i]["object"] . ";" . $var1 . ";" . $request_response . ";\n";
fwrite($myfile, $my_object);
}
}
}
fclose($myfile);
$conn = null;
function check_url($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
$headers = curl_getinfo($ch);
curl_close($ch);
return $headers['http_code'];
}
Link example : http://lom.emokykla.lt/MO/Matematika/pazintis_su_erdviniais%20_kunais_1.doc
Any solutions, advice?
Thank you all for help.Now it works way faster. It seems there is problem with blank spaces, but that's even intriguing.
As it seems the problem i had was in understanding, how http status is working, like what it return's and why. Link's that i had marked as bad,but working where 301 or 302 - Redirect's.
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
Thank you all for help.
Using CURL for remote file
function checkRemoteFile($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
// don't download content
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if(curl_exec($ch)!==FALSE)
{
return true;
}
else
{
return false;
}
}
EDIT: I may have misunderstood you but if you just want to check if the url actually exists than the code below will be all you need.
function url_exists($url) {
if(#file_get_contents($url,0,NULL,0,1))
{return 1;}
else
{return 0;}
}
curlopt_nobody set to TRUE makes a HTTP HEAD request instead of a GET request, so try using curl_setopt( $ch, CURLOPT_NOBODY, true );
Try to use file_exists method : http://php.net/manual/fr/function.file-exists.php
I'm trying to do a very basic setup of LinkedIn - accessing public profile data about people.
I've tried several ways of accessing with oAuth over several hours. I'm not getting anywhere.
All the existing class structures et'al seem to help with accessing a user's account to post, or add friends, find a fish etc. I don't need any of that. I just want to get basic profile data.
Some code of latest attempts; but I don't get it past here:-
$consumer = new OAuthConsumer($apiKey, $apiSecret);
$signature_method = new OAuthSignatureMethod_HMAC_SHA1();
$req_req = OAuthRequest::from_consumer_and_token($consumer, NULL, "GET", $linkedInURL . "/uas/oauth/requestToken");
$req_req->sign_request($signature_method, $consumer, NULL);
$signed_url = $req_req->to_url();
That should gives me a signed request of:-
https://api.linkedin.com/uas/oauth/requestToken?oauth_consumer_key=xxx&oauth_nonce=xx&oauth_signature=xxxx&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1316530337&oauth_version=1.0
Obviously, that's not what I need to get data. But, just out of interest I checked the URL with the API data request, as such:-
http://api.linkedin.com/v1/people/url=http%3A%2F%2Fwww.linkedin.com%2Fin%2Fchrisvoss:public?oauth_consumer_key=xxx&oauth_nonce=xxx&oauth_signature=xxx&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1316529463&oauth_version=1.0
And got :-
<error>
<status>401</status>
<timestamp>1316531835564</timestamp>
<request-id>L8A1M85MWN</request-id>
<error-code>0</error-code>
<message>
[unauthorized].OAU:tm6i3ke827xz|*01|*01|*01:1316529463:MSFHS3f4iaG9pg2gWYlf22W4NPo=
</message>
</error>
I'm just a bit clueless here. I know everyone says it's tears to implement oAuth and Linkedin. But, I don't need half of what most need, so how do I get to the basic data is only my question.
Thanks in advance for any help.
Try To Use the following code
session_start();
require_once("OAuth.php");
$domain = "https://api.linkedin.com/uas/oauth";
$sig_method = new OAuthSignatureMethod_HMAC_SHA1();
$test_consumer = new OAuthConsumer("DEHYU99peS88wDDAFOcSm3Af5VO1tdrdgq1xPu_fpSSjsqPcoeABUs_NCyY33WIH", "gZrZr2-7s80CEsGpAHqFgREMbRWkR3L8__tkje3j-oKtIDlmn5KCR6bXD8i0HFp1", NULL);
$callback = "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']."?action=getaccesstoken";
# First time through, get a request token from LinkedIn.
if (!isset($_GET['action'])) {
$req_req = OAuthRequest::from_consumer_and_token($test_consumer, NULL, "POST", $domain . "/requestToken");
$req_req->set_parameter("oauth_callback", $callback); # part of OAuth 1.0a - callback now in requestToken
$req_req->sign_request($sig_method, $test_consumer, NULL);
$ch = curl_init();
// make sure we submit this as a post
curl_setopt($ch, CURLOPT_POSTFIELDS, ''); //New Line
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER,array (
$req_req->to_header()
));
curl_setopt($ch, CURLOPT_URL, $domain . "/requestToken");
curl_setopt($ch, CURLOPT_POST, 1);
$output = curl_exec($ch);
curl_close($ch);
//print_r($req_req); //<---- add this line
//print("$output\n"); //<---- add this line
parse_str($output, $oauth);
# pop these in the session for now - there's probably a more secure way of doing this! We'll need them when the callback is called.
$_SESSION['oauth_token'] = $oauth['oauth_token'];
$_SESSION['oauth_token_secret'] = $oauth['oauth_token_secret'];
# Redirect the user to the authentication/authorisation page. This will authorise the token in LinkedIn
Header('Location: ' . $domain . '/authorize?oauth_token=' . $oauth['oauth_token']);
#print 'Location: ' . $domain . '/authorize?oauth_token=' . $oauth['oauth_token']; // <---- add this line
} else {
# this is called when the callback is invoked. At this stage, the user has authorised the token.
# Now use this token to get a real session token!
//print "oauth_token = [[".$_REQUEST['oauth_token']."]]\n";echo "<br/><br/>";
$req_token = new OAuthConsumer($_REQUEST['oauth_token'], $_SESSION['oauth_token_secret'], 1);
$acc_req = OAuthRequest::from_consumer_and_token($test_consumer, $req_token, "POST", $domain . '/accessToken');
$acc_req->set_parameter("oauth_verifier", $_REQUEST['oauth_verifier']); # need the verifier too!
$acc_req->sign_request($sig_method, $test_consumer, $req_token);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, ''); //New Line
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER,array (
$acc_req->to_header()
));
curl_setopt($ch, CURLOPT_URL, $domain . "/accessToken");
curl_setopt($ch, CURLOPT_POST, 1);
$output = curl_exec($ch);
if(curl_errno($ch)){
echo 'Curl error 1: ' . curl_error($ch);
}
curl_close($ch);
parse_str($output, $oauth);
$_SESSION['oauth_token'] = $oauth['oauth_token'];
$_SESSION['oauth_token_secret'] = $oauth['oauth_token_secret'];
# Now you have a session token and secret. Store these for future use. When the token fails, repeat the above process.
//$endpoint = "http://in.linkedin.com/in/intercom"; # need a + symbol here.
$endpoint = "http://api.linkedin.com/v1/people/~:(id,first-name,last-name,headline,industry,educations,site-standard-profile-request)";
//$req_token = new OAuthConsumer($oauth['oauth_token'], $oauth['oauth_token_secret'], 1);
$req_token = new OAuthConsumer($oauth['oauth_token'],$oauth['oauth_token_secret'], 1);
//$profile_req = OAuthRequest::from_consumer_and_token($test_consumer, $req_token, "GET", $endpoint, array("name" => "intercom")); # but no + symbol here!
$profile_req = OAuthRequest::from_consumer_and_token($test_consumer,$req_token, "GET", $endpoint, array());
$profile_req->sign_request($sig_method, $test_consumer, $req_token);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER,array (
$profile_req->to_header()
));
curl_setopt($ch, CURLOPT_URL, $endpoint);
$output = curl_exec($ch);
if(curl_errno($ch)){
echo 'Curl error 2: ' . curl_error($ch);
}
curl_close($ch);
//header ("Content-Type:text/xml");
//print $output;
$myFile = $_SERVER['DOCUMENT_ROOT']."/oauth/linkedin.xml";
$fh = fopen($myFile, 'w') or die("can't open file");
//$stringData = "Bobby Bopper\n";
fwrite($fh, $output);
fclose($fh);
//Initialize the XML parser
global $currentTag;
global $profileArray;
$parser=xml_parser_create();
//Function to use at the start of an element
function start($parser,$element_name,$element_attrs) {
$element_name = strtolower($element_name);
global $currentTag;
$currentTag = $element_name;
/*switch($element_name) {
case "person":
$currentTag = $element_name;
break;
case "headline":
echo "headline: ";
break;
case "school-name":
echo "school-name: ";
break;
case "degree":
echo "degree: ";
break;
case "field-of-study":
echo "field-of-study: ";
}*/
}
//Function to use at the end of an element
function stop($parser,$element_name) {}
//Function to use when finding character data
function char($parser,$data){
//echo $data;
global $currentTag;
global $profileArray;
switch($currentTag) {
/* case "member-url":
if(!isset($profileArray['member-url'])) {
$profileArray['member-url'] = $data;//echo $profileArray['industry'];
}
break;*/
case "id":
if(!isset($profileArray['id'])) {
$profileArray['id'] = $data;//echo $profileArray['industry'];
}
break;
case "site-standard-profile-request":
if(!isset($profileArray['site-standard-profile-request'])) {
$profileArray['site-standard-profile-request'] = $data;//echo $profileArray['industry'];
}
break;
case "first-name":
if(!isset($profileArray['first-name'])) {
$profileArray['first-name'] = $data;//echo $profileArray['industry'];
}
break;
case "last-name":
if(!isset($profileArray['last-name'])) {
$profileArray['last-name'] = $data;//echo $profileArray['industry'];
}
break;
case "industry":
if(!isset($profileArray['industry'])) {
$profileArray['industry'] = $data;//echo $profileArray['industry'];
}
break;
case "headline":
if(!isset($profileArray['headline'])) {
$profileArray['headline'] = $data;
}
break;
case "school-name":
if(!isset($profileArray['school-name'])) {
$profileArray['school-name'] = $data;
}
break;
case "degree":
if(!isset($profileArray['degree'])) {
$profileArray['degree'] = $data;
}
break;
case "field-of-study":
if(!isset($profileArray['field-of-study'])) {
$profileArray['field-of-study'] = $data;
}
break;
}
}
//Specify element handler
xml_set_element_handler($parser,"start","stop");
//Specify data handler
xml_set_character_data_handler($parser,"char");
//Open XML file
$fp=fopen($_SERVER['DOCUMENT_ROOT']."/oauth/linkedin.xml","r");
//Read data
while ($data=fread($fp,4096)) {
xml_parse($parser,$data,feof($fp)) or
die (sprintf("XML Error: %s at line %d",
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser)));
}
//Free the XML parser
xml_parser_free($parser);
print_r($profileArray);
getCurrentCookieValue($name)
}
you can use linkedIn javascript API to retrieve profile information