How to run a file_get_content in a loop? - php

I'm trying to loop it. But when executing this script:
for ( $page_number = 1; $page_number <= $pages_count ; $page_number++ )
{
$url = $this->makeURL( $limit, $category->getSources()[0]->getSourceId(), $subCat->getSources()[0]->getSourceId() );
echo $url."</br>"; // Returns the correct URL
$json = json_decode( file_get_contents( $url ) );
echo "<pre>";
print_r( $json ); //Only return the proper date the first time. Then its always the same whatever the url
echo "</pre>";
//$this->insert( $json, $subCat );
$limit = $limit + 10;
}
The reponse I get in the file_get_contents() doesn't match the url called (the parameters changes during the loop of course, its like a pagination, but I always get the first page for no reason.). Even if the URL is ok, it doesn't seem to call this page and always returns the same results. But when I copy and paste the URL from the what I get in the echo to my browser search/url bar, I get the right results.
I have the feeling I'm missing something with file_get_contents() maybe to clear the previous call or something.
EDIT: This is the makeURL()
public function makeURL( $limit, $mainCat, $subCat )
{
$pagi_start = $limit;
$url = "http://some.api/V3/event_api/getEvents.php?"
. "&cityId=" . "39"
. "&subcat=" . $subCat
. "&cat=" . $mainCat
. "&link=" . "enable"
. "&tags=" . "enable"
. "&strip_html=". "name,description"
. "&moreInfo=" . "popularity,fallbackimage,artistdesc"
. "&tz=" . "America/Los_ Angeles"
. "&limit=" . $pagi_start.",10";
return $url;
}

Without providing fuller code, hard to know exactly what is happening. But I have two ideas based on past experience.
First, perhaps the server is simply unable to handle too many requests at once. So I would suggest adding a sleep() setting in your script to pause between request to give the server a chance to catch up.
for ( $page_number = 1; $page_number <= $pages_count ; $page_number++ )
{
$url = $this->makeURL( $limit, $category->getSources()[0]->getSourceId(), $subCat->getSources()[0]->getSourceId() );
echo $url."</br>";
$json = json_decode( file_get_contents( $url ) );
// Adding a 'sleep()' command with a 10 second pause.
sleep(10);
echo "<pre>";
print_r( $json );
echo "</pre>";
//$this->insert( $json, $subCat );
$limit = $limit + 10;
}
The other idea is perhaps the server you are trying to connect to is blocking curl requests? What happens if you go to the command line and type the following"
curl "http://some.api/V3/event_api/getEvents.php?[all parameters here]"
Or even check the headers with the curl -I option like this:
curl -I "http://some.api/V3/event_api/getEvents.php?[all parameters here]"
EDIT: Looking at your makeURL() function shows me another glaring issue. Pretty sure you should be using urlencode() on the values.
This is how I would recode your function:
public function makeURL( $limit, $mainCat, $subCat )
{
$pagi_start = $limit;
// Set the param values.
$param_array = array();
$param_array['cityId'] = 39;
$param_array['subcat'] = $subCat;
$param_array['cat'] = $mainCat;
$param_array['link'] = "enable";
$param_array['tags'] = "enable";
$param_array['strip_html'] = "name,description";
$param_array['moreInfo'] = "popularity,fallbackimage,artistdesc";
$param_array['tz'] = "America/Los_ Angeles";
$param_array['limit'] = $pagi_start . ",10";
// Now roll through the param values urlencode them.
$param_array_urlencoded = array();
foreach($param_array as $param_key => $param_value) {
$param_array_urlencoded[$param_key] = urlencode($param_value);
}
// Create the final param array.
$param_array_final = array();
foreach($param_array_urlencoded as $final_param_key => $final_param_value) {
$param_array_final[] = $final_param_key . "=" . $final_param_value;
}
// Create the final URL with the imploded `$param_array_final`.
$url = "http://some.api/V3/event_api/getEvents.php?" . implode("&", $param_array_final) ;
return $url;
}

Related

Calls to Office365 API to synchronize events, throttling

