PHP Put variables in Session doesn't work - php

I created a php page that receive in input a string that is an encoded Json, i must decript this string and put all Json attributes in session.
This page is login.php.
To test this page i created another page named test.php.
In this page i encript a Json and sent it to login.php.
The problem is that all works fine (encription, sending, decription) but the variables is not saved in session.
I tried to open directly login.php, i set a fixed encripted json and in this case all works fine.
Some help???
login.php
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TantoSvago</title>
<script src="../vendors/jquery/jquery-2.1.4.min.js"></script>
<script src="../js/angular.min.js"></script>
<script src="../js/ui-bootstrap-tpls-0.12.0.js"></script>
<script src="../js/angular-google-maps.min.js"></script>
<script src="https://code.angularjs.org/1.2.28/angular-route.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBze9qLOsDpAWj8938CYJSVsopwrkuWbPA&callback=initMap"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular-sanitize.js"></script>
<script src="../js/markerclusterer.js"></script>
<script src="../js/angular.rangeSlider.js"></script>
<script src="../js/assets/app.js"></script>
</head>
<body ng-app="tantoSvagoApp">
<?php
session_start();
include 'AES.php';
$inputText = file_get_contents("php://input");
//$inputText = "RFk0ZGRtZWQ0NUdrNzNHa3BtYVBCdklEYUlUMk5CUUdGMUF5V2tFSHVWRTRsUEtYZTRiL1FmVGNsY2pKZHdIb2lkOG1ra3BMODdPZUVuUmQzN3Vqd1JpamZGRmloeW1EU09xVFMzbU1Jd1Z0N1dNZzF6MitDYWlHZ3p6VUVyRXgycDYrbHU1Tm0yYVQ4amNuK0hheUNyODErSXZqMzVIQm9NdCtOQU0vVTcyMVBUQ09YQmRZTWZkM1JsbHk0aVJJaFFJdUYrR0JWZzF5WG1HUXl6QnFEa0d0V2ozNWl2YmhheGp6UkpXSVRFZDh4TXM3Q2Vyb2liQWp1UmJEZXNvYnFWNmkzc3ZzWEp4ak92MjB0ZWpjYWJGOFVoMEw0Vk8rNTI2WXhoMTRvYW89";
$inputText = base64_decode($inputText);
$inputKey = "466169626f20536f74662052756c657a";
$blockSize = 256;
$aes = new AES($inputText, $inputKey, $blockSize);
$enc = $aes->decrypt();
$inputJson = json_decode($enc);
$email = $inputJson->{'email'};
$firstName = $inputJson->{'firstName'};
$lastName = $inputJson->{'lastName'};
$phone = $inputJson->{'phone'};
$credit = $inputJson->{'credit'};
$userId = $inputJson->{'userId'};
$supportPhone = $inputJson->{'supportPhone'};
$supportMail = $inputJson->{'supportMail'};
$paymentTypes = $inputJson->{'paymentTypes'};
if (isset($email)) {
$_SESSION['email'] = $email;
}
if (isset($firstName)) {
$_SESSION['firstName'] = $firstName;
}
if (isset($lastName)) {
$_SESSION['lastName'] = $lastName;
}
if (isset($phone)) {
$_SESSION['phone'] = $phone;
}
if (isset($credit)) {
$_SESSION['credit'] = $credit;
}
if (isset($userId)) {
$_SESSION['userId'] = $userId;
}
if (isset($supportPhone)) {
$_SESSION['supportPhone'] = $supportPhone;
}
if (isset($supportMail)) {
$_SESSION['supportMail'] = $supportMail;
}
if (isset($paymentTypes)) {
$_SESSION['paymentTypes'] = $paymentTypes;
}else{
$_SESSION['paymentTypes'] = 'welfare';
}
echo 'ok';
?>
<div ng-controller="loginController"></div>
</body>
</html>
test.php
<?php
$inputText = '{"firstName":"Mario","lastName":"Rossi","email":"mario.rossi#gmail.com","phone":"02 342522","userId":2,"credit":30,"paymentTypes":"welfare","supportMail":"supporto#welfarebit.it","supportPhone":"0321 444999"}';
include 'AES.php';
$inputKey = "466169626f20536f74662052756c657a";
$blockSize = 256;
$aes = new AES($inputText, $inputKey, $blockSize);
$enc = $aes->encrypt();
$result = base64_encode($enc);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://welfarebitexperience.tantosvago.it/login/login.php');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $result );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($result))
);
$result = curl_exec($ch);
curl_close($ch);
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body onload="test()">
<form id="B2BKv" name="B2BKv" action="http://welfarebitexperience.tantosvago.it/login/login.php" method="POST">
<input type="hidden" id="MPCookieManager" name="MPCookieManager" value="<?php echo $result; ?>">
</form>
<script language="javascript">
function test() {
document.B2BKv.submit();
}
</script>
</body>
</html>

