Page become white - php

Hello I have a error on my page.. When i go to www.mysite.com/request.php the page is just white..
<?php
include("../includes/config.php");
include("../includes/functions.php");
######
include('../config_radio.php'); //you may edit this path to fit your server environment otherwise leave it alone
$scfp = fsockopen("$scip", $scport, &$errno, &$errstr, 30);
if(!$scfp) {
$scsuccs=1;
echo''.$scdef.' is Offline';
}
if($scsuccs!=1){
fputs($scfp,"GET /admin.cgi?pass=$scpass&mode=viewxml HTTP/1.0\r\nUser-Agent: SHOUTcast Song Status (Mozilla Compatible)\r\n\r\n");
while(!feof($scfp)) {
$page .= fgets($scfp, 1000);
}
###########################################################
///////////////////////// Part 1 \\\\\\\\\\\\\\\\\\\\\\\\\
###########################################################
//define xml elements
$loop = array("STREAMSTATUS", "BITRATE", "SERVERTITLE", "CURRENTLISTENERS");
$y=0;
while($loop[$y]!=''){
$pageed = ereg_replace(".*<$loop[$y]>", "", $page);
$scphp = strtolower($loop[$y]);
$$scphp = ereg_replace("</$loop[$y]>.*", "", $pageed);
if($loop[$y]==SERVERGENRE || $loop[$y]==SERVERTITLE || $loop[$y]==SONGTITLE || $loop[$y]==SERVERTITLE)
$$scphp = urldecode($$scphp);
// uncomment the next line to see all variables
//echo'$'.$scphp.' = '.$$scphp.'<br>';
$y++;
}
//end intro xml elements
###########################################################
///////////////////////// Part 2 \\\\\\\\\\\\\\\\\\\\\\\\\
###########################################################
//get song info and history
$pageed = ereg_replace(".*<SONGHISTORY>", "", $page);
$pageed = ereg_replace("<SONGHISTORY>.*", "", $pageed);
$songatime = explode("<SONG>", $pageed);
$r=1;
while($songatime[$r]!=""){
$t=$r-1;
$playedat[$t] = ereg_replace(".*<PLAYEDAT>", "", $songatime[$r]);
$playedat[$t] = ereg_replace("</PLAYEDAT>.*", "", $playedat[$t]);
$song[$t] = ereg_replace(".*<TITLE>", "", $songatime[$r]);
$song[$t] = ereg_replace("</TITLE>.*", "", $song[$t]);
$song[$t] = urldecode($song[$t]);
$dj[$t] = ereg_replace(".*<SERVERTITLE>", "", $page);
$dj[$t] = ereg_replace("</SERVERTITLE>.*", "", $pageed);
$r++;
}
//end song info
fclose($scfp);
}
########
if($_GET['sendreq'] == "true" && $_GET['dj'] && $_GET['name'] && $_GET['type'] && $_GET['message']) {
$name = $_GET['name'];
$dj = $_GET['dj'];
$type = $_GET['type'];
$message = $_GET['message'];
$name = clean($name);
$dj = clean($dj);
$type = clean($type);
$message = clean($message);
$name = censor($name);
$dj = censor($dj);
$type = censor($type);
$message = censor($message);
$ip = $_SERVER['REMOTE_ADDR'];
$a1 = date("r");
$a2 = explode(" ", $a1);
$insert = mysql_query("INSERT INTO requests (`name`, `dj`, `type`, `msg`, `time`, `ip`) VALUES ('$name', '$dj', '$type', '$message', '$a2[4]', '$ip')") or die('Could not send request! Error: '.mysql_error());
echo('<strong>Thanks!</strong> Your message has been sent to the DJ specified!');
die();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Request Line</title>
<style type="text/css">
<!--
#title { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10px; font-weight: bold; }
#sub_title { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10px; font-weight: normal; font-style: italic; }
#text { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10px; font-weight: normal; font-style: none; }
#results { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10px; font-weight: normal; font-style: none; }
input { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10px; font-weight: normal; font-style: none; }
select { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10px; font-weight: normal; font-style: none; }
textarea { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10px; font-weight: normal; font-style: none; }
-->
</style>
<script>
var xmlHttp
function GetXmlHttpObject()
{
var objXMLHttp = null
if (window.XMLHttpRequest)
{
objXMLHttp = new XMLHttpRequest()
}
else if (window.ActiveXObject)
{
objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP")
}
return objXMLHttp
}
function sendreq() {
// Open function
// Set object
xmlHttp = GetXmlHttpObject()
if (xmlHttp == null)
{
alert ("Browser does not support HTTP Request")
return
}
// We have set teh object
// Check for empty strings
if(document.request.type.value == "") {
alert("You must select a type of request!")
return
}
if(document.request.name.value == "") {
alert("You must enter a name!")
return
}
if(document.request.message.value == "") {
alert("You must enter a message!")
return
}
// We have alerted if any strings are emptyyy
var url = "request.php?sendreq=true&dj="+document.request.dj.value+"&name="+document.request.name.value+"&type="+document.request.type.value+"&message="+document.request.message.value
xmlHttp.open("GET",url,true)
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
document.getElementById("results").innerHTML = xmlHttp.responseText;
document.getElementById("form").innerHTML = "" // This removes the form, stopping them from sending the same request over and over again - SMART, EH?
}
};
xmlHttp.send(null);
// Now we clear out the forms and hide the form to TRY to prevent spamz!
// End function
}
</script>
</head>
<body>
<span id="title">Kontakta studion</span><br />
<span id="sub_title">Edit the css for this to fit YOUR site!</span>
<br />
<br />
<div id="form" name="form" style="display: block">
<form method="post" name="request" onsubmit="sendreq();return false;">
<span id="text"><strong>
Radio DJ:<br />
<label>
<select name="dj" id="dj">
<?php
$query = mysql_query("SELECT * FROM users WHERE level != 'banned'") or die('ERROR '.mysql_error());
while($rows = mysql_fetch_array($query)) {
if(preg_match("/". $rows[username] ."/i", $servertitle)) {
echo("<option value='". $rows[username] ."' SELECTED>DJ ". $rows[username] ." lol</option>");
} else {
echo("<option value='". $rows[username] ."'>DJ ". $rows[username] ."</option>");
}
}
?>
</select></label>
</strong><br />
<br />
<strong>Ditt Namn:</strong><br />
<label>
<input name="name" type="text" id="name" />
</label>
<br />
<br />
<strong>Typ:</strong><br />
<label>
<select name="type" id="type">
<option value="request">Låtönskning</option>
<option value="shoutout">Hälsning</option>
<option value="competition">Tävlingssvar</option>
<option value="joke">Skämt</option>
</select>
</label>
<br />
<br />
<strong>Meddelande:</strong></span>
<br />
<label>
<textarea name="message" cols="30" rows="4" id="message"></textarea>
</label>
<br />
<br />
<label>
<input type="submit" name="Submit" value="Skicka!" />
</label>
</form>
<br /><br />
</div>
<div id="results"></div>
</body>
</html>
Thats the code... I got 500 Internal Server Error
Any help on whats wrong with this?
I have search on google but no answer there... Maybe I search wrong but anyway. I hope to get some help here instead :).

