launch website url with array when value is empty - php

I am trying to make a little search game and i am creating a command line that opens websites in a iframe, in the middle of the page (i didn't add this iframe yet to the page). I must say that the command line field is also in an iframe.
You can see and test the page here: http://www.josdenhertog.nl/tnes/getin.php
Now the problem:
When you just use your mouse and just press it so that you see the cursor at the start in the text field and you press ENTER on your keyboard without typing any command in this line, then it goes black on the iframe and do not load anything.
This is the code what i have so far:
$urlList = array ('test' => 'commandline.php',
' ' => 'commandline.php',
' ' => 'commandline.php'
);
if (isset ($_POST['command']) && strlen($_POST['command']) > 0) {
# See if the command provided by the user exists in the list.
if (array_key_exists ($_POST['command'], $urlList)) {
#When Command exist.
header ("Location: " . $urlList[$_POST['command']]);
}
else {
# Command not found
header ("Location: commandline.php");
}
}
My question is now:
How do i make that when you press only ENTER without typing anything in the command line, load up ONLY the commandline.php webpage. Like that array variable: $urlList
I am terrible when it comes on questions, hopefully you understand what i mean :)

You need another else at the very end presumably. This will redirect back to commandline.php when $_POST['command'] is not set, or strlen() is <=0.
$urlList = array ('test' => 'commandline.php',
' ' => 'commandline.php',
' ' => 'commandline.php'
);
if (isset ($_POST['command']) && strlen($_POST['command']) > 0) {
# See if the command provided by the user exists in the list.
if (array_key_exists ($_POST['command'], $urlList)) {
#When Command exist.
header ("Location: " . $urlList[$_POST['command']]);
}
else {
# Command not found
header ("Location: commandline.php");
}
} else {
header ("Location: commandline.php");
}
die();

Add this to the end of the code shown above, all you need is an else statement since your check for command string length and isset are the ones behind your issue:
else {
header ("Location: commandline.php");
}

Related

My php script outputs a blank page

I have a php page that accepts and processes a form submission, the page displays normally when it is requested, however if the page is submitted and its form validation fails, the page suppose to be re-displayed with the form errors, but on page re-display, php displays a blank page when it reaches the error processing block. Here is the code that processes the validation errors:
<?php if(isset($errorLog) and is_array($errorLog)): ?>
<div class="alert alert-danger">
<?php $output = '';
if($errorLog['message'] == '') {
$output = "<ul class='error-list'>";
foreach($errorLog as $key => $value) {
if ($key != 'has_error_occured') {
$output .= "<li><strong>{html($key)}</strong>
<span>{html($value)} </span></li>";
}
}
$output .= "</ul>";
} else {
$msg = $errorLog['message'];
$output .= "<p>{html($msg)}</p>";
}
echo $output;
?>
</div>
<?php endif; ?>
and here is the code that processes the form submission
if(isset($_GET['transfer']) or
(isset($_POST['action']) and $_POST['action'] == TRANSFER)){
$transfer_type = $_GET['ttype'];
if(isset($_POST['action']) and
$_POST['action'] == TRANSFER){
//process money transfer.
$log = process_transfer();
if(isset($log) and is_array($log)){
if($log['has_error_occured']){
$_SESSION['error_log'] = $log;
//unset log
unset($log);
include_once $docRoot . '/users/temp/tranfer.html.php';
exit();
}else{
$_SESSION['transfer_msg'] = "Your international
transfer was processed successfully";
header('Location: ?summary');
}
}
//reload primary page.
header('Location: .');
}else{
include_once $docRoot . '/users/temp/tranfer.html.php';
exit();
}
}
Note:
I have tried passing the error array as a global variable as
you can see in the code snippet above.
I have also tried passing it in a session.
I also have tried using output buffering by appending the ob_start() at the beginning and ob_end_flush() at the end the form script.
I have also added error_reporting(-1); ini_set('display_errors', true); at the start of the form script so as to know if the page encounters any error during processing, all to no avail.
I am using PhpStorm with XAMPP v3.2.1 for development on windows 7.
Please, any help as to the cause of this nightmare will be appreciated. Thanks.
If you wanna use $_GET and $_POST then better use $_REQUEST, it allows to access both $_GET and $_POST
not TRANSFER but it should be "TRANSFER"
if errorlog is session data then it should be
if(isset($_SESSION['errorLog']) and is_array($_SESSION['errorLog'])):
i didn't find any thing created by name message
if($errorLog['message'] == '')
why u used it, i think it must be 'has_error_occured'
I discovered the problem through the output of php_error_log and through the various suggestions in the comments above, the problem problem was that I didn't check if the $erroLog['message'] was set before accessing it. But shouldn't php have outputted a warning instead of resorting to such indeterminate option of not fully executing the rest of the document?