Try and put session_start() before the html tag on every page
<?php
session_start();?>
<html>
<head>
and this
<?php
session_start();
$inputText = '{"firstName":"Mario","lastName":"Rossi","email":"mario.rossi#gmail.com","phone":"02 342522","userId":2,"credit":30,"paymentTypes":"welfare","supportMail":"supporto#welfarebit.it","supportPhone":"0321 444999"}';
include 'AES.php';
$inputKey = "466169626f20536f74662052756c657a";

As described over here, session_start() needs to be executed before any content gets returned.

What strikes me from the start is where session_start() is called. PHP manual states: to use cookie-based sessions, session_start() must be called before outputting anything to the browser.

Related

Attempting to stimulate page to produce server sent event with POST data from another page not working

When I open update.php on its own (with self supplied test vars), it sends the SSE to testsse.php just fine and there are no issues (Everything I need to be printed is showing up in inspect element), However, I am trying to have POST data from another page (In this case mootssetest.php) get received by update.php so it may send out the SSE containing the data. I am not sure what I am doing wrong, but this test rig is not working. Guidance would be appreciated.
testsse.php (front end page meant to receive SSE and print)
<!DOCTYPE html>
<html lang="en">
<head>
<title>Using Server-Sent Events</title>
<script>
window.onload = function() {
var link = new EventSource("update.php");
var antispam;
var inputthing = event.data;
var splitted;
link.onmessage = function(event) {
inputthing = event.data;
splitted = inputthing.split(" ");
if (splitted[0] != antispam && splitted[1] == <?php echo $page; ?>) {
document.getElementById("livemsg").innerHTML += "<div id=\"post-" + splitted[0] + "\" class=\"reply\">" + "</div>";
antispam = splitted[0];
};
};
};
</script>
</head>
<body>
<div id="livemsg">
<!--Server response will be inserted here-->
</div>
</body>
</html>
update.php (SSE sender, post receiver)
<?php
$data = json_decode(file_get_contents('php://input'), true);
$postnum = $data[0];
$bread = $data[1];
postnum = 32;
bread = 4;
function liveupdate($postnum, $bread)
{
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
echo "data: " . $postnum . " " . $bread . "\n\n";
flush();
}
liveupdate($postnum, $bread);
?>
mootssetest.php (POST sender)
function httppost($postnum, $bread)
{
$url = "http://localhost/update.php";
$data = array($postnum, $bread);
$curl = curl_init($url);
$jsondata = json_encode($data);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $jsondata );
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
httppost(420, 4);
?>
(For context, I am trying to have this print a new post in some forum software every time a function is called without refreshing the page for the user)
you haven't included the event in your window.onload() function, please fix it first and try again.

Create an php form and make an api request

I have to create an simple form:
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML page</title>
</head>
<body>
<form method="post" action="process.php">
<input type="text" name="firstname" placeholder="rahul_sharma">
<button type="submit">send</button>
</form>
</body>
</html>
From my process.php file, I have to hit an url like below:
https://stackoverflow.com/api?rahul_sharma
which will give back an json response
{"status":"Success","username":"your username is RAHULSHARMA"}
If status is success, have to display the username value.
New to php.Any help is appreciated.
you can call API using curl.
$url='https://stackoverflow.com/api?';
$call_url = $url . $_POST['first_name'] ;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $call_url,
CURLOPT_SSL_VERIFYPEER => false,
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;//{"status":"Success","username":"your username is RAHULSHARMA"}
In your process.php file, you can use the $_POST superglobal to fetch the form data.
$firstname = $_POST['firstname'];
After that you can concatenate it using the . operator to form the url.
$url = "https://your-api-site.com/api?" . $firstname;
Next you can fetch the content from the url using a curl request.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
The result from fetching the url will be obtained in the $output variable. Suppose the result from your API is a JSON string like the one you provided, you can use json_decode PHP function to convert it to an associative array.
$result = json_decode($output);
Now you can use if conditions to check if status is Success and display the username.
if ($result['status'] == "Success") {
echo $result['username'];
}