Turn on error reporting by editing your php.ini file.
Inside your php.ini file, you will find two settings - error_reporting and display_errors. You should set error_reporting to E_ALL, and display_errors to 1. Restart your webserver, and reload your page. You should now see a more descriptive error message.
Note that other answers ask you to enable error reporting at runtime, but not all errors are triggered at runtime. Parse errors (eg bad syntax) will be triggered before your code is even run, and so the error config will still be using the values defined in the php.ini file, still leaving you with a blank page.
As a side note, PHP errors may also be reported to the web server's event log (the location of which will vary on web server and operating system), even if error_reporting is disabled.

Before while loop on line 13 you need to set $page variable, so:
$page = "";
while(!feof($scfp)) {
$page .= fgets($scfp, 1000);
}
In while loop you add st. to undefined $page, so you need to define that first.

Turn on error reporting.
error_reporting(E_ALL);
ini_set('display_errors', 'on');
You will get the error by this.

Related

if isset $_POST output fail

I'm trying to create a banning system for a chat that I made and it has a separate "console" only seen by admins. Im using Mac OS 10.11.4, I am the owner and am using Mamp with php version 5.6.10
Ban.php
<?php
$ban = $_POST['ban'];
$mybfile = fopen("banned.txt", 'a');
$txtb = ($ban." , ");
//Makes sure ip banned it not an admins
if (isset($_POST['ban'])) {
//example ip addresses
if ($ban === '1.1.1.1' || 192.168.1.132) {
echo 'Can\'t ban an Admin';
} else {
echo 'IP banned';
fwrite($mybfile, $txtb);
fclose($mybfile);
}
}
?>
<style>
.ban {
background-color: black;
width:30em;
height:5em;
color: #7ACC52;
}
.buttonBAN {
border:1px solid black;
width: 85px;
height: 55px;
background-color: white;
color: black;
position: absolute;
}
</style>
<body>
<form method="POST">
BanCMD<br />
<input type="text" name="ban" class="ban">
<input type="submit" value="Enter" class="buttonBAN">
</form>
</body>
Chat.php:
<?php
require "blocked.php";
require "connect.inc.php";
require "core.inc.php";
require "commands.php";
$sent = $_POST['chat'];
$myfile = fopen("chat.txt", 'a') or die("Unable to open file!");
$txt = ($sent."\n");
$first = getuserfield('username');
$active = ($first.":".$ip_addr);
$activef = fopen("ip-user.txt", 'a');
$myFile = "domains/domain_list.txt";
if (loggedin()) {
echo 'Welcome, '.$first,'<br />';
if ($first != 'SnR' || 'Koi') {
fwrite($activef, $active."\n"."=");
}
} else if (!loggedin()) {
die('Not logged in');
}
if (isset($_POST['chat'])) {
if (!empty($sent)) {
fwrite($myfile, $first.': '.$txt.'=');
fclose($myfile);
} else if (empty($sent)) {
echo 'Cant send an empty message','<br />';
}
}
$file = "chat.txt";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
$line = fgets($handle);
$linecount++;
}
fclose($handle);
if ($linecount > 49) {
unlink($file);
} else {
echo 'Line count: '.$linecount,'<br />';
}
echo 'Chat will reset at 50 lines','<br />';
echo 'Your IP:';
echo $ip_addr,'<br />';
?>
<html>
<head>
</head>
<body>
<!-- <a href='active.txt'>Online users</a><br /> -->
<iframe id='reload' src='refresh.php'>
<fieldset class="field">
<div id="list"><p><?php
$filename = 'chat.txt';
$handle = fopen($filename, 'r');
$detain = fread($handle, filesize($filename));
$chat_array = explode('=', $detain);
foreach($chat_array as $chat) {
echo $chat.'<br />';
}
?></p></div>
</fieldset>
</iframe>
<form action="chat.php" method="POST">
<input type="text" name="chat" class="textbox">
<input type="submit" value="Send" class="button">
</form>
</body>
</html>
<?php
if ($first == 'SnR' && 'Koi') {
include 'AdminCMD.php';
include 'ban.php';
?>
<iframe id='reload' src='refresh2.php' class="field2">
<fieldset class="field">
</fieldset>
</iframe>
<?php
}
?>
The problem is that everything is fine until you give an input, no matter what you put into the box the output is always "Can't ban an Admin" meaning that it doesn't write to the given file
Thank you for any help.
Your code contains an error, preventing the file from being written. The first line of PHP code,$ban = $_POST['ban'];, could fail if no post data was sent. You need to first check if the $_POST['ban'] was set. A fixed version of your code can be found below.
<?php
//Makes sure ip banned it not an admins
if (isset($_POST['ban'])) {
$ban = $_POST['ban'];
$mybfile = fopen("banned.txt", 'a');
$txtb = ($ban." , ");
if ($ban === '1.1.1.1') {
echo 'Can\'t ban an Admin';
} else {
echo 'IP banned';
fwrite($mybfile, $txtb);
fclose($mybfile);
}
}
?>
<style>
.ban {
background-color: black;
width:30em;
height:5em;
color: #7ACC52;
}
.buttonBAN {
border:1px solid black;
width: 85px;
height: 55px;
background-color: white;
color: black;
position: absolute;
}
</style>
<body>
<form method="POST">
BanCMD<br />
<input type="text" name="ban" class="ban">
<input type="submit" value="Enter" class="buttonBAN">
</form>
</body>
When i ran your code it returns undefined index ban, you can try this and make sure what is not working for you.
<?php
$ban = isset($_POST['ban']) ? $_POST['ban'] : null;
$mybfile = fopen("banned.txt", 'a');
$txtb = ($ban." , ");
//Makes sure ip banned it not an admins
if(isset($ban)){
if ($ban === '1.1.1.1') {
echo 'Can\'t ban an Admin';
} else {
echo 'IP banned';
fwrite($mybfile, $txtb);
fclose($mybfile);
}
}
?>
<style>
.ban {
background-color: black;
width:30em;
height:5em;
color: #7ACC52;
}
.buttonBAN {
border:1px solid black;
width: 85px;
height: 55px;
background-color: white;
color: black;
position: absolute;
}
</style>
<body>
<form method="POST">
BanCMD<br />
<input type="text" name="ban" class="ban">
<input type="submit" value="Enter" class="buttonBAN">
</form>
</body>