Check redirect source

I have a form to edit an entry, after the user presses the submit button it executes the includes/edit.php?id=XXX script and then redirects using the header('Location: ../index.php'); to the index page where all the entries are being displayed.
On the index page, I want to create a condition:
if the index page is accessed via a redirect from the edit.php?id=XXX page, then show a success message to notify the user that the edit was succesfull.
How should this condition look like?
<?php
require_once('includes/session.php');
require_once('includes/config.php');
if(!isset($_SESSION['login'])){ //if login in session is not set
header("Location: http://www.domain.com/app/login.php");
}
$query = ("SELECT * FROM archive ORDER by id DESC");
$result = mysqli_query($link, $query) or die (mysqli_error());
/*if (condition){
//show success message
}*/
?>
You should take a look at this var :
$_SERVER['HTTP_REFERER'];
As it will return the page from where you come before this one:
So you could just do :
if($_SERVER['HTTP_REFERER'] == "edit.php?id=XXX"){
// your code here
}
you can simply try this :
if(isset($_GET['id']) && !empty($_GET['id']))
{
// your success message
}
If you set a $_SESSION variable with messages you can then display all messages and clear the list afterwards.
Adding a message:
if ( ! isset($_SESSION['messages']) ) {
# initialize messages
$_SESSION['messages'] = [];
}
# Add a new message:
$_SESSION['messages'][] = 'Something was a success!';
Reading messages:
# If there are messages not displayed
if ( isset($_SESSION['messages']) && is_array($_SESSION['messages']) ) {
foreach ( $_SESSION['messages'] as $message ) {
echo $message . '<br>';
}
# Clear messages
unset( $_SESSION['messages'] );
}
The suggested 'HTTP_REFERER' can be manipulated and browsers are not required to send it.
I would suggest to redirect immediately and not execute more code after the location header is set:
if(!isset($_SESSION['login'])){ //if login in session is not set
header("Location: http://www.domain.com/app/login.php");
exit();
}
If $_SESSION['login'] is not set: redirect and exit.
You might consider the rest of the code as one big "else" (= if $_SESSION['login'] is set).
To answer the question from comments: without the exit, the code below will be executed .. and doing that query is not really necessary. Thats why its better to end the program flow by adding an exit. Referencing: Why I have to call 'exit' after redirection through header('Location..') in PHP?
And for the condition you could use $_SERVER['HTTP_REFERER'] or $_GET['id'] to check the page you are coming from. Just compare the strings or parts of them.

Header location works inconsistently on chrome?

