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).
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>";
}
?>
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)
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.