Running on OSX, on PHP 5.6.30. I am trying to execute a script from a html file, and it downloads the file instead. NOTE: this doesn't work right as the html file should be .php, but that is also downloading instead of opening it.
I have tried:
uncommenting LoadModule php5_module libexec/apache2/libphp5.so
adding AddHandler application/x-httpd-php5 .php to /etc/apache2/httpd.conf
restarting apache (sudo /usr/sbin/apachectl restart)
moving my file to www/script.php
checking that script.php is executable
You can see it at https://reteps.github.io/website.html, and I have only tested on google chrome.
HTML (should be .php)
<!doctype html>
<html>
<head>
<title>
</title>
<link rel="stylesheet" type="text/css" href="navbar.css">
</head>
<body>
<div id="menu">
Home
Github
School Projects
<a href="side.html" >Side Projects</a>
Blog
</div>
<form action="www/script.php" method="get">
<input type="text" name="quizid" placeholder="kahoot id">
<input type="submit" value="Go">
</form>
<p id="output">Nothing yet...</p>
</body>
</html>
PHP
#!/usr/bin/php
<?php
$username = 'USERNAME#gmail.com';
$password = 'PASSWORD';
$loginUrl = 'https://create.kahoot.it/rest/authenticate';
$kahootId = htmlentities($_GET['quizid']);
$pageUrl = 'https://create.kahoot.it/rest/kahoots/' . $kahootId;
$loginheader = array();
$loginheader[] = 'content-type: application/json';
$loginpost = new stdClass();
$loginpost->username = $username;
$loginpost->password = $password;
$loginpost->grant_type = "password";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $loginUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($loginpost));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,$loginheader);
$store = curl_exec($ch);
curl_close($ch);
$token = json_decode($store,true)["access_token"];
//get questions
$quizheader = array();
$quizheader[] = 'authorization: ' . $token;
$options = array(
'http' => array(
'method' => 'GET',
'header' => "Authorization: ".$token."\r\n"
)
);
$context = stream_context_create($options);
$raw_result = file_get_contents($pageUrl, false, $context);
$result = json_decode($raw_result,true)["questions"];
$myoutput = $_POST['output'];
header( "Location: website.html?output=$myoutput" );
print_r($result)
?>
From the GitHub Pages documentation: https://help.github.com/articles/what-is-github-pages/:
GitHub Pages is a static site hosting service and doesn't support server-side code such as, PHP, Ruby, or Python.
Related
I'm trying to run CURL command in PHP to upload image to an API
the code mentioned in the doc was:
curl -u 15:tokenkeyiskmzwa8awaa https://api.bukalapak.com/v2/images.json -F file=#product-image.png -X POST
Have tried using mac terminal running this curl command (with proper username and password) and successfully got the result as it is uploading, however was not successfully doing it on PHP.
My php code is :
<?php
$data = array('file'=> '#'.$imagePath );
// this is an absolute path, give something like D://folder/path/on/my/webserver/image.jpg
$user = '1234567';
$pass = '123456';
$ch = curl_init();
$curl_options[CURLOPT_URL] = 'https://api.bukalapak.com/v2/images.json';
$curl_options[CURLOPT_CAINFO] = storage_path('app/cacert.pem');
$curl_options[CURLOPT_HEADER] = "Content-Type: application/x-www-form-urlencoded";
$curl_options[CURLOPT_POST] = 1;
$curl_options[CURLOPT_USERPWD] = $user.':'.$pass;
$curl_options[CURLOPT_POSTFIELDS] = http_build_query($data);
curl_setopt_array($ch, $curl_options);
$content = curl_exec($->ch);`
Curl version : 7.47.1
PHP version : 5.6.21
any feedback is very appreciated.
You did not posted the complete script: $curl_options is undefined, storage_path is related to Laravel but there is no import, etc.
Something like the following script should work as you expect (I didn't tested it since I don't have an account on this service):
<?php
$imagePath = 'path/to/your/image.ext';
$user = 'youruser';
$pass = 'yourpass';
$file = curl_file_create($imagePath);
$body = ['file' => $file];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.bukalapak.com/v2/images.json');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, $user.':'.$pass);
curl_setopt($ch, CURLOPT_CAINFO, 'path/to/cacert.pem');
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
$result = curl_exec($ch);
curl_close($ch);
EDIT: For the solution, view reply from Barmar below. Hope this helps anyone with a similar problem.
I'm trying to take a login from my test.php file and cURL it to a site which uses the data to simulate a login on another page (I know this is tedious, but this isn't the full extent of what I'm doing as a whole, just where I have the problem). So I post an encoded json to the index.php url which has no problem decoding it. The information passed is then used and the decoded json is edited to show successful or unsuccessful login. The json is then encoded once again and echoed onto the page and held in $contents on test.php. When I try to decode it on this file I get NULL everytime. I've tried a ton of things and am just starting to think I made a stupid mistake somewhere so I'm desperately looking for any help here.
-If I echo $contents it shows:
{"user":"user","pass":"password","success":true}
-If I var_dump(trim($contents)) it shows (formatted exactly as shown):
string(364) "
{"user":"user","pass":"password","success":true} "
-last_json_error_msg shows:
SYNTAX ERROR
-I've tried trimming, utfencoding, iconv, setting curl headers and literally everything I've seen recommended on other posts here.
Any help at all would be greatly appreciated. Thanks in advance guys.
test.php:
<html>
<head>
<meta charset="UTF-8">
<title>TITLE</title>
</head>
<body>
<form action="test.php" method=POST>
<input type="text" name="user">
<input type="password" name="pass">
<input type="submit" value="Submit">
</form>
<?php
function logInfo(){
class data{
public $user = "";
public $pass = "";
public $success = false;
}
$data = new data();
$data->user = $_POST['user'];
$data->pass = $_POST['pass'];
$ch = curl_init();
$json = json_encode($data);
curl_setopt($ch, CURLOPT_URL, [URL TO INDEX.PHP]);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array("data"=>$json));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$contents = curl_exec($ch);
curl_close($ch);
$array = json_decode($contents, true);
var_dump($array);
//VAR_DUMP SHOWS NULL
}
if(isset($_POST['user']) && isset($_POST['pass'])){
logInfo();
}
?>
</body>
</html>
index.php:
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="test.php" method=POST>
<input type="hidden" name="data">
</form>
<?php
header('Context-type: application/json');
function logInfo(){
$datastring = $_POST['data'];
$data = json_decode($datastring);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, [URL TO SIMULATE LOGIN]);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, [LOGIN POST]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($code == [SUCCESSFUL LOGIN HTTP CODE]){
$data->success = true;
} else {
$data->success = false;
}
echo json_encode($data);
curl_close ($ch);
}
if(isset($_POST['data'])){
logInfo();
}
?>
</body>
</html>
EDIT: For the solution, view reply from Barmar below. Hope this helps anyone with a similar problem.
index.php is printing HTML before the JSON (weren't you suspicious when var_dump() said that the string is 365 characters long, but you can only see about 50?). When the script is being used to return JSON, it can't produce any other output.
So check for the data parameter before printing any output. And if it's found, exit the script after sending the JSON, so you don't print the HTML.
<?php
if(isset($_POST['data'])){
logInfo();
exit();
}
?>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="test.php" method=POST>
<input type="hidden" name="data">
</form>
<?php
</body>
</html>
<?php
function logInfo(){
header('Context-type: application/json');
$datastring = $_POST['data'];
$data = json_decode($datastring);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, [URL TO SIMULATE LOGIN]);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, [LOGIN POST]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($code == [SUCCESSFUL LOGIN HTTP CODE]){
$data->success = true;
} else {
$data->success = false;
}
echo json_encode($data);
curl_close ($ch);
}
A simpler solution would probably be to put the code that returns logInfo() into a different script.
You should do
json_encode(get_object_vars($data));
in logInfo function
A couple of things I would recommend. It's not a good practice to define a class inside a function. You should have your class in a separate file. It helps keep your code organised.
Secondly, its good to follow either snake case or camel case for defining classes / methods / functions etc.
Snake case eg: my_function_name_to_execute
Camel case eg: MyFunctionNameToExecute
Try to check resulting JSON syntax using this library https://github.com/Seldaek/jsonlint
UPDATE
It correctly detects extra HTML from index.php and other possible problems.
Following example
use Seld\JsonLint\JsonParser;
$parser = new JsonParser();
$exception = $parser->lint('<html>{"user":"user","pass":"password","success":true}');
echo $exception->getMessage();
will output:
Parse error on line 1:
<html>{"user":"user"
^
Expected one of: 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['
I'm running the XML to PHP install of paid Google site search.
https://code.google.com/p/google-csbe-example/downloads/detail?name=gss.php&can=2&q=
My initial implementation runs perfectly on a LAMP server, however I now have to run a PHP environment on the Windows Azure Platform.
It appears as though the $url variable is not being passed through cURL, as the $result varaible returns as NULL.
$url = 'https://www.google.com/cse?cx=' . $your_cx_number . '&client=google-csbe&output=xml_no_dtd&q=' . $q;
if(isset($start)){
$url .= '&start=' . $start;
}
If i modify the value of $url to a different remote xml file, with a little adjustment to the output structure, I get the expected results.
I have tried several different troubleshooting steps including:
cURL: alternate xml feed renders
simplexml: alternate rss feed renders
permissions: site permissions aren't required google cse dashboard
alternate azure site: tested and failed
alternate LAMP hosted site: tested and success
alternate search setup: this had no effect
is the domain blocked to google: don't think so
url queries blocked: not sure if this is causing any issues
I'm stumped.
Any help would be greatly appreciated.
Thanks!
Here's the full code (minus the cx number):
<?php
//ini_set('display_startup_errors',1);
//ini_set('display_errors',1);
//error_reporting(-1);
$q = $_GET['q'];
$q = urlencode($q);
//WRAPPED IN A IF STATEMENT SO PROMOTED RESULTS SHOW UP ON THE FIRST PAGE
if(isset($_GET['start'])){
$start = $_GET['start'];
}
$your_cx_number = 'enter_your_paid_google_site_search_cx_number';
$url = 'https://www.google.com/cse?cx=' . $your_cx_number . '&client=google-csbe&output=xml_no_dtd&q=' . $q;
if(isset($start)){
$url .= '&start=' . $start;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);// allow redirects
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return into a variable
curl_setopt($ch, CURLOPT_TIMEOUT, 30); // times out after 30s
curl_setopt($ch, CURLOPT_HTTPGET, true); // set POST method
//curl_setopt($ch, CURLOPT_POSTFIELDS, "postparam1=postvalue"); // add POST fields
//submit the xml request and get the response
$result = curl_exec($ch);
curl_close($ch);
//now parse the xml with
$xml = simplexml_load_string($result);
$START = $xml->RES['SN'];
$END = $xml->RES['EN'];
$RESULTS = $xml->RES->M;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Search results</title>
</head>
<body>
<form action="search-test.php" id="searchform" >
<input type="text" name="q" placeholder="Search..." <?php if(isset($_GET['q'])) { echo 'value="' . $_GET['q'] . '"' ; }?> id="search-text" size="25" autocomplete="off" />
<input type="submit" id="search-button" title="Search" value="" />
</form>
<p>The url of the XML output</p>
<?php
//extract the title, link and snippet for each result
if ($xml->RES->R) {
foreach ($xml->RES->R as $item) {
$title = $item->T;
$link = $item->U;
$snippet = $item->S;
echo '<h3>' . $title . '</h3>
<p>' . $title . '</p>
<p>' . $snippet . '</p>
<hr />';
}
}
?>
</body>
</html>
cURL error reporting returned an error code : 60
Curl error: 60 - SSL certificate problem: unable to get local issuer certificate
A search for a similar error provided the solution
HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK
Add in the line:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
The full cURL function is now:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);// allow redirects
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return into a variable
curl_setopt($ch, CURLOPT_TIMEOUT, 30); // times out after 30s
curl_setopt($ch, CURLOPT_HTTPGET, true); // set POST method
$result = curl_exec($ch);
if(curl_errno($ch)){
echo 'Curl error: ' . curl_errno($ch) . ' - ' .curl_error($ch);
$info = curl_getinfo($ch);
if (empty($info['http_code'])) {
die("No HTTP code was returned");
} else {
echo $info['http_code'];
}
}
curl_close($ch);
Microsoft's own PHP example for new Bing API doesn't work. I tried in many ways, it just shows:
Server Error
401 - Unauthorized: Access is denied due to invalid credentials.
You do not have permission to view this directory or page
using the credentials that you supplied.
Example Coding given in the official documentation is below, it breaks up at
'proxy' => 'tcp://127.0.0.1:8888',
I am 100% sure my key is correct, and when I just enter it in the browser url it works fine, i.e
https://api.datamarket.azure.com/Bing/SearchWeb/Web?Query=%27love+message%27
(you need to put the API key as your password and username can be anything)
<html>
<head>
<link href="styles.css" rel="stylesheet" type="text/css" />
<title>PHP Bing</title>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Type in a search:
<input type="text" id="searchText" name="searchText"
value="<?php
if (isset($_POST['searchText']))
{
echo($_POST['searchText']);
}
else
{
echo('sushi');
}
?>"
/>
<input type="submit" value="Search!" name="submit" id="searchButton" />
<?php
if (isset($_POST['submit']))
{
// Replace this value with your account key
$accountKey = 'BKqC2hIKr8foem2E1qiRvB5ttBQJK8objH8kZE/WJVs=';
$ServiceRootURL = 'https://api.datamarket.azure.com/Bing/Search/';
$WebSearchURL = $ServiceRootURL . 'Image?$format=json&Query=';
$context = stream_context_create(array(
'http' => array(
//'proxy' => 'tcp://127.0.0.1:8888',
'request_fulluri' => true,
'header' => "Authorization: Basic " . base64_encode($accountKey . ":" . $accountKey)
)
));
$request = $WebSearchURL . urlencode( '\'' . $_POST["searchText"] . '\'');
echo($request);
$response = file_get_contents($request, 0, $context);
print_r($response);
$jsonobj = json_decode($response);
echo('<ul ID="resultList">');
foreach($jsonobj->d->results as $value)
{
echo('<li class="resultlistitem"><a href="' . $value->MediaURL . '">');
echo('<img src="' . $value->Thumbnail->MediaUrl. '"></li>');
}
echo("</ul>");
}
?>
</form>
</body>
</html>
I have tried both google API and Yahoo API both, none of those were as difficult as this.
after days of argument with microsoft techinchal support they accpeted that it didnt work
here is the proper coding which uses CURL do this in the BING API, apply CURL method instead of the file_get_contents which can’t pass the correct authentication information from Linux client to BING service.
<html>
<head>
<title>PHP Bing</title>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Type in a search:
<input type="text" id="searchText" name="searchText"
value="<?php
if (isset($_POST['searchText']))
{
echo($_POST['searchText']);
}
else
{
echo('sushi');
}
?>"
/>
<input type="submit" value="Search!" name="submit" id="searchButton" />
<?php
if (isset($_POST['submit']))
{
$credentials = "username:xxx";
$url= "https://api.datamarket.azure.com/Bing/SearchWeb/Web?Query=%27{keyword}%27";
$url=str_replace('{keyword}', urlencode($_POST["searchText"]), $url);
$ch = curl_init();
$headers = array(
"Authorization: Basic " . base64_encode($credentials)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$rs = curl_exec($ch);
echo($rs);
curl_close($ch);
return $rs;
}
?>
</form>
</body>
</html>
I had to add
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
in order to make it work, at least in my local copy (WAMP).
Hope it helps, I have been messing with this all the day.
$WebSearchURL = $ServiceRootURL . 'Image?$format=json&Query=';
This is part of the prob
This wont give the url bing is looking for
e.g. https://api.datamarket.azure.com/Bing/SearchWeb/Web?Query=%27love+message%27
it would be
https://api.datamarket.azure.com/Bing/Search/Image?$format=json&Query=%27love+message%27
whereas you want a web not an image search and also format and other parameters shld be after the query
"image" should be "web"
I just spent 3 days trying to get this to work.
I've just posted an example of how to connect to Bing/Azure API using Unirest Library here: https://stackoverflow.com/a/20096151/257815
Is there any example code of importing contacts from Hotmail/Live mail using their API in PHP?
Thanks.
I suggest you taking a look at Windows Live Contacts for PHP and their simplest example:
<?php
// COPIED FROM http://livecontactsphp.codeplex.com/SourceControl/changeset/view/6336#150263
// Example of how to use the library -- contents put in $ret_array
include "contacts_fn.php";
$ret_array = get_people_array();
//to see a array dump...
var_dump($ret_array);
?>
I haven't used that myself, but it looks like thing you are after.
Yes Here is the complete code.
A)- Create a Live.com application in “Microsoft account Developer Center” for obtaining your Client ID and Client Secret.
1)- create a login.php page and paste the following code in it.
<?php
session_start();
$client_id = 'YOUR CLIENT ID';
$client_secret = 'YOUR CLIENT SECRETE';
$redirect_uri = 'http://example.com/callback.php';
$urls_ = 'https://login.live.com /oauth20_authorize.srf?client_id='.$client_id.'&scope=wl.signin%20wl.basic%20wl.emails%20wl.contacts_emails&response_type=code&redirect_uri='.$redirect_uri;
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Import Hotmail Contacts</title>
</head>
<body>
<?php echo 'Contact From MSN/Hotmail/outlook';?>
</body>
</html>
2) - Now create index.php or callback.php //it will be used as redirected page.
<?php
//function for parsing the curl request
function curl_file_get_contents($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$client_id = 'YOUR CLIENT ID';
$client_secret = 'YOUR CLIENT SECRET';
$redirect_uri = 'http://example.com/callback.php';
$auth_code = $_GET["code"];
$fields=array(
'code'=> urlencode($auth_code),
'client_id'=> urlencode($client_id),
'client_secret'=> urlencode($client_secret),
'redirect_uri'=> urlencode($redirect_uri),
'grant_type'=> urlencode('authorization_code')
);
$post = '';
foreach($fields as $key=>$value) { $post .= $key.'='.$value.'&'; }
$post = rtrim($post,'&');
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,'https://login.live.com/oauth20_token.srf');
curl_setopt($curl,CURLOPT_POST,5);
curl_setopt($curl,CURLOPT_POSTFIELDS,$post);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
$result = curl_exec($curl);
curl_close($curl);
$response = json_decode($result);
$accesstoken = $response->access_token;
$url = 'https://apis.live.net/v5.0/me/contacts?access_token='.$accesstoken.'&limit=2';
$xmlresponse = curl_file_get_contents($url);
$xml = json_decode($xmlresponse, true);
$msn_email = "";
foreach($xml['data'] as $emails)
{
// echo $emails['name'];
$email_ids = implode(",",array_unique($emails['emails']));
$msn_email .= "<div><span>".$emails['name']."</span>=> <span>". rtrim($email_ids,",")."</span></div>";
}
echo $msn_email;
?>