Removing an option from dropbox after selected

I have a state guessing guess I wrote. I'm trying to remove a capital from the dropbox menu after it has been guessed. Any clues on how to go about doing that?
I have a comment on line 44 which is code that I believe may work but I havent been able to get working.
Thanks for reading and thanks in advance!
Heres my code:
<?php
require_once "include/session.php";
if (!isset($session->valid)) {
header("location: login.php");
exit();
}
require_once "include/city_info.php";
/* DO NOT MODIFY THE ABOVE LINES !!!!! */
$states = array_keys($state_capitals);
$capitals = array_values($state_capitals);
$cities = array_merge($capitals, $other_cities);
sort($cities);
$params = (object) $_REQUEST;
if (isset ($params->guess) ) {
$state = $session->statename;
$capital = $params->city;
$city = $params->city;
$session->guess ++ ;
//if they guess correctly
if ($capital == $state_capitals[$session->statename]){
$response = "You've Guessed Correct After $session->guess Guesses";
}
//if they guess incorrectly
else {
$response = " You've Guessed Wrong $session->guess Times";}
}
else {
$index = rand( 0, count($states)- 1 );
$state = $states[ $index ];
$city = $state_capitals[ $state ];
$session->statename = $state;
$guess = (0);
$session->guess = (0);
$response = "Try To Get Less Than 3 Guesses";
// create initial selections
//$session->selections = array();
// foreach($city as $value) {
// $session->selections[$value] = 1;
//}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta http-equiv="Cache-Control"
content="no-cache, max-age=0, no-store, must-revalidate" />
<title>State Capital Guessing Game</title>
<style type="text/css">
body {
background-color:#ffff4d;
}
div {
position:center;
width: 350px;
padding: 10px;
border: 3px solid black;
border-radius: 10px;
color: black;
background-color:#3399ff;
}
}
h1{
padding:5px;
}
h2 {
text-align: center;
font-size:20px;
}
h3 {
text-align:center;
}
h4 {
text-align:center;
}
h5 {
position: absolute;
top:0px;
right:0px;
}
#logout {
position: absolute;
top: 0px;
right: 0px;
}
</style>
</head>
<body>
<a id="logout" href="logout.php">Log out</a>
<h1>
State Capital Guess Game
<form action="program.php" method="get">
<button type="submit">Reset</button>
</h1>
</form>
<div>
<form action="program.php" method="post">
<input type="hidden" name="answer" value="<?php echo $state?>" />
<h2>
Guess the capital of: <?php echo "$session->state" ?>
</h2>
<h3>
<select name="city">
<?php
$options = "";
foreach ($cities as $value){
$options .= '<option value="' . $value . '"';
if ($value == $params->city)
$options .= ' selected';
$options .= '>' . $value . '</option>';
}
echo $options;
?>
</select>
<input type="submit" name="guess" value="Guess" />
</form>
</h3>
<h4><?php echo $response ?></h4>
</div>
<h5><?php echo "The Correct Answer Is: $state_capitals[$state]" ?><h5>
</body>
</html>​

