How do I get twitter posts? - php

I am trying to get twitter posts following this tutorial:
https://www.youtube.com/watch?v=tPrsVKudecs
there aren't a lot of tutorials regarding this online, and twitters console doesn't support running queries anymore as far as I understood.
any idea why this is happening?
This is the output I get in the Chrome "Network":
Remote Address:54.666.666.666:80
Request URL:http://666.com/yh/test/tweets_json.php
Request Method:GET
Status Code:500 Internal Server Error
Response Headers
view source
Connection:close
Content-Length:0
Content-Type:text/html
Date:Mon, 15 Jun 2015 13:51:40 GMT
Server:Apache/2.4.7 (Ubuntu)
X-Powered-By:PHP/5.5.9-1ubuntu4.5
Request Headers
view source
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Host:666.com
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36
Any ideas why this is happening?
Is there a better simple way to do it?
EDIT:
tweets_json.php
<?php
require 'tmhOAuth.php'; // Get it from: https://github.com/themattharris/tmhOAuth
// Use the data from http://dev.twitter.com/apps to fill out this info
// notice the slight name difference in the last two items)
$connection = new tmhOAuth(array(
'consumer_key' => '',
'consumer_secret' => '',
'user_token' => '', //access token
'user_secret' => '' //access token secret
));
// set up parameters to pass
$parameters = array();
if ($_GET['count']) {
$parameters['count'] = strip_tags($_GET['count']);
}
if ($_GET['screen_name']) {
$parameters['screen_name'] = strip_tags($_GET['screen_name']);
}
if ($_GET['twitter_path']) { $twitter_path = $_GET['twitter_path']; } else {
$twitter_path = '1.1/statuses/user_timeline.json';
}
$http_code = $connection->request('GET', $connection->url($twitter_path), $parameters );
if ($http_code === 200) { // if everything's good
$response = strip_tags($connection->response['response']);
if ($_GET['callback']) { // if we ask for a jsonp callback function
echo $_GET['callback'],'(', $response,');';
} else {
echo $response;
}
} else {
echo "Error ID: ",$http_code, "<br>\n";
echo "Error: ",$connection->response['error'], "<br>\n";
}
// You may have to download and copy http://curl.haxx.se/ca/cacert.pem
tmhOAuth.php: https://github.com/themattharris/tmhOAuth/blob/master/tmhOAuth.php
and this pem key: http://curl.haxx.se/ca/cacert.pem
All three in the same folder
In the tutorial it should run the query and get the json output.
I get a blank page.

Related

Doesn’t my curl post request contains cookies?

