file index.php
<html>
<head>
<title>Guset Book</title>
</head>
<body>
<h3>Guest book</h3>
<a href="/addNew.php">
<p><input type="button" value="Add in book" ></p>
</a>
<a href="/readAll.php">
<p><input type="button" value="Read all"></p>
</a>
</body>
file addNew.php
<html>
<head>
<title>Guset Book</title>
</head>
<body>
<h3>New</h3>
<form name='formAddNew' method='post' action="ControllerAdd.php">
<p>Author: <input type="text" name="nameAuthor"></p>
<p>Comment:</p>
<p><textarea rows="5" cols="40" name="commentAuthor" style="resize: none;"></textarea></p>
<p><input type="submit" name="submitAuthor" value="Submit"></p>
</form>
</body>
file Model.php
<?php
class GuestBook
{
private $author;
private $comment;
function __construct($author, $commment)
{
$this->author = $author;
$this->comment = $commment;
}
public function getAuthor()
{
return $this->author;
}
public function getComment()
{
return $this->comment;
}
}
$guestBookList = new ArrayObject();
$guestBookList[] = new GuestBook("Author", "Comment");
function addInList($author, $comment)
{
$guestBookList[] = new GuestBook($author, $comment);
}
?>
file ControllerAdd.php
<html>
<head>
<title>Add</title>
</head>
<body>
<?php
require_once "Model.php";
addInList($_POST["nameAuthor"], $_POST["commentAuthor"]);
?>
<h3>Succes</h3>
<input type="button" value="On main">
</body>
file readAll.php
<html>
<head>
<title></title>
</head>
<body>
<?php
require_once "Model.php";
foreach($guestBookList as $value)
{
echo("<br>-----------<br>");
echo($value->getAuthor());
echo("<br>");
echo($value->getComment());
}
?>
</body>
The problem is that complier don't throws a mistakes, but don't write the code into array from textboxes. It read in right way the info from textboxes, but don't write into array Plz help.
I suggest in your particular case you need to change behaviour of your Model, something like this:
it's only an example, and must not be used as is
I guess, this code don't crash OP source
<?php
class GuestBook {
private $source;
private $book;
function __construct($filename) {
$this->book = array();
$this->source = $filename;
$this->restore();
}
function getBook() {
return $this->book;
}
function restore() {
if (file_exists($this->source)) {
$records = file($this->source);
if (is_array($records)) {
while (count($records)) {
$line = trim(array_shift($records));
list($author, $comment) = explode(':splitter:',$line);
$this->book[] = new GuestBookRecord($author, $comment);
}
}
}
}
function save() {
$fd = fopen($this->source, 'w');
foreach ($this->book as $record) {
fwrite($fd, $record->getAuthor().':splitter:'.$record->getComment().PHP_EOL);
}
fclose($fd);
}
function addComment($author, $comment) {
$this->book[] = new GuestBookRecord($author, $comment);
$this->save();
}
}
class GuestBookRecord {
private $author;
private $comment;
function __construct($author, $commment) {
$this->author = $author;
$this->comment = $commment;
}
public function getAuthor() {
return $this->author;
}
public function getComment() {
return $this->comment;
}
}
$guestBook = new GuestBook('sample.txt');
// compatibility with OP source
$guestBookList = $guestBook->getBook();
// compatibility with OP source
function addInList($author, $comment) {
global $guestBook;
$guestBook->addComment($author, $comment);
}
But it's not so good. Here is minimum 2 problems, first - the code reads all of the records into memory, second - concurrent accessing. It's just an example.
Session are best way to pass variables in this case
if i understand properly then you want to pass text filds value from two page and use them in 3rd page in array.
Use this as reference
index.php
<?php
session_start();
if(isset($_POST['submit'])){
if(!empty($_POST['tex1'])){
$_SESSION['tex1'] = $_POST['tex1'];
header('location:form.php');
}
}
?>
<form method="POST">
<input type="text" name="tex1">
<input type="submit" name="submit" value="submit">
</form>
form.php
<?php
session_start();
if(isset($_POST['submit'])){
if(!empty($_POST['tex2'])){
$_SESSION['tex2'] = $_POST['tex2'];
header('location:final_page.php');
}
}
?>
<form method="POST">
<input type="text" name="tex2">
<input type="submit" name="submit" value="submit">
</form>
final_page.php
<?php
session_start();
print_r($_SESSION);
$_SESSION is global variable of php.
To read more about session. Please read http://php.net/manual/en/reserved.variables.session.php
file1.php
<form action="file2.php" method="POST">
<textarea rows="4" cols="50" name="data[]"> </textarea>
<input type="submit" value="Submit">
</form>
file2.php
<?php
session_start();
$formData = $_POST['data'];
//echo '<pre>'; print_r($formData); die;
$_SESSION['formData'] = $formData;
echo 'Open File 3 to check submitted data.'
?>
file3.php
<?php
session_start();
if(isset($_SESSION['formData']) && $_SESSION['formData'] != ''){
print_r($_SESSION['formData']);
} else {
echo 'Submit form first.';
}
session_destroy();
?>
Related
How can I display the message for $myGame variable after a post?
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$myGame = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["myGame"])) {
$myGame = "";
} else {
$myGame = test_input($_POST["myGame"]);
}
}
function test_input($data) {
$data = trim($data);
return $data;
}
?>
<h2>TITLE</h2>
<?php echo $myGame;?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="submit" name="submit" value="Submit" class="btn">
</form>
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
$myGame = "Does this message display after post?";
$_POST['myGame'] = $myGame;
}
?>
</div>
</body>
</html>
If you go to this page http://universitychess.com/creategame.php
and post, then scroll to the bottom, it shows the new url. I need it at the top of the page, but $myGame doesn't display it.
Firstly
If your script calls the same page you can leave action parameter empty (action="")
Secondly
You want to get $_POST["myGame"] variable but there is no input with myGame name.
Here is how I would do it:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$myGame = "";
if (isset($_POST))) {
if (!empty($_POST["myGame"])) {
$myGame = test_input($_POST["myGame"]);
}
}
function test_input($data) {
$data = trim($data);
return $data;
}
?>
<h2>TITLE</h2>
<?php echo $myGame;?>
<form method="post" action="">
<input type="text" name="myGame">
<input type="submit" name="submit" value="Submit" class="btn">
</form>
Additional information
You should not get $_POST values directly.
It is better to do it this way: filter_input(INPUT_POST, 'myGame') instead of $_POST['myGame']
filter_input
There is an error while redirecting the page from login to index(i.e server error // error 500). I used redirect_to function to call function.php from login.php file and i have included header function in function.php file. unfortunately, there is server error.I tried to solve it but i could not.i have posted my all four file.
login.php
<?php
require_once("../../includes/function.php");
require_once("../../includes/database.php");
require_once("../../includes/session.php");
require_once("../../includes/user.php");
if($session->is_logged_in()){
redirect_to("index.php");
}
//remember to give your form's submit tag a name= "submit" attribute
if(isset($_POST['submit'])){
$username = trim($_POST['username']);
$password = trim($_POST['password']);
//check database to see if username/password exit.
$found_user = User::authenticate($username,$password);
if($found_user){
$session->login($found_user);
redirect_to("index.php");
}else{
//username/password combo was not found in the database
$message ="Username/password incorrect.";
echo $message;
}
}
else{//form has not been submitted
$username = "";
$password = "";
}
?>
<?php if(isset($database)) {
$database->close_connection();
}
?>
<html>
<head>
<title>Photo Gallery</title>
<link href="boot/css/bootstrap.css" media="all" rel ="stylesheet" type
="text/css"/>
</head>
<body>
<div id="header">
<h1>Photo Gallery</h1>
</div>
<div id ="main">
<h2>staff login</h2>
</div>
<form action="login.php" method="post">
<table>
<tr>
<td>Username:</td>
<td>
<input type = "text" name = "username" maxlength="30" value="<?php echo
htmlentities($username);?>"/>
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type = "password" name= "password" maxlength = "30" value ="
<?php echo htmlentities($password);?>"/>
</td>
</tr>
<tr>
<td>
<input type="submit" name="submit" value = "login"/>
</td>
</tr>
</table>
</form>
</body>
</html>
index.php
<?php
require_once('../../includes/function.php');
require_once('../../includes/session.php');
if(!$session->is_logged_in()) {
redirect_to("login.php");
}
?>
<html>
<head>
<title>Photo Gallery</title>
<link href="boot/css/bootstrap.css" media="all" rel ="stylesheet" type
="text/css"/>
</head>
<body>
<div id="header">
<h1>Photo Gallery</h1>
</div>
<div id ="main">
<h2>staff login</h2>
</div>
<div id = "footer">Copyright<?php echo date("Y", time());?>,prayash
bhari</div>
</body>
</html>
function.php
<?php
ob_start();
function strip_zeros_from_data($marked_string =""){
//first remove the marked zeros
$no_zeros = str_replace('*0','',$marked_string);
//then remove any remaining marks
$cleaned_string = str_replace('*','', no_zeors);
return $cleaned_string;
}
function redirect_to($location = NULL){
if ($location != NULL){
header("Location : {$location}");
exit;
}
}
function output_message($message = ""){
if($empty($message)){
return "<p class = \"message\">{$message}</p>";
}
else{
return "";
}
}
function __autoload($class_name){
$class_name = strtolower($class_name);
$path = "../includes/{$class_name}.php";
if(file_exists($path)){
require_once($path);
}else{
die("the file {$class_name}.php could not found.");
}
}
ob_end_flush();
?>
sesssion.php
<?php
// A class to help work with Sessions
//In our case, primarily to mange logging users in and out
//keep in mind when working with sessions that it is generally
//inadvisable to store DB-relate objects in sessions
class Session{
private $logged_in = false;
public $user_id;
function __construct(){
session_start();
$this->check_login();
if($this->logged_in){
//actions to take right away if user is logged in
}else{
//actions to take right away if user is not logged in
}
}
public function is_logged_in(){
return $this->logged_in;
}
public function login($user){
//database should find user based on username/password
if($user){
$this->user_id = $_SESSION['user_id'] = $user -> id;
$this->logged_in = true;
}
}
public function logout(){
unset($_SESSION['user_id']);
unset($this->user_id);
$this->logged_in = false;
}
private function check_login(){
if(isset($_SESSION['user_id'])){
$this->user_id = $_SESSION['user_id'];
$this->logged_id = true;
}else{
unset($this->user_id);
$this->logged_in = false;
}
}
}
$session = new Session()
?>
error message
remove {} and put".." in
header("Location : {$location}");
instead of
header("Location:".$location);
You have to redirect to full URL so Try this,
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
redirect_to($url."index.php");
As Gyandeep Mentioned above change your function,too.
function redirect_to($location){
header('Location:'.$location);
exit();
}
Hope this helps.
I am stuck with writing View for my code igniter search form which need to use get..
I currently have this
Controller
<?php
class Search extends CI_Controller {
function __construct(){
parent::__construct();
}
public function index(){
$this->load->view('Search');
}
public function doSearch()
{
$this->load->model("Messages_model");
if ($this->input->get('search') !== FALSE) {
$data ['results'] = $this->Messages_model->searchMessages($this->input->get('search'));
} else {
$data['results'] = array();
}
$this->load->view("Search", $data);
}
Model
class Messages_model extends CI_Model{
function searchMessages($string){
$this->load->database();
$query = $this->db->query("SELECT * FROM messages WHERE text LIKE '%$string%'");
return $query->result();
}
View
<!DOCTYPE html>
<html>
<style>
</style>
<head>
<title></title>
</head>
<body>
<form action="<?php echo site_url('Search/doSearch');?>" method = "get">
<input type="text" name = "keyword"/>
<input type="submit" value = "Search" />
</form>
</div>
</body>
</html>
Can anyone help me out in getting search string displayed
Firstly, go to application/config/config.php and find $config['allow_get_array'] and make sure it's set to TRUE.
Then in your controller you would have something like this:
public function search()
{
$this->load->model("Messages_model");
if ($this->input->get('search') !== FALSE) {
$data ['results'] = $this->Messages_model->searchMessages($this->input->get('search'));
} else {
$data['results'] = array();
}
$this->load->view("Search", $data);
}
Please note that there isn't any validation happening on the string here so you will need to add your own.
Hope this helps!
EDIT
View file:
<!DOCTYPE html>
<html>
<style>
</style>
<head>
<title></title>
</head>
<body>
<form action="<?php echo site_url('search/doSearch'); ?>" method = "get">
<input type="text" name="keyword" value="<?php echo isset($search_value) ? $search_value : ''?>"/>
<input type="submit" value="Search" />
</form>
<?php
if ($search_passed && !empty($results)) {
foreach ($results as $result) {
//Code for displaying results
}
} elseif ($search_passed && empty($results)) {
echo 'No results found!';
}
?>
</div>
</body>
</html>
Controller Method:
public function doSearch()
{
$this->load->model("Messages_model");
if ($this->input->get('keyword') !== FALSE) {
$data ['results'] = $this->Messages_model->searchMessages($this->input->get('keyword'));
//Uncomment the line below to test
// echo '<pre>'; print_r($data['results']);die('</pre>');
$data['search_passed'] = TRUE;
$data['search_value'] = $this->input->get('keyword');
} else {
$data['search_passed'] = FALSE;
$data['results'] = array();
}
$this->load->view("Search", $data);
}
can someone explain me how to protect the profile page from the wrong user editing the URL to see some other users profile page. i am using a token class to generate a random number to protect against Cross Site Request Forgery. for some reason it doesn't work any suggestion or other way to do that
Also i get the following error : Undefined index: token in PhpProject22_CSRF\profile.php on line 12
<?php
session_start();
require_once 'Classes/Token.php';
$tk = new Token();
if(isset($_POST['username'],$_POST['product'],$_POST['token'])){
$username = $_POST['username'];
$product = $_POST['product'];
if(!empty($product) && !empty($username)){
if(Token::check($_POST['token'])){
echo $_POST['token'].'<br>';
$tk->get('username');
$_SESSION['user'] = $tk->name();
echo 'Process Order';
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>CSRF Protection</title>
</head>
<body>
<form action="" method="POST">
<div class="product">
<strong>Profile</strong>
<div class='field'>
Username: <input type='text' name='username'>
</div>
<input type='submit' value='Order'>
<input type='hidden' name='product' value='1'>
<input type='hidden' name='token' value='<?php echo Token::generate();?>'>
</div>
</form>
<?php
if(isset($_POST['username'])){
?>
<p>Hello <a href = 'profile.php?user=<?php echo $tk->name();?>'><?php echo $tk- >name();?></a>!</p>
<?php
}
?>
</body>
</html>
<?php
class Token{
private $_data;
public static function generate(){
return $_SESSION['token'] = base64_encode(openssl_random_pseudo_bytes(32));
}
public static function check($token){
if(isset($_SESSION['token']) && $token === $_SESSION['token']){
unset($_SESSION['token']);
return true;
}
return false;
}
public function get($item){
if(isset($_POST[$item])){
$this->_data = $_POST[$item];
}
}
public function name(){
return $this->_data;
}
}
?>
<?php
require_once 'Classes/Token.php';
session_start();
?>
<form action="" method="POST">
<input type='hidden' name='token' value='<?php echo Token::generate();?>'>
</form>
<?php
echo 'Hello '.$_SESSION['user'].'!<br>';
if(isset($_GET['user'])){
if(Token::check($_POST['token'])){
echo $_GET['user'];
}
}
?>
When checking post you need to do the following:
if($_POST){
if(isset($_POST['token']) && Token::check($_POST['token']){
code
}else{
error
}
}
If someone spoof the post, and doesn't include the token, you're going to get an undefined index error, because $_POST['token'] doesn't exist and you are referencing it.
I am trying to display a list of comments from a MySql database in PHP.
The foreach loop works as it displays the necessary html for each comment in the database, but no actual content from the database is being pulled through.
Comment class
class Comment {
protected $_id;
protected $_user;
protected $_commentText;
protected $_dateTimePosted;
public function __construct()
{
$this->_dateTimePosted = new DateTime();
$this->_dateTimePosted->format(DATE_RFC3339);
}
public function get_id()
{
return $this->_id;
}
public function set_id($value)
{
$this->_id = $value;
}
public function get_user()
{
return $this->_user;
}
public function set_user($value)
{
$this->_user = $value;
}
public function get_commentText()
{
return $this->_commentText;
}
public function set_commentText($value)
{
$this->_commentText = $value;
}
public function get_dateTimePosted()
{
return $this->_dateTimePosted;
}
public function set_dateTimePosted($value)
{
$this->_dateTimePosted = $value;
}
}
CommentFunctions.php
include 'dbConnect.php';
class CommentFunctions {
protected $conn;
public function __construct()
{
$this->conn = dbConnect();
}
public function get_comments()
{
$sql = "SELECT * FROM comments";
$stmt = $this->conn->stmt_init();
$stmt->prepare($sql);
$stmt->execute();
$stmt->store_result();
$comments = array();
while ($row = $stmt->fetch())
{
$comment = new Comment();
$comment->set_id($row['id']);
$comment->set_user($row['user']);
$comment->set_commentText($row['comment_text']);
$comment->set_dateTimePosted($row['datetime_posted']);
$comments[] = $comment;
}
return $comments;
}
}
Index.php
<?php
include './includes/Comment.php';
include './includes/CommentFunctions.php';
$comments_func = new CommentFunctions();
$all_comments = $comments_func->get_comments();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Comments</title>
<link rel="stylesheet" type="text/css" href="./css/Master.css" />
<link rel="stylesheet" type="text/css" href="./css/Site.css" />
</head>
<body>
<div id="Container">
<h2>Comments</h2>
<a class="reload-comments" href="/">Refresh</a>
<div id="Comments">
<?php if (!$all_comments) {
echo 'No comments yet.';
} ?>
<?php foreach ($all_comments as $c) { ?>
<div class="comment">
<input class="id" type="hidden" value="<?php echo $c->get_id(); ?>" />
<div class="author">Posted by <?php echo $c->get_user(); ?></div>
<div class="comment-text">
Posted <?php echo $c->get_dateTimePosted(); ?>
<p><?php echo $c->get_commentText(); ?></p>
</div>
</div>
<?php } ?>
</div>
<div id="AddComment">
<form name="add_comment_form" id="add_comment_form" action="index.php" method="post">
<label for="user">Your Name:</label>
<input name="user" id="user" type="text" /><br />
<label for="comment_text">Comment:</label>
<textarea name="comment_text" id="comment_text" rows="5" cols="10"></textarea><br />
<input name="submit" id="submit" type="submit" value="Submit" />
<input id="reset" type="reset" class="hidden" />
</form>
</div>
<div class="loader"></div>
<div class="response"></div>
</div>
</body>
Comments can be added, the data is stored fine in the database, and the loop runs the correct number of times, but the code such as echo $c->get_commentText(); is not displaying a value.
Appreciate any help.
Looks like you're using mysqli.
You're forgetting a key step: binding your result variables.
See http://www.php.net/manual/en/mysqli-stmt.bind-result.php and the examples there for more info on how to get actual values back.
try a
var_dump($all_comments)
after you fetch it, to prove that there is actually something in the array
next step would be to check that the sql worked. I am not sure what database layer you are using so i'm not sure what the check to do that would be.
i would assume that this method should have a return value you can check
$stmt->execute();