php header to redirect.. not working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I've checked and re checked and I don't know what I'm doing wrong. No errors are showing up, it just directs me no where after I submit a login page.. any suggestions?
header:
<html>
<head>
<title><?php echo $title; ?></title>
<style type ="text/css">
#top_links a:link, a:visited{
width: 100%;
display: block;
font-weight: bold;
color: #FFFFFF;
background-color: black;
text-align: center;
padding: 4px;
text-decoration: none;
text-transform: uppercase;
border: none;
font-family: "Trebuchet MS", Helvetica, sans-serif;
}
#top_links ul{
display: table-row;
}
#top_links li{
display: table-cell;
margin: 0;
}
#top_links a:hover {
color: pink;
}
</style>
</head>
<body<div id="top_links">
<ul>
<li>Register</li>
<li>Login</li>
</ul>
</div>
LOGIN.php file:
<?php
require_once('../../../secure_files/mysql_connect.php');
$title = 'Login';
include_once('header.php');
if(isset($_POST['validate'])) {
$errors = array();
function validate_func($value, $msg, $val_type) {
global $link;
switch ($val_type) {
case 'string':
if(empty($value)){
$errors[] = "You forgot to enter your email ".$msg;
}else{
$value = mysqli_real_escape_string($link, trim($value));
}
break;
case 'password':
if(empty($value)) {
$errors[] = "You forgot to enter your email ".$msg;
}else{
$value = trim($value);
}
break;
case 'number':
if(!isset($value)||!is_numeric($value)) {
$error[] = "You forgot to enter ".$msg." or the value you entered is not a number.";
}else{
$value = trim($value);
}
break;
}
return $value;
}
$email = validate_func($_POST['email'], "email", "string");
$password = validate_func($_POST['password'], "password", "password");
if(!count($errors) != 0){
foreach($errors as $value) {
echo $value." <br />";
}
}else {
$select_guest = "SELECT GUEST_INFO_ID FROM GUEST_INFO WHERE EMAIL = '$email' AND PASSWORD = sha1('$password') LIMIT 1";
$exec_select_guest = #mysqli_query($link, $select_guest);
if(mysqli_num_rows($exec_select_guest) != 1) {
echo "You are not an authentic user, you are being directed to the registration page...";
mysqli_close($link);
header("Refresh:3; url='REGISTRATION_FORM&HANDLE.php'");
}else{
$one_record = #mysqli_fetch_row($exec_select_guest);
setcookie('GUEST_INFO_ID', $one_record[0], 0, '/', '', 0, 0);
echo "You are an authentic user";
header("Refresh:3; url='GUEST_MAIN_MENU.php'");
}
}
} else{
?>
<div id="LOGIN_MAIN">
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method = "post" >
<div>
Email:<input type="text" name="email" id="email" />
</div>
<div>
Password:<input type='password' name='password' id='password' />
</div>
<div>
<input type='submit' name='submit' id='submit' value='Submit' />
<input type='reset' name='reset' id='reset' value='Reset' />
<input type="hidden" name="validate" ID="validate" value="Reset" />
</div>
</form>
</div>
<?php
}
include('footer.php');
?>
and my footer:
</body>
</html>
The reason is, that you echoed something before you set the headers.
Any header MUST be before any other output to be valid.
See the php-manual for header()
So remove
echo $value." <br />";
echo "You are not an authentic user, you a...";
or any output before the header-redirection and it'll work!
If you want to redirect AFTER the user has seen the response, you will have to work with a javascript redirection!
That would then be something like this:
<script>
// redirects after 3 seconds
setTimeout(function(){
window.location.href = "GUEST_MAIN_MENU.php";;
}, 3000);
</script>
Sidecomment:
Anyway, I would recommend to test the user credentials without loading a new (or the same) php-script again. Have a look at javascript ajax! Using this technique the user will stay on the same page and get a more immediate response that your app also can react to with messages and redirections.

