I'm new here.
Anyway, I'm working on an application system that logs your answers to the form into a text file called data.txt It was working for a while and then I tinkered with some stuff and it's not working anymore.
<html>
<head>
<link rel="stylesheet" href="style.css"
<meta charset="utf-8">
<title>Apply</title>
<link rel="icon" type="image/png" href="favicon.png">
</head>
<body>
<h1 class="unselectable">PvPCity Application</h1>
<form target=_blank action="index.php" method="post">
<input type="text" name="IGN" placeholder="IGN" autocomplete="off"><br>
<input type="text" name="Discord" placeholder="Discord" autocomplete="off"><br>
<input type="text" name="Age" placeholder="Age" autocomplete="off">
<textarea name="Why" placeholder="Why do you want to be staff?" autocomplete="off"></textarea>
<input onclick="window.location.href = 'http://pvpcity.dx.am/submitted/index.html';" type="submit" value="Apply" />
</form>
</body>
</html>
<?php
if( isset($_POST['IGN'] ) && isset( $_POST['Discord'] ) && isset( $_POST['Age'] ) && isset( $_POST['Why'] ) )
{
$txt=' ##### IGN: '.$_POST['IGN'].' ##### Discord: '.$_POST['Discord'].' ##### Age: '.$_POST['Age'].' ##### Why: '.$_POST['Why'] . PHP_EOL;
file_put_contents('data.txt', $txt, FILE_APPEND);
}
?>
Here is the code.
If you could tell me what is wrong that would be great.
The code here is from index.php
The submit button redirects to a different page when you click.
I honestly have no idea why it's not working
You should allow PHP to perform the redirection rather than allow people to potentially spoof others from your site. That said - you can simplify the collection of POSTed data a little by processing the POST array. The form will submit OK and redirect but the remote site will perhaps inaccurately report back that the application has been submitted - presumably this will be hosted on that site also so not necessarily an issue.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
$payload=array();
foreach( $_POST as $field => $value )$payload[]=sprintf('##### %s %s', $field, $value );
file_put_contents( 'data.txt', implode( ' ',$payload ).PHP_EOL, FILE_APPEND );
header('Location: http://pvpcity.dx.am/submitted/index.html');
}
?>
<html>
<head>
<link rel="stylesheet" href="style.css"
<meta charset="utf-8">
<title>Apply</title>
<link rel="icon" type="image/png" href="favicon.png">
</head>
<body>
<h1 class="unselectable">PvPCity Application</h1>
<form target=_blank method="post">
<input type="text" name="IGN" placeholder="IGN" autocomplete="off"><br>
<input type="text" name="Discord" placeholder="Discord" autocomplete="off"><br>
<input type="text" name="Age" placeholder="Age" autocomplete="off">
<textarea name="Why" placeholder="Why do you want to be staff?" autocomplete="off"></textarea>
<input type="submit" value="Apply" />
</form>
</body>
</html>
I believe you don't need onclick="window.location.href = ... Your submission can go to same file (index.php), you just need a better condition and since your inputs are not marked as required you might use something like this:
<?php
if(!empty($_POST)){
$txt = '';
foreach ($_POST as $key => $value){
$txt = $txt. " ##### ".$key.': '.$value;
}
file_put_contents('data.txt', $txt, FILE_APPEND);
}
?>
<html>
<head>
<link rel="stylesheet" href="style.css"
<meta charset="utf-8">
<title>Apply</title>
<link rel="icon" type="image/png" href="favicon.png">
</head>
<body>
<h1 class="unselectable">PvPCity Application</h1>
<form target=_blank action="" method="post">
<input type="text" name="IGN" placeholder="IGN" autocomplete="off"><br>
<input type="text" name="Discord" placeholder="Discord" autocomplete="off"><br>
<input type="text" name="Age" placeholder="Age" autocomplete="off">
<textarea name="Why" placeholder="Why do you want to be staff?" autocomplete="off"></textarea>
<input type="submit" value="Apply" />
</form>
</body>
</html>
<?php
if( isset($_POST['IGN'] ) && isset( $_POST['Discord'] ) && isset( $_POST['Age'] ) && isset( $_POST['Why'] ) )
{
$txt=' ##### IGN: '.$_POST['IGN'].' ##### Discord: '.$_POST['Discord'].' ##### Age: '.$_POST['Age'].' ##### Why: '.$_POST['Why'] . PHP_EOL;
if(file_put_contents('data.txt', $txt, FILE_APPEND)){
header('Location: http://pvpcity.dx.am/submitted/index.html');
}else{
echo 'data is not saved';
}
}
?>
I did some alteration in that above code for redirect to another website. You don't want to redirect on click, you can do that via PHP header().
header('Location: http://pvpcity.dx.am/submitted/index.html');
This will redirect after submit the form...
Related
I have 3 textboxes and i can't get it value with $_GET and $_POST options. I need something like this:
-I fill textboxes with text
-I click button
-I activate function when clicking button
-In this function I recieve text from textboxes
-I save it to file (saving to file works ;) )
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>One Hit Point</title>
<link href="Bez_nazwy1.css" rel="stylesheet">
<link href="test.css" rel="stylesheet">
</head>
<body>
<form action="<?php $_PHP_SELF ?>" method="GET">
<label for="" id="Label1" style="position:absolute;left:67px;top:16px;width:194px;height:31px;line-height:31px;z-index:0;">Imię</label>
<input type="text" id="x11" name="x1" style="position:absolute;left:158px;top:23px;width:196px;height:16px;z-index:1;" value="">
<label for="" id="Label2" style="position:absolute;left:67px;top:63px;width:289px;height:31px;line-height:31px;z-index:2;">Nazwisko</label>
<input type="text" id="x22" name="x2" style="position:absolute;left:158px;top:70px;width:196px;height:16px;z-index:3;" value="">
<label for="" id="Label3" style="position:absolute;left:67px;top:111px;width:194px;height:31px;line-height:31px;z-index:5;">Telefon</label>
<input type="text" id="x33" name="x3" style="position:absolute;left:158px;top:118px;width:196px;height:16px;z-index:6;" value="+48 ">
<input type="button" id="Button1" onclick="<?php costam() ?>;" name="" value="Zatwierdź" style="position:absolute;left:194px;top:164px;width:96px;height:25px;z-index:7;">
</form>
</body>
<body>
<?php
//window.location.href='./niespodzianka.html';return false;
function costam(){
$imie= $_GET['x1'];
$Nazwisko=$_GET['x2'];
$Numer= $_GET['x3'];
//łączenie
$dane=$imie.", ".$Nazwisko.", ".$Numer;
//dodawanie nowej linii
$popr=$dane." k\n";
//otwieranie, zapisanie, zamknięcie
$plik=fopen("zap.txt", "a");
fputs($plik, $popr);
fclose($plik);
}
?>
</body>
</html>
EDIT:
new code (now there are 2 files):
File 1 (dz.php):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>One Hit Point</title>
<link href="Bez_nazwy1.css" rel="stylesheet">
<link href="test.css" rel="stylesheet">
</head>
<body>
<form action="pliki.php" method="GET">
<label for="" id="Label1" style="position:absolute;left:67px;top:16px;width:194px;height:31px;line-height:31px;z-index:0;">Imię</label>
<input type="text" id="x11" name="x1" style="position:absolute;left:158px;top:23px;width:196px;height:16px;z-index:1;" value="">
<label for="" id="Label2" style="position:absolute;left:67px;top:63px;width:289px;height:31px;line-height:31px;z-index:2;">Nazwisko</label>
<input type="text" id="x22" name="x2" style="position:absolute;left:158px;top:70px;width:196px;height:16px;z-index:3;" value="">
<label for="" id="Label3" style="position:absolute;left:67px;top:111px;width:194px;height:31px;line-height:31px;z-index:5;">Telefon</label>
<input type="text" id="x33" name="x3" style="position:absolute;left:158px;top:118px;width:196px;height:16px;z-index:6;" value="+48 ">
<input type="button" id="Button1" onclick="location.href='pliki.php'" name="" value="Zatwierdź" style="position:absolute;left:194px;top:164px;width:96px;height:25px;z-index:7;">
</form>
</body>
</html>
File 2 (pliki.php):
<?php
//window.location.href='./niespodzianka.html';return false;
$imie= $_GET['x1'];
$Nazwisko=$_GET['x2'];
$Numer= $_GET['x3'];
//łączenie
$dane=$imie.", ".$Nazwisko.", ".$Numer;
//dodawanie nowej linii
$popr=$dane." k\n";
//otwieranie, zapisanie, zamknięcie
$plik=fopen("zap.txt", "a");
fputs($plik, $popr);
fclose($plik);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Bez nazwy</title>
<meta name="generator" content="WYSIWYG Web Builder 14 - http://www.wysiwygwebbuilder.com">
<link href="Bez_nazwy1.css" rel="stylesheet">
<link href="niespodzianka.css" rel="stylesheet">
</head>
<body>
<div id="wb_TextArt1" style="position:absolute;left:16px;top:13px;width:867px;height:470px;z-index:0;">
<img src="images/img0001.png" id="TextArt1" alt="Bede dzownić xd" title="Bede dzownić xd" style="width:867px;height:470px;"></div>
</body>
</html>
That code can't works. You can't call PHP function using javascript onclick.
For your clarification this code would execute costam() function everytime page is loaded.
Try to change Button1 with:
<input type="submit" id="Button1" name="submit" value="Zatwierdź" style="position:absolute;left:194px;top:164px;width:96px;height:25px;z-index:7;">
Then change php code in:
<?php
if($_GET['submit']){
$imie= $_GET['x1'];
$Nazwisko=$_GET['x2'];
$Numer= $_GET['x3'];
//łączenie
$dane=$imie.", ".$Nazwisko.", ".$Numer;
//dodawanie nowej linii
$popr=$dane." k\n";
//otwieranie, zapisanie, zamknięcie
$plik=fopen("zap.txt", "a");
fputs($plik, $popr);
fclose($plik);
}
This should works, but is not a good approch. Also the page will refresh.
If you're familiar with jQuery:
jQuery.ajax({
type: "POST",
url: 'your_functions_address.php',
dataType: 'json',
data: {functionname: 'add', arguments: [1, 2]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
yourVariable = obj.result;
}
else {
console.log(obj.error);
}
}
});
This may help you: Call php function from JavaScript
At the moment I am trying embed an osTicket form into my website so that users can submit a ticket that is integrated into my website.
I found a PHP script online and with the help of users from another thread, I have got it working so that when I run the script on the server it opens a ticket with all the information that was written in the PHP script. I want to be able to have a HTML page which submits the information from a form on the HTML page to replace the preset information in the PHP script.
My first thoughts to complete this was to simply copy the relevant files from the default 'submit ticket' page that came as part of osTicket. I viewed the source in my web browser and saw different code than if I downloaded the file and viewed it in a text editor.
So the PHP script that I am using is:
<?php
# //Configuration: Enter the url and key.
# url => URL to api/tickets.json # e.g http://yourdomain.com/s#upport/api/tickets.json
# key => API's Key (see admin panel o#n how to generate a key)
#
$config = array(
'url'=>'support.sinergycraft.net/tickets/api/tickets.json',
'key'=>'C2621CFA3E5F94B5396003218952DA0D'
);
#pre-checks
function_exists('curl_version') or die('CURL support required');
#set timeout
set_time_limit(30);
#Sample data for the ticket
# See https://github.com/osTicket/osTicket-1.7/blob/develop/setup/doc/api/tickets.md for full list of variables and options that you can pass.
$data = array("alert" => "true",
"autorespond" => "true",
"source" => "API",
"name" => "Angry User",
"email" => "api#osticket.com",
"subject" => "Testing API 3",
"message" => "MESSAGE HERE"
);
#Convert the above array into json to POST to the API with curl below.
$data_string = json_encode($data);
#curl post
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $config['url']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_USERAGENT, 'osTicket API Client v1.7');
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Expect:', 'X-API-Key: '.$config['key']));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result=curl_exec($ch);
curl_close($ch);
if(preg_match('/HTTP\/.* ([0-9]+) .*/', $result, $status) && $status[1] == 200)
exit(0);
echo $result;
exit(1);
?>
If I link a form to this like I have done in this code:
<form id="ticketForm" method="post" action="new_ticket.php" enctype="multipart/form-data">
The PHP script is called new_ticket.php. This opens a ticket with the prefilled options in the PHP but not what the uswer enters in the form.
Next I thought that I should try using the file that I downloaded off the server and not the code that I got from view source.
The file that is opened in the browser when you click the link to make a new ticket is called open.php and its content is bellow:
<?php
open.php
require('client.inc.php');
define('SOURCE','Web'); //Ticket source.
$ticket = null;
$errors=array();
if ($_POST) {
$vars = $_POST;
$vars['deptId']=$vars['emailId']=0; //Just Making sure we don't accept crap...only topicId is expected.
if ($thisclient) {
$vars['uid']=$thisclient->getId();
} elseif($cfg->isCaptchaEnabled()) {
if(!$_POST['captcha'])
$errors['captcha']=__('Enter text shown on the image');
elseif(strcmp($_SESSION['captcha'], md5(strtoupper($_POST['captcha']))))
$errors['captcha']=__('Invalid - try again!');
}
$tform = TicketForm::objects()->one()->getForm($vars);
$messageField = $tform->getField('message');
$attachments = $messageField->getWidget()->getAttachments();
if (!$errors && $messageField->isAttachmentsEnabled())
$vars['cannedattachments'] = $attachments->getClean();
// Drop the draft.. If there are validation errors, the content
// submitted will be displayed back to the user
Draft::deleteForNamespace('ticket.client.'.substr(session_id(), -12));
//Ticket::create...checks for errors..
if(($ticket=Ticket::create($vars, $errors, SOURCE))){
$msg=__('Support ticket request created');
// Drop session-backed form data
unset($_SESSION[':form-data']);
//Logged in...simply view the newly created ticket.
if($thisclient && $thisclient->isValid()) {
session_write_close();
session_regenerate_id();
#header('Location: tickets.php?id='.$ticket->getId());
}
}else{
$errors['err']=$errors['err']?$errors['err']:__('Unable to create a ticket. Please correct errors below and try again!');
}
}
//page
$nav->setActiveNav('new');
if ($cfg->isClientLoginRequired()) {
if (!$thisclient) {
require_once 'secure.inc.php';
}
elseif ($thisclient->isGuest()) {
require_once 'login.php';
exit();
}
}
require(CLIENTINC_DIR.'header.inc.php');
if($ticket
&& (
(($topic = $ticket->getTopic()) && ($page = $topic->getPage()))
|| ($page = $cfg->getThankYouPage())
)) {
// Thank the user and promise speedy resolution!
echo Format::viewableImages($ticket->replaceVars($page->getBody()));
}
else {
require(CLIENTINC_DIR.'open.inc.php');
}
require(CLIENTINC_DIR.'footer.inc.php');
?>
I tried substituting this as the action in my HTML code instead of new_ticket.php but I still had no luck.
So basically what I am looking to do is be able to submit informaiton in the HTML form and for it to substitute the pre-written text in the PHP script for what the user entered.
Finally, bellow I have provided what the open.php file shows in view shource when I open it in the web browser. This is the file which I coppied the form off for my HTML document which I was hoping would submit the data to the PHP script.
<!DOCTYPE html>
<html >
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>SinergyCraft.net Support</title>
<meta name="description" content="customer support platform">
<meta name="keywords" content="osTicket, Customer support system, support ticket system">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="stylesheet" href="/tickets/css/osticket.css?ecb4f89" media="screen">
<link rel="stylesheet" href="/tickets/assets/default/css/theme.css?ecb4f89" media="screen">
<link rel="stylesheet" href="/tickets/assets/default/css/print.css?ecb4f89" media="print">
<link rel="stylesheet" href="/tickets/scp/css/typeahead.css"
media="screen" />
<link type="text/css" href="/tickets/css/ui-lightness/jquery-ui-1.10.3.custom.min.css"
rel="stylesheet" media="screen" />
<link rel="stylesheet" href="/tickets/css/thread.css?ecb4f89" media="screen">
<link rel="stylesheet" href="/tickets/css/redactor.css?ecb4f89" media="screen">
<link type="text/css" rel="stylesheet" href="/tickets/css/font-awesome.min.css?ecb4f89">
<link type="text/css" rel="stylesheet" href="/tickets/css/flags.css?ecb4f89">
<link type="text/css" rel="stylesheet" href="/tickets/css/rtl.css?ecb4f89"/>
<script type="text/javascript" src="/tickets/js/jquery-1.8.3.min.js?ecb4f89"></script>
<script type="text/javascript" src="/tickets/js/jquery-ui-1.10.3.custom.min.js?ecb4f89"></script>
<script src="/tickets/js/osticket.js?ecb4f89"></script>
<script type="text/javascript" src="/tickets/js/filedrop.field.js?ecb4f89"></script>
<script type="text/javascript" src="/tickets/js/jquery.multiselect.min.js?ecb4f89"></script>
<script src="/tickets/scp/js/bootstrap-typeahead.js?ecb4f89"></script>
<script type="text/javascript" src="/tickets/js/redactor.min.js?ecb4f89"></script>
<script type="text/javascript" src="/tickets/js/redactor-osticket.js?ecb4f89"></script>
<script type="text/javascript" src="/tickets/js/redactor-fonts.js?ecb4f89"></script>
<meta name="csrf_token" content="4f5df4c017ca804903b7b513210231cd8fd6d714" />
</head>
<body>
<div id="container">
<div id="header">
<a class="pull-left" id="logo" href="/tickets/index.php"
title="Support Center"><img src="/tickets/logo.php" border=0 alt="SinergyCraft.net Support"
style="height: 5em"></a>
<div class="pull-right flush-right">
<p>
</p>
<p>
</p>
</div>
</div>
<div class="clear"></div>
<ul id="nav" class="flush-left">
<li><a class=" home" href="/tickets/index.php">Support Center Home</a></li>
<li><a class="active new" href="/tickets/open.php">Open a New Ticket</a></li>
<li><a class=" status" href="/tickets/view.php">Check Ticket Status</a></li>
</ul>
<div id="content">
<h1>Open a New Ticket</h1>
<p>Please fill in the form below to open a new ticket.</p>
<form id="ticketForm" method="post" action="open.php" enctype="multipart/form-data">
<input type="hidden" name="__CSRFToken__" value="4f5df4c017ca804903b7b513210231cd8fd6d714" /> <input type="hidden" name="a" value="open">
<table width="800" cellpadding="1" cellspacing="0" border="0">
<tbody>
<tr>
<td class="required">Help Topic:</td>
<td>
<select id="topicId" name="topicId" onchange="javascript:
var data = $(':input[name]', '#dynamic-form').serialize();
$.ajax(
'ajax.php/form/help-topic/' + this.value,
{
data: data,
dataType: 'json',
success: function(json) {
$('#dynamic-form').empty().append(json.html);
$(document.head).append(json.media);
}
});">
<option value="" selected="selected">— Select a Help Topic —</option>
<option value="12" >Ban Site/Server</option><option value="1" >General Inquiry</option><option value="2" >Recruitment</option><option value="10" >Report a Problem</option><option value="11" >White List Me</option> </select>
<font class="error">* </font>
</td>
</tr>
<tr><td colspan="2"><hr />
<div class="form-header" style="margin-bottom:0.5em">
<h3>Contact Information</h3>
<em></em>
</div>
</td></tr>
<tr>
<td><label for="b695be87472f918f" class="required">
Email Address:</label></td><td>
<span style="display:inline-block">
<input type="text"
id="_b695be87472f918f"
size="40" maxlength="64" placeholder="" name="b695be87472f918f"
value=""/>
</span>
<font class="error">*</font>
</td>
</tr>
<tr>
<td><label for="e6ac2c5b0fbeba20" class="required">
Full Name:</label></td><td>
<span style="display:inline-block">
<input type="text"
id="_e6ac2c5b0fbeba20"
size="40" maxlength="64" placeholder="" name="e6ac2c5b0fbeba20"
value=""/>
</span>
<font class="error">*</font>
</td>
</tr>
</tbody>
<tbody id="dynamic-form">
</tbody>
<tbody> <tr><td colspan="2"><hr />
<div class="form-header" style="margin-bottom:0.5em">
<link rel="stylesheet" type="text/css" href="/tickets/css/jquery.multiselect.css"/> <h3>Ticket Details</h3>
<em>Please Describe Your Issue</em>
</div>
</td></tr>
<tr>
<td><label for="48b638e54863b978" class="required">
Issue Summary:</label></td><td>
<span style="display:inline-block">
<input type="text"
id="_48b638e54863b978"
size="40" maxlength="50" placeholder="" name="48b638e54863b978"
value=""/>
</span>
<font class="error">*</font>
</td>
</tr>
<tr>
<td colspan="2">
<div style="margin-bottom:0.5em;margin-top:0.5em"><strong>Issue Details</strong>:</div>
<textarea style="width:100%;" name="message"
placeholder="Details on the reason(s) for opening the ticket."
data-draft-namespace="ticket.client"
data-draft-object-id="ea999hv0kkq1"
class="richtext draft draft-delete ifhtml"
cols="21" rows="8" style="width:80%;"></textarea>
<div id="b6d716e83936ea511681b5" class="filedrop"><div class="files"></div>
<div class="dropzone"><i class="icon-upload"></i>
Drop files here or choose them <input type="file" multiple="multiple"
id="file-b6d716e83936ea511681b5" style="display:none;"
accept=""/>
</div></div>
<script type="text/javascript">
$(function(){$('#b6d716e83936ea511681b5 .dropzone').filedropbox({
url: 'ajax.php/form/upload/attach',
link: $('#b6d716e83936ea511681b5').find('a.manual'),
paramname: 'upload[]',
fallback_id: 'file-b6d716e83936ea511681b5',
allowedfileextensions: [],
allowedfiletypes: [],
maxfiles: 20,
maxfilesize: 32,
name: 'attach:21[]',
files: [] });});
</script>
<link rel="stylesheet" type="text/css" href="/tickets/css/filedrop.css"/> <font class="error">*</font>
</td>
</tr>
</tbody>
<tbody>
<tr><td colspan=2> </td></tr>
</tbody>
</table>
<hr/>
<p style="text-align:center;">
<input type="submit" value="Create Ticket">
<input type="reset" name="reset" value="Reset">
<input type="button" name="cancel" value="Cancel" onclick="javascript:
$('.richtext').each(function() {
var redactor = $(this).data('redactor');
if (redactor && redactor.opts.draftDelete)
redactor.deleteDraft();
});
window.location.href='index.php';">
</p>
</form>
</div>
</div>
<div id="footer">
<p>Copyright © 2015 SinergyCraft.net Support - All rights reserved.</p>
<a id="poweredBy" href="http://osticket.com" target="_blank">Helpdesk software - powered by osTicket</a>
</div>
<div id="overlay"></div>
<div id="loading">
<h4>Please Wait!</h4>
<p>Please wait... it will take a second!</p>
</div>
</body>
</html>
Thanks
I may be missing something in your question, but I think you just need to put more into your form and then extract the variables in your PHP:
HTML:
<form id="ticketForm" method="post" action="new_ticket.php" >
<input type="text" name="name" />
<input type="text" name="email" />
<input type="text" name="subject" />
<textarea name="message"></textarea>
<input type="submit" name="submit" value="send" />
(I think I can see some of these input fields in your page source dump, but the name fields appear to be generated e.g. name="b695be87472f918f" whichever you use the html name='name' and the $_POST['name'] need to match).
Then in your PHP code:
$data = array("alert" => "true",
"autorespond" => "true",
"source" => "API",
"name" => $_POST['name'],
"email" => $_POST['email'],
"subject" => $_POST['subject'],
"message" => $_POST['message']
);
Probably wise to carry out some validation on the values before actually using them.
I am having an issue with storing $_SESSION variables, i am a little new at PHP and I like it to the extent of my current knowledge.
first my creds:
Win 7 Pro 64
PHP 5
Remote Server(not sure of its config)
So what I am trying to do is set up a Login Page that contains a hardcoded username and password for testing purposes.
I want to display the username on a successor page to confirm it.
Login.php
<?php session_start();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head >
<title>Login</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="content-language" content="en-gb" />
<script type="text/javascript">
// Perform Client side validation of Username and Password
function redirect() {
var username = document.getElementById("username");
var password = (document.getElementById("password"));
if (!username.value == " ") {
if (!password.value == " ") {
if (username.value == "aknight") {
if (password.value == "00226291") {
window.location = "Home.php";
exit();
} else
alert("Username or Password Invalid");
}
} else
alert("Password is required");
} else
alert("Username is required");
}
</script>
</head>
<body>
<div id="header">
<h1>Product Order System</h1>
<br/>
<h2>The most expensive crap youll ever find...</h2>
</div>
<div id="content">
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$_SESSION['username'] = $_POST['username'];
}else{
?>
<form action="" method="POST">
<fieldset>
<legend>Login Information</legend>
<p>
<label for="Username">Username:</label>
<input type="text" name="username" id="username" />
</p>
<p>
<label for="Password">Password:</label>
<input type="password" name="password" id="password" />
</p>
<p>
<input type="button" name="login" value="Login" onclick="redirect();"/>
<input type="button" name="cancel" value="Cancel" />
</fieldset>
</form>
<?php }
include ('includes/footer.html');
?>
home.php
<?php
session_start();
$page_title = 'Home';
include ('includes/header.php');
if(isset($_SESSION['username'])) { $name = $_SESSION['username'];}else{echo "<p>error</p>";}
echo "<h3>Welcome ".$name."!</h3>" ;
?>
I have tried printing out the $_SESSION values and they are coming up empty.
producing this result
<?php
echo "<pre>".print_r($_SESSION)."</pre>";
?>
Array {
[username] =>
}
Please do not mind the JS, it is preschool client validation just to move forward.
Any help would be greatly appreciated.
Give your login form a name, and then in your JavaScript validation function, instead of window.location, do a document.forms['yourformname'].submit().
I think your Javascript validation is actually what's causing the issue.
You're setting the session variable in Login.php using the POST request, but no POST is actually being sent to Login.php since your Javascript is redirecting to Home.php once the form is considered valid. You need to submit the form at some point in the process, so you actually get some POST values which you'll use to populate your SESSION variables.
If you want to keep your Javascript validation, maybe have a look at submit() : http://www.w3schools.com/jsref/met_form_submit.asp
You'll have to set a correct action property on your form before submitting it.
So heres a fix that seems to be working
<?php session_start();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head >
<title>Login</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="content-language" content="en-gb" />
<script type="text/javascript">
// Perform Client side validation of Username and Password
function redirect() {
var username = document.getElementById("username");
var password = (document.getElementById("password"));
if (!username.value == " ") {
if (!password.value == " ") {
if (username.value == "aknight") {
if (password.value == "00226291") {
document.forms[0].submit();
exit();
} else
alert("Username or Password Invalid");
}
} else
alert("Password is required");
} else
alert("Username is required");
}
</script>
</head>
<body>
<div id="header">
<h1>Product Order System</h1>
<br/>
<h2>The most expensive crap youll ever find...</h2>
</div>
<div id="content">
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$_SESSION['username'] = $_POST['username'];
header('Location : ../Home.php');
}else{
?>
<form action="Home.php" name="login" method="POST">
<fieldset>
<legend>Login Information</legend>
<p>
<label for="Username">Username:</label>
<input type="text" name="username" id="username" />
</p>
<p>
<label for="Password">Password:</label>
<input type="password" name="password" id="password" />
</p>
<p>
<input type="button" name="login" value="Login" onclick=" redirect();"/>
<input type="button" name="cancel" value="Cancel" />
</fieldset>
</form>
<?php }
include ('includes/footer.html');
?>
Will post again if the nex series of pages has a similiar issue
Thanks
I am developing a phonegapp app. Have a simple login form in action.php file and for test purpose I am just printing the submit variable in other file see.php.
Issue is that if I include following line of code in action.php then submitted variables from form are not getting printed:
<script src="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.js" type="text/javascript"></script>
But If I remove the above line from action.php, form is getting submitted properly and input variables are getting printed in see.php
action.php
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Application</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.0/jquery.mobile.structure-1.4.0.min.css" />
<link href='http://fonts.googleapis.com/css?family=EB+Garamond&subset=latin,cyrillic-ext,vietnamese,latin-ext,cyrillic' rel='stylesheet' type='text/css'>
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.js" type="text/javascript"></script>
</head>
<body>
<form action="see.php" method = "post">
<label for="Cedula" style="font-size:10px; color:#FFF; text-shadow:none">Cedula</label>
<input type="text" name="usr" id="usr" value="username" data-clear-btn="true">
<label for="Contrasena" style="font-size:10px; color:#FFF; text-shadow:none">Contrasena</label>
<input type="password" name="pwd" id="pwd" value="password" data-clear-btn="true">
<input type="submit" data-role="button" style="font-weight:100" value="Submit"/>
</form>
</body>
</html>
see.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$uid = $_POST['usr'];
$upwd = $_POST['pwd'];
echo $uid;
echo "<br>";
echo $upwd;
echo "<br>";
?>
As you see in console ( network ) , see.php is being called and values of post are printed . You can turn your firebug ON and check the results ..
In jQuery Mobile, form submissions are automatically handled using Ajax whenever possible
To submit the form normally you can use data-ajax="false" in form
<form data-ajax="false" action="" method="">
I have the following PHP printExam.php page:
<?php
$logins = array(
'user' => 'pass',
'user1' => 'pass1',
'user2' => 'pass2',
'user3' => 'pass3',
'user4' => 'pass4'
);
// Clean up the input values
foreach($_POST as $key => $value) {
$_POST[$key] = stripslashes($_POST[$key]);
$_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}
/******************************************************************************/
if (isset($_POST['submit'])){
$user = isset($_POST['user']) ? strtolower($_POST['user']) : '';
$pass = isset($_POST['pass']) ? $_POST['pass'] : '';
$report = $_POST['typereport'];
if ((!array_key_exists($user, $logins))||($logins[$user] != $pass)) {
showForm("Wrong Username/Password");
exit();
}
else {
if ($report == "Clinical") {
?>
<html>
<head>
</head>
<body>
CLINICAL PAGE
</body>
</html>
<?php
}
elseif ($report == "Annual Education") {
?>
<html>
<head>
</head>
<body>
ANNUAL EDUCATION PAGE
</body>
</html>
<?php
}
}
} else {
showForm();
exit();
}
function showForm($error=""){
?>
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>Certificate Printing :: Login</title>
<script src="http://code.jquery.com/jquery-1.7.1.min.js" type="text/javascript"></script>
<Script>
$(function() {
$("#user").focus();
});
</Script>
</head>
<body>
<form id="login" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="pwd">
<h1>Log In</h1>
<fieldset id="inputs">
<input id="user" name="user" placeholder="Username" autofocus="" required="" type="text">
<input id="pass" name="pass" placeholder="Password" required="" type="password">
</fieldset>
<fieldset id="actions">
<input type="radio" name="typereport" id="cbox" value="Clinical" checked="yes" /> Clinical
<input type="radio" name="typereport" id="cbox" value="Annual Education" /> Annual Education
</fieldset>
<fieldset id="actions">
<input id="submit" name="submit" value="Log in" type="submit">
</fieldset>
<div class="caption"><?php echo $error; ?></div>
</form>
</body>
</html>
<?php
}
?>
For printCert.php and printCertHR.php, the very first line is:
<?php require_once('printExam.php'); ?>
What it is suppose to do is call the printExam.php page each time the user visits either pages. If the username AND password matches and depending on the selection, whether it's clinical or annual education, it should take the user to the correct page. I know the form is working correctly, because if I enter wrong username/password it shows me the error but once correct, it doesnt redirect. Any idea how to resolve it?
Please Note: the username/password is simplified for the example only!
The 'Location' header command in PHP should be followed with an exit;
Otherwise the code below is executed, ie any output is sent to the browser.
See the examples from the PHP header page:
<?php
header("Location: http://www.example.com/"); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit;
Location (or any other header) needs to be the first thing echoed by your script. Remove the blank lines in your script.
You have contents being displayed before the header is being called (as for your comment to Rob W). The way to get around it is, put ob_start(); at the top of your php code, and ob_end_flush(); at the end of your code so the header can be called anywhere in between your code.
Is it possible that you might need to use PHP's Output Buffer to fix that? When the script is parsed, having the output of the form in a function might be throwing it off, as the function will be parsed before the rest of the script is run.
Also, you should use strcmp for comparing strings, not the == sign. strcmp vs ==
Try using the output buffer functions and see if that fixes it. it's gonna look something like this:
function showForm($error=""){
ob_start(); ?>
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>Certificate Printing :: Login</title>
<script src="http://code.jquery.com/jquery-1.7.1.min.js" type="text/javascript"></script>
<Script>
$(function() {
$("#user").focus();
});
</Script>
</head>
<body>
<form id="login" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="pwd">
<h1>Log In</h1>
<fieldset id="inputs">
<input id="user" name="user" placeholder="Username" autofocus="" required="" type="text">
<input id="pass" name="pass" placeholder="Password" required="" type="password">
</fieldset>
<fieldset id="actions">
<input type="radio" name="typereport" id="cbox" value="Clinical" checked="yes" /> Clinical
<input type="radio" name="typereport" id="cbox" value="Annual Education" /> Annual Education
</fieldset>
<fieldset id="actions">
<input id="submit" name="submit" value="Log in" type="submit">
</fieldset>
<div class="caption"><?php echo $error; ?></div>
</form>
</body>
</html>
<?php
return ob_get_flush();
}
Output Buffers (php.net)
After your elseif ($report == "Annual Education") { block, try print_r($report) - ensure it's what you are expecting...
if ($report == "Clinical") {
header ("Location: printCert.php");
}
elseif ($report == "Annual Education") {
header ("Location: printCertHR.php");
}
print_r($report);
Also, try monitoring FireBug's NET tab (or CHROME's)