I am trying to synchronize a few events from Outlook to my local DB and I call the API as below:
$url = 'https://outlook.office365.com/api/v2.0/users/' . $this->user . '/CalendarView/'
. '?startDateTime=' . $start_datetime
. '&endDateTime=' . $end_datetime
This gives me all the events from Outlook between two specific dates.
Then I go and save all this events using the code below. The problem with it is that it returns only 10 events at a time.
$http = new \Http_Curl();
$http->set_headers( $this->get_headers() );
$response = $http->get( $url );
$data = array();
$continue = true;
while ( $continue ) {
if ( isset($response->value) ) {
$arr = array();
foreach ( $response->value as $event ) {
$arr[] = $event;
}
$data = array_merge( $data, $arr );
}
$property = '#odata.nextLink';
if ( isset( $response->$property ) ) {
$url = $response->$property;
$response = $http->get( $url );
} else {
$continue = false;
}
}
unset( $http );
return $data;
I tried then to call the API like below, setting the top parameter to 10, but I end up with many empty events.
$url = 'https://outlook.office365.com/api/v2.0/users/' . $this->user . '/CalendarView/'
. '?startDateTime=' . $start_datetime
. '&endDateTime=' . $end_datetime
.'&top=100'
I am trying to avoid making more than 60 calls per minute. Is there any way to first get the number of events between two dates and then retrieve all of them, so the top parameter should actually be the total number of events.
The correct query parameter is $top and not top. Notice $ in there.
http://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/part2-url-conventions/odata-v4.0-errata03-os-part2-url-conventions-complete.html#_Toc453752362
5.1.5 System Query Options $top and $skip
The $top system query option requests the number of items in the queried collection to be included in the result. The $skip query option requests the number of items in the queried collection that are to be skipped and not included in the result. A client can request a particular page of items by combining $top and $skip.
The semantics of $top and $skip are covered in the [OData-Protocol] document. The [OData-ABNF] top and skip syntax rules define the formal grammar of the $top and $skip query options respectively.

Not able to remove backslash from below code?