So i have this webshop running on a server, it's working fine on every pc i have been able to get my hands on. but for some reason quite often customers still have problems with one header(location ) to a payment site. I checked everything codewise and tried a hundred different ways of breaking the payment link but haven't found one.
I'm assuming it's the header(location: ...) or the fact that it's three in a row (some php only verification pages inbetween) which might give some version trouble but i'm only guessing.
snip out of the index.php
ob_start();
require_once($Content_Path);
$zpfw_page_output = ob_get_contents();
ob_end_clean();
//************************************************
// Include the requested header / footer / etc..
//************************************************
//Here we include the HEADER HTML.
require_once($Config['AbsolutePath'] . '_headers/' . $Config['HeaderFilename']);
//Here we include the PHP PAGE.
echo $zpfw_page_output;
//Here we include the FOOTER HTML.
require_once($Config['AbsolutePath'] . '_footers/' . $Config['FooterFilename']);
The Content page is the only thing that changes ($Content_Path) So the customers puts hit products that he wants to buy in his basket and goes towards checkout, now every post done on our pages go to a posttogethandler to make it seo friendly (the indexpages uses the first 2 parameters (www.google.nl/module/page/test)
to change the content path everything behind that are used as parameters $_Get[Param1] = 'test'
posttogethandler.php:
<?php
if(isset($_POST))
{
include '../../../_bootstrap.php';
if(!empty($_POST['m']) && !empty($_POST['c']))
{
$post_string = '';
foreach($_POST as $key => $postitem)
{
if($key == 'm')
{
}
elseif($key== 'c')
{
}
else
{
$post_string = $post_string.$postitem.'/';
}
}
header('location:'.$Config['AbsoluteURL'].$_POST['m'].'/'.$_POST['c'].'/'.$post_string);
}
}
and for the actual check which creates a mollie payment and sends to person to the payment (again i will shorten it a bit to only containt the code it passes through if nothing is wrong) (No echo commands exist in this file)
<?php
$mollie = new Mollie_API_Client();
$mollie->setApiKey($Config['Mollie']['Api_Key']);
if(!empty($_GET['param1']) && $_GET['param1'] == 'checkout' && !empty($_SESSION['Customer_ID']))
{
/* alot of checks and inserts into mysql database to keep track */
if(!empty($_GET['param3']) && $_GET['param3'] == 'secretcode')
{
//for skipping payment
header('Location: ' . $Config['AbsoluteURL'] . 'account/order/' . $uniqueID);
exit;
}
else
{
$payment = $mollie->payments->create(array(
"amount" => mollieCartPriceIncTaxes($_SESSION['cart'],$_SESSION['Customer_ID'])[0],
"description" => "Payment for ...",
"redirectUrl" => $Config['AbsoluteURL']."account/order/payment/".$uniqueID."",
"webhookUrl" => $Config['AbsoluteURL']."cart/checkout/webhook"
));
$payment = $mollie->payments->get($payment->id);
zp_mysqli_query("Update orders set Order_MollieID = '".$mysqli->real_escape_string($payment->id)."' where Order_ID = '".$mysqli->real_escape_string($uniqueID)."'");
if(!empty($_SESSION['pick_up']))
{
unset($_SESSION['pick_up']);
}
header("Location: " . $payment->getPaymentUrl()."/#");
exit;
}
}
I'll edit it some more in a few hours, need to go now. this is hosted on a server so i've checked for html code being send first but can't find any nor experience any problems with it on any pc i've tried to open the website with.
any pointers would be much appreciated!
EDIT:
It seems to be a problem with redirecting to a page outside of the domain. I'm remaking the page so the button is a direct link to the payment page. This seems to work.

PhP Headers and output buffering

So... if you have a script that states something like so...
while($result = mysql_fetch_array($resource))
{
if($result['TITLE'] == $this->title)
{
header("LOCATION: profile.php?error=11");
}
echo 'testing';
}
//Create the database profile
$second_query = "INSERT INTO profiles(USER_ID, KEYWORDS, TITLE, INTRO) ";
$second_query .= "VALUES(".$this->userId.",'".serialize($this->keywords)."','".$this->title."','".$this->intro."')";
echo $second_query;
if($result = mysql_query($second_query))
{
if(isset($file))
{
$this->update_profile($this->files);
}
return true;
}else
{
return false;
}
and the first condition fails and sends the header back... If you don't return false after sending the header, does it continue running the script? I had an issue to where if the title was found in my database it would return the error, but it would continue running that script, thus inserting a duplicate title entry into my database.
So again... does a script continue executing even after you send a header? aka (in this case) a redirect?
If a location header is sent without an exit yes it continues to run script.
Valid:
header("Location: profile.php?error=11");
die(); // or exit();
Think about that header isn't executed by the PHP itself, it's executed by the browser, same thing when you apply a header("Content-Type: application/force-download"); it tells the browser that the following outputted block has to be downloaded.
So even if you set the header to another location, all code inside script, unless we exit, gets processed by PHP and then the browser gets the location and redirects.
Yes it will ,so exit your script after sending header
header("Location: profile.php?error=11");
exit;

PHP notice - Undefined index on index.php

I'm running into a server notice that doesn't seem to effect the loading of my pages but nonetheless creates a new entry in the error log every time a page is loaded... That error is:
PHP Notice: Undefined index: thing in C:\File Location\htdocs\index.php on line 1
I'm not sure whether the problem is actually on the first line or on a subsequent line, so I included a modified version of the whole file. The weird thing for me is that there's an identical line of code on several other files and it doesn't raise an issue in them. Also, the value is correctly extracted and all is well, I just don't know what to change in order to avoid the notice.
$thingvalue = $_REQUEST['thing'];
include("mdetect.php");
$iphoneTierHomePage = 'mobilemain.php';
$iphoneTierMobilePage = 'mobilepage.php?thing=' . $thingvalue;
$genericMobileDeviceHomePage = 'mobilemain.php';
$genericMobileDeviceMobilePage = 'mobilepage.php?thing=' . $thingvalue;
$line1 = define('WP_USE_THEMES', true);
$line2 = require('./wp-blog-header.php');
$desktopPage == $line1 + $line2;
$uagent_obj = new uagent_info();
function AutoRedirectToProperHomePage()
{
global $thingvalue, $uagent_obj, $iphoneTierHomePage, $genericMobileDeviceHomePage, $iphoneTierMobilePage, $genericMobileDeviceMobilePage, $desktopPage;
if ($thingvalue == ''){
if ($uagent_obj->isTierIphone == $uagent_obj->true)
header ('Location: '.$iphoneTierHomePage);
else if ($uagent_obj->DetectMobileQuick() == $uagent_obj->true)
header ('Location: '.$genericMobileDeviceHomePage);
else
header ('Location: '.$desktopHomePage);
}
if ($thingvalue != ''){
if ($uagent_obj->isTierIphone == $uagent_obj->true)
header ('Location: '.$iphoneTierMobilePage);
else if ($uagent_obj->DetectMobileQuick() == $uagent_obj->true)
header ('Location: '.$genericMobileDeviceMobilePage);
else
header ('Location: '.$desktopPage);
}
}
AutoRedirectToProperHomePage();
It's referring to the array index for the first line in index.php:
Try this:
$thingvalue = empty($_REQUEST['thing']) ? '' : $_REQUEST['thing'];
It is trying to reference the index thing inside the $_REQUEST superglobal. If someone is viewing that page directly and was not posted via a form or directed with a ?thing=foobar in the query string, PHP will show that notice. I'd recommend not using $_REQUEST as it checks both $_GET and $_POST which is not very secure/practical - then check if it is set, and if not, taking some failsave action:
try
{
if(!isset($_POST['thing']))
{
throw new Exception('No direct access. Please use our Contact form');
}
else
{
$thingvalue = $_POST['thing'];
}
}
catch(Exception $e)
{
echo $e->getMessage();
exit();
}
The issue is that you are trying to get the value of thing here
$thingvalue = $_REQUEST['thing']; before checking if the value exists first.
try this first
if( !isset( $_REQUEST['thing']) )
{
do something because its missing
}

Categories