How to submit error free form

Being a beginner, I am at a cross road on how to submit an error free form. Reference to the php file below, I have used 3 action settings with the following consequence:
Method 1
action = ""
This indicates the errors on same page whether there is an error or not.
Method 2:
action=""
This indicates the errors on same page whether there is an error or not.
Method 3:
action="User sch contact.php"
This opens a new page (User sch contact) with all the user input whether there is error or not.
Now I do not want the form submitted until every error is cleared by the user. Please how can I achieve this? Is there anything I am missing in php, sql, Mysql that will help me achieve this?
<!DOCTYPE html>
<html>
<head>
<title>PHP Exercise</title>
<style type="text/css">
body {font-family: Arial, Verdana, Helvetica,Sans-serif; padding: 0px;
margin-left: 50px;}
input:hover {background-color: rgb(250,250,150);}
.btn {padding: 5px 5px 5px 5px; background-color: rgb(240,240,240); font-
size: 12px; font-weight: bold; font-style: italic; border: 1px; }
.btn:hover {background-color: rgb(250,250,150);}
th {font-weight: bold; font-size: 14px; border: 1px; border-style: solid;
margin: 0px; border-spacing: 0px;}
.cdtl {text-align: left;}
td {font-weight: Normal; font-size: 14px; border: 1px; border-style: solid;
margin: 0px; border-spacing: 0px;}
.err {color: rgb(250,50,10); width: 200px; font-style: italic; border: 0px;
font-size: 14px;}
</style>
<script type="text/javascript">
var debugScript = true;
</script>
</head>
<?php
$username = $useraddy1 = $useraddy2 = $userfone = $useremail = $userurl
= "";
$firstgrade = $secondgrade = $thirdgrade = $fourthgrade = "";
$usernameerr = $useraddy1err = $useraddy2err = $userfoneerr =
$useremailerr = $userurlerr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["username"])) {
$usernameerr = "Name is required";
} else {
$username = test_input($_POST["username"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z0-9 ]*$/",$username)) {
$usernameerr = "Only alphanumerics and white space allowed";
} else {$usernameerr = "";}
}
if (empty($_POST["useraddy1"])) {
$useraddy1err = "Address is required";
} else {
$useraddy1 = test_input($_POST["useraddy1"]);
if (!preg_match("/^[a-zA-Z0-9 ]*$/",$useraddy1)) {
$useraddy1err = "Only alphanumerics and white space allowed";
} else {$useraddy1err = "";}
}
if (empty($_POST["useraddy2"])) {
$useraddy2err = "Address is required";
} else {
$useraddy2 = test_input($_POST["useraddy2"]);
if (!preg_match("/^[a-zA-Z ]*$/",$useraddy2)) {
$useraddy2err = "Only letters and white space allowed";
} else {$useraddy2err = "";}
}
if (empty($_POST["userfone"])) {
$userfoneerr = "Address is required";
} else {
$userfone = test_input($_POST["userfone"]);
if (!preg_match("/^[+0-9]*$/",$userfone)) {
$userfoneerr = "Only + numbers and white space allowed";
} else {$userfoneerr = "";}
}
if (empty($_POST["useremail"])) {
$useremailerr = "Email is required";
} else {
$useremail = test_input($_POST["useremail"]);
// check if e-mail address is well-formed
if (!filter_var($useremail, FILTER_VALIDATE_EMAIL)) {
$useremailerr = "Invalid email format";
}
}
if (empty($_POST["userurl"])) {
$userurl = "";
} else {
$userurl = test_input($_POST["userurl"]);
// check if URL address syntax is valid (this regular expression also
allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?
=~_|!:,.;]* [-a-z0-9+&##\/%=~_|]/i",$userurl)) {
$userurlerr = "Invalid URL";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h4>User Input</h4>
<form id="setUp" method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table id="contact" class="userInfo">
<tbody>
<tr>
<th class="cdtl">User Name:</td>
<td><input type="text" name='username' value="<?php echo $username;?>" />
</td>
<td class='err'><?php echo $usernameerr;?></td>
</tr>
<tr>
<th class="cdtl">Address1:Number, Street, City</td>
<td><input type="text" name='useraddy1' value="<?php echo $useraddy1;?>" />
</td>
<td class='err'><?php echo $useraddy1err;?></td>
</tr>
<tr>
<th class="cdtl">Address2:State, Country</td>
<td><input type="text" name='useraddy2' value="<?php echo $useraddy2;?>" />
</td>
<td class='err'><?php echo $useraddy2err;?></td>
</tr>
<tr>
<th class="cdtl">Telephone (International format)</td>
<td><input type="text" name='userfone' value="<?php echo $userfone;?>" />
</td>
<td class='err'><?php echo $userfoneerr;?></td>
</tr>
<tr>
<th class="cdtl">e-mail Address</td>
<td><input type="email" name='useremail' value="<?php echo $useremail;?>" />
</td>
<td class='err'><?php echo $useremailerr;?></td>
</tr>
<tr>
<th class="cdtl">Website (Optional)</td>
<td><input type="url" name='userurl' value="<?php echo $userurl;?>" /></td>
<td class='err'><?php echo $userurlerr;?></td>
</tr>
</tbody>
</table>
<br>
<input class="btn" type="submit" value="Submit" />
</form>
</body>
</html>
I have resubmitted this question in a different way. Basically, I was trying to validate a form on the client side. The best approach is to use both required and pattern in the input. With these 2, the form will not be submitted with a blank field & if user input does not follow the pattern. Further validation will of course be done on the server side for double assurance.
<form>
<b>User Id:<b><br>
<input id="userid" name="userid" type="text" required pattern="[A-Za-
z0-9.-_]{5,10}"><br>
<b>Password:<b><br>
<input id="userpswd" name="userpswd" type="password" required
pattern="[A-Za-z0-9&*]{8,20}"><br><br>
<b>SS Level:<b><br>
<input id="sslevel" name="sslevel" type="text" required pattern="[A-Za-z0-9]
{3,8}">
<input id='submit' type="submit" value="Submit form">
</form>