below is my code the issue is that when i enter any username with apostrophe (') Additional character "\ backslash" is being displayed when Search results are returned.
Below is my code i find that a function addslashes is used in the checkusername function so backslash is getting added.
if ( 0 < count( $my_field_place ))
{
for ( $i = 0; $i < count( $my_field_place ); $i++ )
{
if ( true === isset( $Fields[$i] ))
{
print "gMapping[$i] = new MappingItem( '" .
addslashes( $Fields[$i] ) .
"', '" .
checkusername( $my_field_place[$i] ) .
"' );";
}
}
}
function checkusername($inStr)
{
$orig = array();
$new = array();
$orig[00] = "/\n/`" ; $new[00] = "\\?n";
$orig[01] = "/[^\x-*()]/"; $new[01] = "";
$var1 = preg_replace($orig, $new, $inStr);
$var2 = addslashes($var1 ); // i am not sure why addslashes is used but i am asked not to remove because of security reasion?
return $var2;
}
Note: I google and find that it used for security reason
Since in my case we are only displaying the searched result. So i am not sure why this function is used here.
My fix is to add stripslashes() function before returning which will removes backslashes added by the addslashes() function.
Please find the code snippet and the comment for code change below:
function checkusername($inStr)
{
$orig = array();
$new = array();
$orig[00] = "/\n/`" ; $new[00] = "\\?n";
$orig[01] = "/[^\x-*()]/"; $new[01] = "";
$var1 = preg_replace($orig, $new, $inStr);
$var2 = addslashes($var1);
return stripslashes($var2); // i am not sure stripslashes is correct fix or not?
}
Please help is it fine to added stripslashes or is there any other way to handle it ?
You can restrict user from those special characeter
though in gmail ,yahoo,fb etc they will never
allow this character.since t allows multiple words to be represented in a somewhat readable manner
below are some doc
https://support.google.com/a/answer/33386?hl=en
see second guidelines

preg_replace remove parameter variable

Want to remove p2variable from url string, below are 3 cases if case 3 also remove ? sign.
case 1: http://www.domain.com/myscript.php?p1=xyz&p2=10&p3=ghj
result: http://www.domain.com/myscript.php?p1=xyz&p3=ghj
case 2: http://www.domain.com/myscript.php?p2=10&p3=ghj
result: http://www.domain.com/myscript.php?p3=ghj
case 3: http://www.domain.com/myscript.php?p2=10
result: http://www.domain.com/myscript.php
Want to achieve result with single preg_replace expression.
Don't use regular expressions when dealing with URL values. It's much easier (and safer) to handle them as a URL instead of plain text.
This could be one way to do it:
Split the url first and parse the query string
Take the parameter out
Rebuild the url
The below code is an example of such an algorithm:
// remove $qs_key from query string of $url
// return modified url value
function clean_url_qs($url, $qs_key)
{
// first split the url in two parts (at most)
$parts = explode('?', $url, 2);
// check whether query string is passed
if (isset($parts[1])) {
// parse the query string into $params
parse_str($parts[1], $params);
// unset if $params contains $qs_key
if (array_key_exists($qs_key, $params)) {
// remove key
unset($params[$qs_key]);
// rebuild the url
return $parts[0] .
(count($params) ? '?' . http_build_query($params) : '');
}
}
// no change required
return $url;
}
Test code:
echo clean_url('http://www.domain.com/myscript.php?p1=xyz&p2=10&p3=ghj', 'p2'), "\n";
echo clean_url('http://www.domain.com/myscript.php?p2=10&p3=ghj', 'p2'), "\n";
echo clean_url('http://www.domain.com/myscript.php?p2=10', 'p2'), "\n";
Found this in one of my old projects (a bit of shitcode, but...), may help you:
$unwanted_param = 'p2';
$s = 'http://www.domain.com/myscript.php?p1=xyz&p2=10&p3=ghj';
$s = parse_url($s);
$params = explode('&', $s['query']);
$out_params = array();
foreach ($params as $key => &$param) {
list($name, $value) = explode('=', $param);
if ($unwanted_param == $name) {
unset($params[$key]);
} else {
$out_params[$name] = $value;
}
}
$query = '?' . http_build_query($out_params);
$result = $s['scheme'] . '://' . $s['host'] . $s['path'] . $query;
var_dump($result);
Using preg_replace, something like
$url = preg_replace('!([\?&]p2=[^&\?$]+)!i', '', $url);
However, personally I'd do the following
if (strpos($url, '?') !== false) {
list($domain, $qstring) = explode('?', $url, 2);
parse_str($qstring, $params);
if (isset($params['p2'])) {
unset($params['p2']);
}
$qstring = !empty($params) ? '?' . http_build_query($params) : '';
$url = $domain . $qstring;
}

some PHP code fails to execute properly when I enclose it in a function, even though variable passing is ok

When I do this:
{some code}
previouslyDeclaredFunction($variable);
{some code}
I can get previouslyDeclaredFunction() to work just fine.
But when I put it inside a new function:
function newFunction($variable){
echo $variable; //see if var passes in properly
{some code}
previouslyDeclaredFunction($variable);
{some code}
}
..then call:
newFunction($variable);
..all of a sudden it stops working EVEN THOUGH I am able to echo() the $variable from within newFunction() just fine, meaning newFunction() was called properly and $variable was passed in properly. Apparently, some stuff inside just won't work unless I remove the whole outer function. PreviouslyDeclaredFunction() is included in the php script and it does get called from within newFunction() but somehow treats $variable differently even though the echo() proves it is being passed in and is the exact same value it was before.
EDIT (ok here comes the REAL code):
$test_tag = "afro";
cacheBuilder($test_tag); //declaration of function
function cacheBuilder($test_tag) {
$images = array();
$tags = array();
$imagetype = 'Hair';
$per_page = 60;
$orderby_view = FALSE;
echo $test_tag; //this works so var is passed in fine
$tags2 = $test_tag;
$tags = explode(',', $test_tag);
if( count($tags) == 1 && strlen($tags[0]) == 0 ) $tags = array();
$tag_url = urlencode($tags2);
$cachename = dirname( __FILE__ ) . '/cache-fp/' . $imagetype . '-' . $per_page . '-' . $page . '-' . ($orderby_view ? 'by_view' : 'by_date') . $tag_url . '.json';
$detailurl = get_option('image_detail_url');
$detailurl .= (strstr($detailurl, '?') === FALSE ? '?' : '&');
$json = array();
$images = array();
$posts = get_pix($imagetype, array('per_page' => $per_page, 'page' => $page, 'tags' => $tags), $orderby_view);
foreach( $posts['attachments'] as $ii => $post ) {
$ta = array();
$meta = array();
$imagesrclight2 = array();
// BWP - Theater mode
$ta['detail_url'] = $detailurl . 'uid=' . $post->post_author . '&img_id=' . $post->ID . '&theater';
$meta = get_post_meta(get_the_ID(), 'image_tag', false);
$ta['image_tags'] = implode(' ', $meta);
$ta['attachment_image'] = wp_get_attachment_image($image->ID, 'thumbnail');
$imagesrclight2 = wp_get_attachment_image_src($image->ID, array(150, 150));
$ta['attachment_image_src'] = rawurlencode($imagesrclight2[0]);
$images[] = $ta;
}
file_put_contents($cachename, json_encode($images));
}
This is a bit complicated, and it's Wordpress, so I hope this isn't totally confusing. While there are no errors, it looks like get_option and/or get_pix are failing inside the outer function. The json produced has no data in it. When I get rid of the outer function, I get json which is populated with data as it should.
I figured it out. For whatever reason, certain Wordpress functions like get_the_ID() fail when I put them inside the function. Not sure why, but when I get the post ID via other means aside from the WP function, the value comes in instead of being null.

Return array from Recursive - Php

When browsing the binary tree I want to return an array of recursive functions. In particular when an element in binary tree reaching conditions (if statement) is inserted into the array. After all, the element returns an array of all. My code not work !??
function tree_view($clear_static = false,$conn,$index)
{
static $count = 0;
if ($clear_static) {
$count = 0;
}
$q=mysql_query("SELECT user_id FROM thanhvien WHERE gioithieu='".$index."'",$conn);
while($arr=mysql_fetch_assoc($q))
{
if (truongban($conn,$arr["user_id"],1)==true){
$mang[$count]=$arr["user_id"];
$count++;
}
tree_view(false,$conn,$arr["user_id"]);
}
return $mang;
}
$mang1=tree_view (true,$conn,anloc);
print_r($mang1);
Well, the problem I see is that you are not doing anything with the array returned from the recursive call, here in this line:
tree_view(false,$conn,$arr["user_id"]);
I would recommend including both the array and the count on the method parameters (using a static variable is not recommended). So it would be like this:
function tree_view($conn, $index, $mang, &$count)
{
$q=mysql_query("SELECT user_id FROM thanhvien WHERE gioithieu='".$index."'",$conn);
while($arr=mysql_fetch_assoc($q))
{
if (truongban($conn,$arr["user_id"],1)==true){
$mang[$count]=$arr["user_id"];
$count++;
}
tree_view($conn,$arr["user_id"], $mang, $count);
}
return $mang;
}
And you would invoke your method like this:
$mang1[0] = "";
$count = 0;
$mang1 = tree_view ($conn, anloc, $mang1, $count); print_r($mang1);
First $mang isn't initialized, but likely should be:
// Always initialize variables - good style
$mang = array();
Instead of passing this ugly $count variable, just append newly discovered data:
// Will append the right side value as a new last element to $mang
$mang[] = $arr["user_id"];
Next, you need to pass the variable $anloc:
$mang1=tree_view ( true, $conn, $anloc );
This version might work better:
function tree_view($conn, $index, $mang ) {
$q=mysql_query( 'SELECT user_id '
. ' FROM thanhvien '
. ' WHERE gioithieu = "' . mysql_real_escape_string ( $index ) . '"',
$conn
);
while( $arr = mysql_fetch_assoc( $q ) ) {
// better compare type-safe
if ( true === truongban( $conn, $arr["user_id"], 1 ) ){
// append found element
$mang[ ] = $arr["user_id"];
}
tree_view( $conn, $arr["user_id"], $mang );
}
return $mang;
} // tree_view

Categories