what should i do for get all http links in cURL

I created a program in php using CURL, in which i can take data of any site and can display it in the browser. Another part of the program is that the data can be saved in the file using file handling and after saving this data, I can find all the http links within the body tag of the saved file. My code is showing all the sites in the browser which I took, but I can not find all http links
Kindly help me out this problem.
PHP Code:
<!DOCTYPE html>
<html>
<head>
<title>Display links using Curl</title>
</head>
<body>
<?php
$GetData = curl_init();
$url = "http://www.ucertify.com/";
curl_setopt($GetData, CURLOPT_URL, $url);
curl_setopt($GetData, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($GetData);
curl_close($GetData);
$file=fopen("content.txt","w");
fputs($file,$data);
fclose($file);
echo $data;
function links() {
$file_content = file_get_contents("http://www.ucertify.com/");
$dom_obj = new DOMDocument();
#$dom_obj->loadHTML($file_content);
$xpath = new DOMXPath($dom_obj);
$links_href = $xpath->evaluate("/html/body//a");
for ($i = 0; $i<$links_href->length; $i++) {
$href = $links_href->item($i);
$url = $href->getAttribute("href");
if(strstr($url,"#")||strstr($url,"javascript:void(0)")||$url=="javascript:;"||$url=="javascript:"){}
else {
echo "<div>".$url."<div/>";
}
}
}
echo links();
?>
</body>
</html>
You can use regex like this
preg_match("/<body[^>]*>(.*?)<\/body>/is", $file_data, $body_content);
preg_match_all("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$body_content[1],$matches);
foreach($matches[0] as $d) {
echo $d."<br>";
}

PHP Google Contact API generateing HTTP/1.0 401 Authorization required

I am using Google Contact API V3 with OAuth 2.0 to retrieve the contacts from Google Account, I am getting a OAuth Token from a child window using jQuery, and after post that token to another file which should get the User's Contacts, but when I pass the token to get the contacts from Google, but it gives an error "Warning: file_get_contents(https://www.google.com/m8/feeds/contacts/default/full&oauth_token=[token]) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 401 Authorization required in ...\getContacts.php on line 7"
Here is my code for reference:
In my index.php:
<!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" />
<script src="js/jquery-1.8.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
var windowSizeArray = [ "width=200,height=200",
"width=300,height=400,scrollbars=yes" ];
$(document).ready(function(){
$('#newWindow').click(function (event){
var url = $(this).attr("href");
var windowName = "popUp";//$(this).attr("name");
var windowSize = windowSizeArray[ $(this).attr("rel") ];
window.open(url, windowName, windowSize);
event.preventDefault();
});
});
function getContacts(accessToken){
$.post("getContacts.php?token="+accessToken,function(data){
$("#contacts").html(data);
});
}
</script>
</head>
<body>
Click Here! to import your contact.
<div id="contacts"></div>
in my childWindow.php:
<!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" />
<script type="text/javascript" src="js/jquery-1.8.1.min.js"></script>
</head>
<body>
<?php
$authcode= $_GET["code"];
$clientid='My Client ID';
$clientsecret='My Client Secret';
$redirecturi='http://localhost/googleContacts/validate.php';
$fields=array(
'code'=> urlencode($authcode),
'client_id'=> urlencode($clientid),
'client_secret'=> urlencode($clientsecret),
'redirect_uri'=> urlencode($redirecturi),
'grant_type'=> urlencode('authorization_code')
);
//url-ify the data for the POST
$fields_string='';
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
$fields_string=rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,'https://accounts.google.com/o/oauth2/token');
curl_setopt($ch,CURLOPT_POST,5);
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//to trust any ssl certificates
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
//extracting access_token from response string
$response= json_decode($result);
$accesstoken= $response->access_token;
//echo "<span>".$accesstoken."</span><hr>";
?>
<script type="text/javascript">
$(document).ready(function() {
window.opener.getContacts("<?php echo $accesstoken; ?>");
window.close();
});
</script>
And finally in my getContacts.php:
<?php
$accesstoken = $_REQUEST['token'];
//passing accesstoken to obtain contact details
$xmlresponse= file_get_contents('https://www.google.com/m8/feeds/contacts/default/full&oauth_token='.$accesstoken);
//reading xml using SimpleXML
$xml= new SimpleXMLElement($xmlresponse);
foreach($xml->entry as $content){
$nameEmail = "";
if(!empty($content->title)){
$nameEmail .= "<span style=\"text-decoration:underline;\">".$content->title."</span>: ";
}
$gd = $content->children('http://schemas.google.com/g/2005');
if($gd){
$nameEmail .= $gd->attributes()->address."<hr>";
echo $nameEmail;
}else{
echo $nameEmail."<hr>";
}
}
?>
Please tell me where is the mistake. Thanks in advance
To allow https for file_get_contents() you should have enabled the php extension php_openssl.dll.
Make sure that in your php.ini you have this lines:
extension=php_openssl.dll
allow_url_fopen = On

Warning when retrieving Metadata from remote webpage

I am getting these two errors when retrieving meta data from a remote webpage. Is this an escaping issue or maybe a cURL issue?
Warning: get_meta_tags(<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://...#import url( "http://www.zymic.com/forum/style_images/v6/folder_editor_images/css_rte.css" ); </style> </head> <body> <div id="ipbwrapper"> <!--ipb.javascript.start--> <script type="text/javascript"> //<![CDATA[ var ipb_var_st = "0"; var ipb_lang_tpl_q1 = "Please enter a page number to jump to between 1 and"; var ipb_var_s = "f2e0d2b492f248ec27ef34ae291a1db4"; var ipb_var_phpext = "php"; var ipb_var_base_url = "http://www.zymic.com/forum/index.php?s=f2e0d2b492f248ec27ef34ae291a1db4&"; var ipb_var_image_url = "style_images/v6"; var ipb_input_f = "34"; var ipb_input_t = "5188"; var ipb_input_p = ""; var ipb_var_cookieid
= ""; var ipb_var_cookie_ in public_html/list/main/output.php on line 22 retrieve pagetitle Warning: file_get_contents(<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://...#import url( "http://www.zymic.com/forum/style_images/v6/folder_editor_images/css_rte.css" ); </style> </head> <body> <div id="ipbwrapper"> <!--ipb.javascript.start--> <script type="text/javascript"> //<![CDATA[ var ipb_var_st = "0"; var ipb_lang_tpl_q1 = "Please enter a page number to jump to between 1 and"; var ipb_var_s = "f2e0d2b492f248ec27ef34ae291a1db4"; var ipb_var_phpext = "php"; var ipb_var_base_url = "http://www.zymic.com/forum/index.php?s=f2e0d2b492f248ec27ef34ae291a1db4&"; var ipb_var_image_url = "style_images/v6"; var ipb_input_f = "34"; var ipb_input_t = "5188"; var ipb_input_p = ""; var ipb_var_cookieid
= ""; var ipb_var_coo in /public_html/list/main/output.php on line 27
Here is the code:
////Use Curl Library to get page content for security
$url = 'http://en.wikipedia.org/wiki/Category:Lists_of_lists';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl, CURLOPT_USERAGENT, 'ListBot 1.0: Used for compiling a DB of lists across the internet.');
$str = curl_exec($curl);
curl_close($curl);
//get metadata
$tags = get_meta_tags($str);
//Get page title
function get_page_title($str){
if( !($data = file_get_contents($str)) ) return false;
if( preg_match("#<title>(.+)<\/title>#iU", $data, $t)) {
return trim($t[1]);
} else {
return false;
}
}
///////////
echo('retrieve pagetitle');
$tags['title'] = get_page_title($str);
get_meta_tags expects a file location (commonly a url).
You could request the url directly and parse the headers, but you'd probably get better results doing a regular expression match on the string you retrieved with curl.
You have a nice bit of code that grabs the title. Simply modify that to grab all the meta tags.
In the php.net page describing "get_meta_tags()" jstel at 126 dot com contributed this nice function call:
preg_match_all("/<meta[^>]+(http-equiv|name)=\"([^\"])\"[^>]" . "+content=\"([^\"])\"[^>]*>/i", $v, $split_content[], PREG_PATTERN_ORDER);
Which will search string $v for meta data and dump matches into $split_content. In his sample he does a bunch of looping that seems unneeded, but I'd suggest looking at his code and seeing if you can adapt it.

Categories