editing CSS of PHP grid

I have an editable grid where I want to edit the CSS such that the textarea to show the maximum width, but somehow I can't increase the width of the text area.
My database has three columns:
ID
Name
Gossip
I'm retrieving everything and displaying it in an editable grid using PHP.
index.php code
<?php
$db = new mysqli('localhost', 'root', '', 'bollywood');
$db->set_charset('utf8');
if ($db->connect_errno) {
die('Check the database connection again!');
}
$userQuery = 'SELECT Id,Name,Gossip FROM bollywood';
$stmt = $db->query($userQuery);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var textBefore = '';
$('#grid').find('td input').hover(function() {
textBefore = $(this).val();
$(this).focus();
}, function() {
var $field = $(this),
text = $field.val();
$(this).blur();
// Set back previous value if empty
if (text.length <= 0) {
$field.html(textBefore);
} else if (textBefore !== text) {
// Text has been changed make query
var value = {
'row': parseInt(getRowData($field)),
'column': parseInt($field.closest('tr').children().find(':input').index(this)),
'text': text
};
$.post('user.php', value)
.error(function() {
$('#message')
.html('Make sure you inserted correct data')
.fadeOut(3000)
.html('&nbsp');
$field.val(textBefore);
})
.success(function() {
$field.val(text);
});
} else {
$field.val(text);
}
});
// Get the id number from row
function getRowData($td) {
return $td.closest('tr').prop('class').match(/\d+/)[0];
}
});
</script>
<title></title>
</head>
<body>
<?php if ($stmt): ?>
<div id="grid">
<p id="message">Click on the field to Edit Data</p>
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Gossip</th>
</tr>
</thead>
<tbody>
<?php while ($row = $stmt->fetch_assoc()): ?>
<tr class="<?php echo $row['Id']; ?>">
<td><input type="text" value="<?php echo $row['Id']; ?>" /> </td>
<td><input type="text" value="<?php echo $row['Name']; ?>" /></td>
<td ><input type="textarea" cols="500" rows="100" value="<?php echo $row['Gossip']; ?>" /></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>
<?php else: ?>
<p>No actors added yet</p>
<?php endif; ?>
</body>
</html>
user.php code
<?php
// Detect if there was XHR request
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$fields = array('row', 'column', 'text');
$sqlFields = array('Id', 'Name', 'Gossip');
foreach ($fields as $field) {
if (!isset($_POST[$field]) || strlen($_POST[$field]) <= 0) {
sendError('No correct data');
exit();
}
}
$db = new mysqli('localhost', 'root', '', 'bollywood');
$db->set_charset('utf8');
if ($db->connect_errno) {
sendError('Connect error');
exit();
}
$userQuery = sprintf("UPDATE bollywood SET %s='%s' WHERE Id=%d",
$sqlFields[intval($_POST['column'])],
$db->real_escape_string($_POST['text']),
$db->real_escape_string(intval($_POST['row'])));
$stmt = $db->query($userQuery);
if (!$stmt) {
sendError('Update failed');
exit();
}
}
header('Location: index.php');
function sendError($message) {
header($_SERVER['SERVER_PROTOCOL'] .' 320 '. $message);
}
style.css code
body {
font: normal 14px Comic Sans, Comic Sans MS, cursive;
}
table {
width: 500px;
}
td, th {
border: 1px solid #d8d8bf;
}
th {
padding: 5px;
font: bold 14px Verdana, Arial, sans-serif;
}
td {
padding: 10px;
width: 200px;
}
td input {
margin: 0;
padding: 0;
// width:200px;
font: normal 14px sans-serif;
/** Less flicker when :focus adds the underline **/
border: 1px solid #fff;
}
td input:focus {
outline: 0;
border-bottom: 1px dashed #ddd !important;
}
#grid input {
// width: 200%;
}
You doing it wrong
<td ><input type="textarea" cols="500" rows="100" value="<?php echo $row['Gossip']; ?>" /></td>
Should be:
<td ><textarea cols="500" rows="100"><?php echo $row['Gossip']; ?></textarea>
textarea is html tag name but not input type. so change this.
<td ><input type="textarea" cols="500" rows="100" value="<?php echo $row['Gossip']; ?>" /></td>
to
<td ><textarea cols="500" rows="100"><?php echo $row['Gossip']; ?></textarea>
also add this css.
<style>
textarea {
resize: both;
width:700px;
}
</style>
also are you sure that you can get content using this.
<?php echo $row['Gossip']; ?>

Categories