I need to login to http://auto.vsk.ru/login.aspx making a post request to it from my site.
I wrote a js ajax function that sends post request to php script on my server, that sends cross-domain request via cUrl.
post.php
<?php
function request($url,$post, $cook)
{
$ch = curl_init();
$curlConfig = array(
CURLOPT_URL => $url,
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_COOKIEFILE => $cook,
CURLOPT_COOKIEJAR => $cook,
CURLOPT_USERAGENT => '"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; Trident/7.0; Touch; .NET4.0C; .NET4.0E; Tablet PC 2.0)"',
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_REFERER => $url,
CURLOPT_POSTFIELDS => $post,
CURLOPT_HEADER => 1,
);
curl_setopt_array($ch,$curlConfig);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$result = request($_POST['url'], $_POST['data'], $_POST['cook']);
if ($result === FALSE)
echo('error');
else
echo($result);
?>
Js code:
function postcross(path,data,cook,run)
{
requestsp('post.php','url='+path+'&data='+data+'&cook='+cook, run);
}
function requestp(path, data, run)
{
var http = new XMLHttpRequest();
http.open('POST', path, true);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function()
{
if(http.readyState == 4 && http.status == 200)
{
run(http);
}
}
http.send(data);
}
postcross('http://auto.vsk.ru/login.aspx',encodeURIComponent('loginandpassord'),'vskcookies.txt',function(e){
document.getElementById('container').innerText=e.responseText;
});
The html page I getting from response says two things:
My browser is not Internet Explorer, I should switch to it.(actually it works from Google Chrome, at least can login).
My browser doesn’t support cookies.
About the cookies it is very similar to this (veeeery long) question. File vskcookies.txt is created in my server and it is actually updates after post request call, and stores cookies.
About the IE, firstly I thought that the site checks browser from js, but it is wrong, because js doesn’t run at all - I only read html page as a plain text, and it already has that notification about IE.
So wondered what if I make cUrl request wrong? I wrote new php script that shows request headers, here is a source:
head.php
<?php
foreach (getallheaders() as $name => $value)
{
echo "$name: $value\n";
}
?>
The result of postcross('http://mysite/head.php',encodeURIComponent('loginandpassord'),'vskcookies.txt',function(e){ document.getElementById('container').innerText=e.responseText; }):
Host: my site
User-Agent: "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; Trident/7.0; Touch; .NET4.0C; .NET4.0E; Tablet PC 2.0)"
Accept: */*
Content-Type: application/x-www-form-urlencoded
Referer: mysite/head
X-1gb-Client-Ip: my ip
X-Forwarded-For: ip, ip, ip
X-Forwarded-Port: 443
X-Forwarded-Proto: https
X-Port: 443
Accept-Encoding: gzip
X-Forwarded-URI: /head
X-Forwarded-Request: POST /head HTTP/1.1
X-Forwarded-Host: my site
X-Forwarded-Server: my site
Content-Length: 823
Connection: close
For some reason there is no Cookie: parameters, but user agent is IE as I mentioned.
Also I tried to replace head.php source with
print_r($_COOKIE);
And got empty array:
Am I doing something wrong, or it is site bot-protection?
Update 1
It is showing cookies only if to pass them through CURLOPT_COOKIE.
So I think I will leave CURLOPT_COOKIEFILE => $cook; as it is, and for CURLOPT_COOKIE something like file_get_contents($cook), although there is useless information. protection?
Important Update 2
Okay, probably I just stupid. Response html page indeed consists messages about IE and offed cookies, but they are in div that is display:none and are displayed on by js.
So, seems my tries fail because of another reasons.

Retrieve input value with server-side script for autocomplete()

When I try to implement auto-complete using the code below :
$('#keyword').autocomplete({
source : '/Dev/pages/search.php',
minLength : 3,
type : 'POST',
select: function( event, ui )
{
$(this).data("autocomplete").menu.element.addClass("yellow");
}
})
.data( "ui-autocomplete" )._renderItem = function( ul, item )
{
console.log(item);
return $( "<li>" )
.append( "<a>" + add3Dots(item.name,20) + "</a>" )
.appendTo( ul );
};
if (isset($_POST["term"])){
$term = trim($_GET['term']);
$parts = explode(' ', $term);
$p = count($parts);
$a_json = array();
$a_json_row = array();
$search = connexion::bdd_test();
$requete = "SELECT name from BDD_TEST.companies";
for($i = 0; $i < $p; $i++) {
$requete .= ' WHERE name LIKE ' . "'%" . $conn->real_escape_string($parts[$i]) . "%'";
}
$result = $search->query($requete);
while($donnees = $result->fetch(PDO::FETCH_ASSOC)) {
$a_json_row["name"] = $data['name'];
array_push($a_json, $a_json_row);
}
}
else
{
$a_json['call']=false;
$a_json['message']="Problem to collect word.";
}
$json = json_encode($a_json);
print_r($json);
When I test, if condition is not satisfied and I get the message directly from else " Problem to collect word . "
It means that $_POST["term"] is not defined.
How can I retrieve the input value ?
To be sure that values have been send, you can see what headers the browser sent to the web server with PHP for testing purposes.
This is possible using the apache_request_headers() function but it only works if PHP is run on Apache as a module.
How using apache_request_headers() :
If PHP is run on Apache as a module then the headers the browser send can be retrieved using the apache_request_headers() function. The following example code uses print_r to output the value from this function call:
print_r(apache_request_headers());
The output from the above using an example request from Google Chrome would output something similar to the following:
Array
(
[Host] => www.testing.local
[Connection] => keep-alive
[User-Agent] => Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/532.0 (KHTML, like Gecko) Chrome/4.0.206.1 Safari/532.0
[Cache-Control] => max-age=0
[Accept] => application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
[Accept-Encoding] => gzip,deflate,sdch
[Accept-Language] => en-US,en;q=0.8
[Accept-Charset] => ISO-8859-1,utf-8;q=0.7,*;q=0.3
)
Alternative when PHP is run as a CGI :
If PHP is not being run as a module on Apache, the browser headers should be stored in the $SERVER array with the key being the request header name converted to upper case, hypens replaced with underscores, and prefixed with HTTP
The same request above showing the relevent lines from $_SERVER are as follows:
[HTTP_HOST] => www.testing.local
[HTTP_CONNECTION] => keep-alive
[HTTP_USER_AGENT] => Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/532.0 (KHTML, like Gecko) Chrome/4.0.206.1 Safari/532.0
[HTTP_CACHE_CONTROL] => max-age=0
[HTTP_ACCEPT] => application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
[HTTP_ACCEPT_ENCODING] => gzip,deflate,sdch
[HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.8
[HTTP_ACCEPT_CHARSET] => ISO-8859-1,utf-8;q=0.7,*;q=0.3
The alternative method is create our own function if the apache_request_headers() function does not exist, which extracts just the values from $_SERVER and converts the key names to the same style as apache_request_headers(). This works like so:
if(!function_exists('apache_request_headers')) {
function apache_request_headers() {
$headers = array();
foreach($_SERVER as $key => $value) {
if(substr($key, 0, 5) == 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))))] = $value;
}
}
return $headers;
}
}
The new function is only declare if the function with that name does not already exist. The end result is that whether or not the internal PHP function exists, you will be able to call a function with this name in your code.
A loop is done though the $SERVER array and any whose key starts with HTTP is added to the array, and the key is translated via a series of function calls to be in the same format as returned by apache_request_headers().
View HTTP headers in Google Chrome
Chrome has a tab "Network" with several items and when I click on them I can see the headers on the right in a tab.
Press F12 on windows or ⌥⌘I on a mac to bring up the Chrome developer tools.
Try to retrieve value(s) without knowing HTTP methods
You can detect which request type was used (GET, POST, PUT or DELETE) in PHP by using
$_SERVER['REQUEST_METHOD']
For more details please see the documentation for the $_SERVER variable.
Or you can retrieve value(s) using $_REQUEST['you_variable'].
Note $_REQUEST is a different variable than $_GET and $_POST, it is treated as such in PHP -- modifying $_GET or $_POST elements at runtime will not affect the elements in $_REQUEST, nor vice versa.

get PHP custom response headers

I´m sending an ajax request with a custom header called Authorization,
and I'm trying to get that header with PHP
if (!function_exists('getallheaders'))
{
function getallheaders()
{
$headers = array();
foreach ($_SERVER as $k => $v)
{
if (substr($k, 0, 5) == "HTTP_")
{
$k = str_replace('_', ' ', substr($k, 5));
$k = str_replace(' ', '-', ucwords(strtolower($k)));
$headers[$k] = $v;
}
}
return $headers;
}
}
$val = getallheaders();
echo $val;
and I get all the headers but not the custom one
val: Object{
Accept: "application/json, text/plain, */*"
Accept-Encoding: "gzip, deflate, sdch"
Accept-Language: "es-ES,es;q=0.8,en;q=0.6"
Connection: "keep-alive"
Host: "www.localhost.com"
Origin: "http://localhost"
Referer: "http://localhost/gestion/"
User-Agent: "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36"
}
Any clues why I'm not getting header Authorization?
For custom headers the $_SERVER global in php documentation state that
There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here. That said, a large number of these variables are accounted for in the » CGI/1.1 specification, so you should be able to expect those
so try to use apache_request_headers which may help you if your working with apache as a server
Server Quote
apache_request_headers

