I'm not sure if what I want to do is possible but here's the case.
Cookies are set on server A (first name, last name, etc).
I have a script on server A which gets the cookies, saves it into the db for future use and then finally displays it. Let's say the script is getCookies.php
Here's the code:
include 'dbconnect.php';
$sessid = $_GET['sid'];
$un = $_COOKIE['un'];
$ul = $_COOKIE['ul'];
$up = $_COOKIE['up'];
$ue = $_COOKIE['ue'];
$idn = $_COOKIE['idn'];
if(!empty($un) || !empty($ul) || !empty($up) || !empty($ue) || !empty($idn)){ // Save log to Database
$savedate = date('Y-m-d G:i');
$q = "INSERT INTO cookiedb (sid, un, ul, up, ue, idn, savedate) VALUES ('$sessid', '$un', '$ul', '$up', '$ue', '$idn', '$savedate')";
$rs = mysqli_query($con,$q);
}
echo "$un, $ul, $up, $ue, $idn";
The code above works if I directly access the script from the browser. However, if I access on another server (server B) using CURL, the cookies doesn't seem to work. It's not being read and saved in the db. I'm getting a blank response. I even used some codes like this suggestion I found here on stackoverflow:
$url = "http://serverA.co.za/getCookie.php";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// get headers too with this line
curl_setopt($ch, CURLOPT_HEADER, 1);
$result = curl_exec($ch);
// get cookie
// multi-cookie variant contributed by #Combuster in comments
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $matches);
$cookies = array();
foreach($matches[1] as $item) {
parse_str($item, $cookie);
$cookies = array_merge($cookies, $cookie);
}
var_dump($matches);
...but this code does not work. Do you have any idea how I can get the value for those cookies? If CURL could not be used here, are there any other ways? Thank you.
Related
I'm junior php developer with one year experience.
It's my first time to ask for some help
If there's anything that is not appropriate,please tell me,thanks a lot.
Situation:
1.We have two different places(domain A, domain B)
2.When updating the sql on domain A, save a txt file in JSON type as well.(json.txt)
3.Then "send" this txt file from domain A to domain B
4.read and decode the txt file on domain B, then used in Updating sql
Question:
that "send" in situation 3 is the question need to be helped.
What kind of method can be used in this situation?
Here is the whole process in code :
Domain A = "c://example"
Domain B = "220.xxx.xx"
testing file = "sending.txt"
DomainA
<?php
// this code is on Domain A
include_once "lib/database.php";
$pdo = DB_CONNECT();
$file = "sending.txt";
$f = fopen($file, 'w');
// select data from sql, update and put in array, then save it into txt
$sql = "SELECT id,lastupdated FROM customer";
$pdo -> query($sql);
$rs = $pdo -> query($sql);
foreach ($rs as $key => $row) {
$array[$key]=[
"id" => $row["id"],
"lastupdated" => $row["lastupdated"],
];
$sql = "INSERT INTO customer_test (customer_id,lastupdated) VALUES
(".$row["id"].",'".$row["lastupdated"]."')";
$pdo -> query($sql);
}
$array_json = json_encode($array);
fwrite($f, $array_json);
fclose($f);
?>
The Json txt I svaed
[{"id":"1","lastupdated":"2017-03-01 13:55:17"},
{"id":"2","lastupdated":"2017-01-08 17:03:39"},
{"id":"3","lastupdated":"2017-02-07 09:34:29"}]
Domain B
<?php
include_once "lib/database.php";
$pdo = DB_CONNECT();
// get from local txt which has been sent to here From other Domain;
$json_data = file_get_contents('sending.txt');
$array = json_decode($json_data, true);
//then save into same database,but this one is on Domain B.
foreach ($array as $i => $row) {
$id = $array[$i]["id"];
$lastupdated = $array[$i]["lastupdated"];
$sql = "INSERT INTO customer_test (customer_id,lastupdated) VALUES
(".$id.",'".$lastupdated."')";
$pdo -> query($sql);
}
?>
What code should I add in these two php files?
My boss only give this link to me :
How to simulate browser form POST method using PHP/cURL
But I still don't have any idea at all.
Can't even know where to add my code to test.
Please take a look when you are available with this question.
Many thanks.
Add this to the bottom of Domain A. This generates a post request by the php curl library. You'll need to have it installed and it likely is. http://php.net/manual/en/book.curl.php
$ch = curl_init('http://220.xxx.xx');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $array_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($array_json))
);
And check the data from Domain A by putting this on domain B:
var_dump($_RESPONSE);exit;
Also, open up the network tab on your element-inspector to get a better idea of what's going on.
// get from local txt which has been sent to here From other Domain;
It could go the other way around. Domain A doesn't send the text... Domain B retrieves the text from Domain A.
Example from php.net: http://php.net/manual/en/curl.examples.php
<?php
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "c://example/sending.txt"); // Domain A
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
// or you could use file_get_contents
$text = file_get_contents('c://example/sending.txt');
$text_array = json_decode($text); print_r($text_array);
?>
I've been trying to write a simple script in PHP to pull off data from a ISBN database site. and for some reason I've had nothing but issues using the file_get_contents command.. I've managed to get something working for this now, but would just like to see if anyone knows why this wasn't working?
The below would not populate the $page with any information so the preg matches below failed to get any information. If anyone knows what the hell was stopping this would be great?
$links = array ('
http://www.isbndb.com/book/2009_cfa_exam_level_2_schweser_practice_exams_volume_2','
http://www.isbndb.com/book/uniform_investment_adviser_law_exam_series_65','
http://www.isbndb.com/book/waterworks_a02','
http://www.isbndb.com/book/winning_the_toughest_customer_the_essential_guide_to_selling','
http://www.isbndb.com/book/yale_daily_news_guide_to_fellowships_and_grants'
); // array of URLs
foreach ($links as $link)
{
$page = file_get_contents($link);
#print $page;
preg_match("#<h1 itemprop='name'>(.*?)</h1>#is",$page,$title);
preg_match("#<a itemprop='publisher' href='http://isbndb.com/publisher/(.*?)'>(.*?)</a>#is",$page,$publisher);
preg_match("#<span>ISBN10: <span itemprop='isbn'>(.*?)</span>#is",$page,$isbn10);
preg_match("#<span>ISBN13: <span itemprop='isbn'>(.*?)</span>#is",$page,$isbn13);
echo '<tr>
<td>'.$title[1].'</td>
<td>'.$publisher[2].'</td>
<td>'.$isbn10[1].'</td>
<td>'.$isbn13[1].'</td>
</tr>';
#exit();
}
My guess is you have wrong (not direct) URLs. Proper ones should be without the www. part - if you fire any of them and inspect the returned headers, you'll see that you're redirected (HTTP 301) to another URL.
The best way to do it in my opinion is to use cURL among curl_setopt with options CURLOPT_FOLLOWLOCATION and CURLOPT_MAXREDIRS.
Of course you should trim your urls beforehands just to be sure it's not the problem.
Example here:
$curl = curl_init();
foreach ($links as $link) {
curl_setopt($curl, CURLOPT_URL, $link);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curl, CURLOPT_MAXREDIRS, 5); // max 5 redirects
$result = curl_exec($curl);
if (! $result) {
continue; // if $result is empty or false - ignore and continue;
}
// do what you need to do here
}
curl_close($curl);
So, I'm working with the Instagram API, but I cannot figure out how to create a like (on a photo) for the logged in user.
So my demo app is currently displaying the feed of a user, and it's requesting the permission to like and comment on behalf of that user. I'm using PHP and Curl to make this happen, creds to some guide I found on the internet:
<?php
if($_GET['code']) {
$code = $_GET['code'];
$url = "https://api.instagram.com/oauth/access_token";
$access_token_parameters = array(
'client_id' => '*MY_CLIENT_ID*',
'client_secret' => '*MY_CLIENT_SECRET*',
'grant_type' => 'authorization_code',
'redirect_uri' => '*MY_REDIRECT_URI*',
'code' => $code
);
$curl = curl_init($url); // we init curl by passing the url
curl_setopt($curl,CURLOPT_POST,true); // to send a POST request
curl_setopt($curl,CURLOPT_POSTFIELDS,$access_token_parameters); // indicate the data to send
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // to stop cURL from verifying the peer's certificate.
$result = curl_exec($curl); // to perform the curl session
curl_close($curl); // to close the curl session
$arr = json_decode($result,true);
$pictureURL = 'https://api.instagram.com/v1/users/self/feed?access_token='.$arr['access_token'];
// to get the user's photos
$curl = curl_init($pictureURL);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$pictures = curl_exec($curl);
curl_close($curl);
$pics = json_decode($pictures,true);
// display the url of the last image in standard resolution
for($i = 0; $i < 17; $i++) {
$id = $pics['data'][$i]['id'];
$lowres_pic = $pics['data'][$i]['images']['low_resolution']['url'];
$username = $pics['data'][$i]['user']['username'];
$profile_pic = $pics['data'][$i]['user']['profile_picture'];
$created_time = $pics['data'][$i]['created_time'];
$created_time = date('d. M - h:i', $created_time);
$insta_header = '<div class="insta_header"><div class="insta_header_pic"><img src="'.$profile_pic.'" height="30px" width="30px"/></div><div class="insta_header_name">'.$username.'</div><div class="insta_header_date">'.$created_time.'</div></div>';
$insta_main = '<div class="insta_main"><img src="'.$lowres_pic.'" /></div>';
$insta_footer = '<div class="insta_footer"><div class="insta_footer_like"><button onClick="insta_like(\''.$id.'\')"> Like </button></div><div class="insta_footer_comment"><form onSubmit="return insta_comment(\''.$id.'\')"><input type="text" id="'.$id.'" value="Comment" /></form></div></div>';
echo '<div class="insta_content">'. $insta_header . $insta_main . $insta_footer .'</div>';
}
}
?>
Now, it might be a stupid question, but how do I make a like on a particular photo on behalf of the user? I'm used to using JavaScript to these kinds of things, therefore I've setup the Like-button with a JS function (which does not exist). But since the Instagram thing have been using Curl and PHP, I'm guessing I have to do the same thing here? I have no experience with Curl, and I do not understand how it works. It would be great if someone could give me a headsup on that as well. But first off, the liking. If it's possible to do it with JS, I'd be very glad. If not, please show me how to do it with PHP and Curl.
Here's a link to the Instagram developers site, which contain the URL you should send a POST request to http://instagram.com/developer/endpoints/likes/.
And if you're not to busy, I'd be really glad if you could show me how to make a comment on behalf of a user as well :)
Thanks in advance.
Aleksander.
I have a twitter api php script successfully spits out the last 100 of my followers
$flwrs_url = "http://api.twitter.com/1/statuses/followers/exampleuser.json";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $flwrs_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curlout = curl_exec($ch);
curl_close($ch);
$response = json_decode($curlout, true);
foreach($response as $friends){
$id = $friends['id'];
$screen_name = $friends['screen_name'];
....
(I used exampleuser instead of my own account)
How do I extend this to include more or all of my followers?
Thank you
According to the Twitter API Documentation for GET followers/ids the request should return up to 5000 followers.
However, if not all followers are returned by the API, there should be a next_cursor element in the response which can be used to retrieve the next batch of followers. You only have to append the value of next_cursor as cursor to the request (see also the API documentation).
Please note that you are using Version 1 of the Twitter API which has been deprecated recently. That is, it will stop working probably early next year. You should upgrade to Version 1.1 as soon as possible. There are new guidelines in place, one of them is that all requests must be authenticated with oAuth.
Thanks for the answer Florian. BTW stumbing around I think I found the correct way to do what I was looking for. Correct me if I'm wrong.
after using the:
$code=$tmhOAuth->request('GET', $tmhOAuth->url('1/followers/ids'),
array('screen_name' => $user, 'cursor' => $cursor));
technique to grab all 5000 followers (user ids). I use the following code to grab batches of 100 (user details) at a time:
$status_url = "http://api.twitter.com/1/users/lookup.json?user_id=";
$lastNum=$last; // $lastNum=100;
$i=$first; // $i=0;
while($i<$lastNum){
if ($i==($lastNum-1)){
$status_url = $status_url . "$followers[$i]";
}else{
$status_url = $status_url . "$followers[$i],";
}
$i++;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $status_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curlout = curl_exec($ch);
curl_close($ch);
$response = json_decode($curlout, true);
$i = 0;
foreach($response as $friends){
$id = $friends['id'];
$screen_name = $friends['screen_name'];
$name = $friends['name'];
$thumb = $friends['profile_image_url'];
$url = $friends['screen_name'];
$location = $friends['location'];
$description = $friends['description'];
echo "$i) $id $screen_name $name $location $description<br />";
$i++;
}
I realize I need to put "sleep" in between each of these "batches of 100", but I'm not quite sure how much to use.
I searched all over, but have not seen anything related to this question. I have a curl script that obtains a random generated string of 10 characters from a website. I have received permission from the website owner to fetch this data and display it on my blog. My question is this when a user comes to my website it displays the string and if they refresh the page it will display a new string. How can I limit one string per user so that they cannot refresh over and over to obtain multiple strings?
Here is an example curl upon which my code is based:
$url = "http://m.www.yahoo.com/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
preg_match('/<dl class="markets clearfix strong small">(.*)<\/dl>/is', $output, $matches);
echo $matches[0];
curl_close($ch);
maybe you can use session variable to check if the user has already got a string.
function startSession(){
$id = session_id();
if ($id != '')
session_write_close();
if (isset($_COOKIE['PHPSESSID']) && $id != $_COOKIE['PHPSESSID']) {
session_write_close();
session_id($_COOKIE['PHPSESSID']);
}
session_start();
}
//Start your sessions
startSession();
if (!$_SESSION['UserGotAString']) {
echo "Some Error msg"
return;
}
session_write_close();
//Request to Yahoo and regex match comes here..
// Start a session
startSession();
$_SESSION['UserGotAString'] = true
echo $matches[0];
session_write_close();
Im not sure if this a good method. Also if you want to reset the session variable base on timer check this link
Set timeout in php