Why do I get "POST http://54.xx.xx.xx/wp-admin/admin-ajax.php 500 (Internal Server Error)" when using Wordpress+Ajax?

It's the first time for me using ajax on WP.
I am working on a simple contact form, and for some reason whenever I click submit I get an error:
on console:
POST http://54.xxx.xx.xx/wp-admin/admin-ajax.php 500 (Internal Server Error)jquery.js?ver=1.11.1:4 m.ajaxTransport.sendjquery.js?ver=1.11.1:4 m.extend.ajaxmain.js:66 (anonymous function)jquery.js?ver=1.11.1:3 m.event.dispatchjquery.js?ver=1.11.1:3 m.event.add.r.handle
on chromes "Networks":
Remote Address:54.xx.xx.xx:80
Request URL:http://54.xx.xx.xx/wp-admin/admin-ajax.php
Request Method:POST
Status Code:500 Internal Server Error
Request Headersview source
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:73
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:wp-settings-1=editor%3Dtinymce%26posts_list_mode%3Dlist; wp-settings-time-1=1424359234
Host:54.xx.xx.xx
Origin:http://54.xxx.xx.xx
Referer:http://54.xxx.xx.xx/?page_id=73
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36
X-Requested-With:XMLHttpRequest
Form Dataview sourceview URL encoded
action:submit_contact_form
fullname:test
email:test#gmail.com
text:test
Response Headersview source
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://54.xxx.xx.xx
Cache-Control:no-cache, must-revalidate, max-age=0
Connection:close
Content-Length:0
Content-Type:text/html; charset=UTF-8
Date:Thu, 26 Feb 2015 16:10:19 GMT
Expires:Wed, 11 Jan 1984 05:00:00 GMT
Pragma:no-cache
Server:Apache/2.4.7 (Ubuntu)
X-Content-Type-Options:nosniff
X-Frame-Options:SAMEORIGIN
X-Powered-By:PHP/5.5.9-1ubuntu4.5
X-Robots-Tag:noindex
This is my ajax part:
//send info to php
$.ajax({
beforeSend: function() {
if ( IsEmail(email) == false) {
$('#aboutUnsuccess').show("slow");
$('.form_content').hide("slow");
}
},
url: document.location.protocol+'//'+document.location.host+'/wp-admin/admin-ajax.php',
type: "POST",
/*action: 'submit_contact_form',*/
data: ({ "action": "submit_contact_form", "fullname": fullname, "email": email, "text": text }),
success: function (results){
if ( IsEmail(email) == true) {
//hide table
$('.form_content').hide('slow', function() {
$('.form_content').hide( "slow" );
});
//show textboxes
$('#aboutSuccess').show("slow");
$( "#aboutSuccess" ).append( "<iframe id=\"pixel-thing\" src=\"http://54.xxx.xx.xx/wp-content/themes/twentyfifteen-child/thePixel.html\" width=\"1\" height=\"1\" border=\"0\"></iframe>" );
}
}
});
});
And this is my php fucntion:
// Contact form Ajax
add_action('wp_ajax_nopriv_submit_contact_form', 'submit_contact_form');
function submit_contact_form(){
if(isset($_POST['email'])) {
$email = $_POST['email'];
$email_to = "mail#main.com";
$host = "ssl://smtp.gmail.com:465";
$username = 'mainmain#mail.com';
$password = 'pass';
$email_subject = "You have a new email from $email via asdasd.com website";
$message = $_POST['text'];
$headers = array ('From' => $email, 'To' => $email_to,'Subject' => $email_subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($email_to, $headers, $message);
if (PEAR::isError($mail)) {
echo($mail->getMessage());
} else {
echo("Message successfully sent!\n");
}
}
}
Whay might be the cause of the error?
I tried var_dump() the variables in the php functions.php file, They all display fine.
when I add require_once "Mail.php";
on the top of my php file, pages just stop loading. I'm not sure this is the problem. So I'm trying without it (?)
The error 500 is throwing because your server is not responding to your call.
Did you tried with at start of the php file.
error_reporting(E_ALL);
ini_set("display_errors", 1);
Use firebug so it will post you the call to server and response so you could see the error.
If you are seeing a blank page,then you missed a syntax somewhere in your PHP file. Have a look into your brackets, colons and semi-colons

Manipulating JSON data with PHP

Scenario: Playing an online game, have an javascript file that allows me to port data to a PHP on a server using POST/json. I have to enter the path of my server into my client PC for this to work. I am getting a confirmation that connection is fine.
The PHP only recognises source from the website I am playing on, and I can see data transferring to the site in my developer console. The data being POSTed is in the following format:
I can see the data coming in an array looking at the console:
Request URL: //xxxxxx.xxxx/aix/server_api.php Request Method:POST Status Code:200 OK Request Headersview source Accept:application/json, text/javascript, */*; q=0.01 Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3 Accept-Encoding:gzip,deflate,sdch Accept-Language:en-GB,en-US;q=0.8,en;q=0.6 Connection:keep-alive Content-Length:65236 Content-Type:application/x-www-form-urlencoded; charset=UTF-8 Host:sd.fast-page.org Origin:http://xx.yyy.com Referer:http://xxx.yyy.com/232/index.aspx User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.22 (KHTML, like Gecko) Ubuntu Chromium/25.0.1364.160 Chrome/25.0.1364.160 Safari/537.22 Form Dataview sourceview URL encoded alliance[id]:118 alliance[name]:DS alliance[members]:12 alliance[score]:982078 data_type:city data[0][id]:12517457 data[0][owner_id]:1538 data[0][owner]:MM1 data[0][coords]:'081:191 data[0][name]:C31 4Chief data[0][score]:11020 data[0][city_type]:castle data[0][location]:land data[1][id]:12517458 data[1][owner_id]:1538 data[1][owner]:MM1 data[1][coords]:'082:191 data[1][name]:C31 5Redrum data[1][score]:10596 data[1][city_type]:castle data[1][location]:water data[2][id]:12386381 data[2][owner_id]:1538 data[2][owner]:MM1 data[2][coords]:'077:189 data[2][name]:C31 1Home data[2][score]:10460 data[2][city_type]:castle data[2][location]:land data[3][id]:12320847 data[3][owner_id]:1538 data[3][owner]:MM1 data[3][coords]:'079:188 data[3][name]:C31 6North data[3][score]:10182 data[3][city_type]:castle data[3][location]:land data[4][id]:12386382 data[4][owner_id]:1538 data[4][owner]:MM1 data[4][coords]:'078:189 data[4][name]:C31 3Back data[4][score]:10108 data[4][city_type]:castle data[4][location]:land data[5][id]:12517453 data[5][owner_id]:1538 data[5][owner]:MM1 data[5][coords]:'077:191 data[5][name]:C31 2Second data[5][score]:9968 data[5][city_type]:castle data[5][location]:land data[6][id]:12714060 data[6][owner_id]:1538 data[6][owner]:MM1 data[6][coords]:'076:194 data[6][name]:C31 MacoHub data[6][score]:9692 data[6][city_type]:castle data[6][location]:land data[7][id]:12517460 data[7][owner_id]:1538 data[7][owner]:MM1 data[7][coords]:'084:191 data[7][name]:C31 Tango data[7][score]:9163 data[7][city_type]:castle data[7][location]:land data[8][id]:12582993 data[8][owner_id]:1538 data[8][owner]:MM1 data[8][coords]:'081:192 data[8][name]:C31 Spring data[8][score]:8864 data[8][city_type]:castle data[8][location]:land data[9][id]:12517454 data[9][owner_id]:1538 data[9][owner]:MM1 data[9][coords]:'078:191 data[9][name]:C31 Pally data[9][score]:8816 data[9][city_type]:castle data[9][location]:land data[10][id]:12779603 data[10][owner_id]:1538
[and so on and so forth.....have masked the rest but this is the format
Response Headersview source Access-Control-Allow-Headers:Content-Type Access-Control-Allow-Methods:POST, GET, OPTIONS Access-Control-Allow-Origin: //xxx.yyy Access-Control-Max-Age:1000 Cache-Control:no-store, must-revalidate, max-age=0, proxy-revalidate, no-transform Connection:keep-alive Content-Encoding:gzip Content-Length:70 Content-Type:application/json Date:Fri, 29 Mar 2013 18:08:14 GMT Expires:Fri, 29 Mar 2013 18:08:14 GMT Pragma:no-cache Server:Apache Vary:Accept-Encoding X-Powered-By:PHP/5.5.0alpha5
Now what I see above is the output to the console on my PC when I trigger the client app.
The PHP is as follows:
$m = false;
if(preg_match('/http\:\/\/game url/',$_SERVER['HTTP_ORIGIN'],$m))
{ $m = $m[1]; }
if(empty($m)) { die('Invalid Origin.'); }
if(!empty($_POST['data_type']))
{
$sender = $_POST['sender'];
$alliance = $_POST['alliance'];
$request = $_POST['data_type'];
$data = $_POST['data'];
// Response to Alliance Info Exporter
$json = array(
'message' => 'recieved.',
'data' => array(),
'error' => false
);
// handle data types
switch($request)
{
case 'connection_test': $json['message'] = 'Welcome to our server. Your are connected!'; break;
case 'member' : /* Code for member request */ break;
case 'city' : /* Code for city request */ break;
case 'support' : /* Code for support request */ break;
default : $json['message'] = 'Nothing Done.'; break;
}
// set headers for API
header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-type: application/json');
// Respond
die(json_encode($json));
}
die('No Access.');
I have two or three problems here
I can't seem to manipulate the data that the PHP is getting at all
Whenever I try to add any arguments to the case statement just to even see if I can parse the data somehow then the api stops responding to my client
For example, at the city switch I just tried to output the data to a file just to confirm it was coming through because my browser console gives me a POST success code (http 200)
This is the code I used:
$f = fopen("city.txt", "w");
fwrite($f, $_POST);
fclose($f);
I tried it in the main part of my PHP, tried it at the city case switch (that is the type of query I am executing first), and I tried with other defined types like $data, etc. Nothing writes.
What am I doing wrong?
Secondly my endstate is to post this to a SQL server, how would I do that?

Categories