php script to get data from csv to blog website - php

I am trying to write a basic blog that i can post blogs and view them blogs. I have posted the blog by form action however what i want to try to do now is that get the data that i got from my csv into h1 h2 p2 on my viewpost.html. How would i be able to do this.
This is my index.html
<!DOCTYPE html>
<html>
<head>
<title>My Blog</title>
<link type='text/css' rel ='stylesheet' href="style.css"/>
</head>
<body>
<form action="form_process.php" method="post">
<label for="title">Title</label>
<input type="text" name="title" id='title'/>
<label for="desc">Description</label>
<input type="text" name="desc" id='desc'/>
<label for="cont">Content</label>
<input type="text" name="cont" id='cont'/>
<input type="submit" name="formSubmit" value="Submit" />
</body>
</html>
This is form_process.php
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['title']))
{
$errorMessage .= "<li>You forgot to enter a title!</li>";
}
if(empty($_POST['desc']))
{
$errorMessage .= "<li>You forgot to enter a description!</li>";
}
if(empty($_POST['cont']))
{
$errorMessage .= "<li>You forgot to enter a description!</li>";
}
$varTitle = $_POST['title'];
$varDesc = $_POST['desc'];
$varCont = $_POST['cont'];
if(empty($errorMessage))
{
$fs = fopen("mydata.csv","a");
fwrite($fs,$varTitle . ", " .$varDesc . ", " .$varCont . "\n");
fclose($fs);
header("Location: index.html");
exit;
}
}
?>
And lastly this is my viewpost.html
<!DOCTYPE html>
<html>
<head>
<title> View Post</title>
</head>
<body>
<div class="post">
<h1>Title</h1>
<h2>Description</h2>
<p>Content</p>
</body>
</html>

Related

Form action field unable to upload and move to new page together

EDITED: Answered by #James solution is bolded in the code below.
Thanks again #James.
I have a form(HTML) which has a text field and upload a file to database.
Before I was using
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST" name="form1" enctype="multipart/form-data"></pre>
It was working fine, now I want the page to submit the entries to database and display a different page so I tried this
<form action="page3.php"......>, but didn't worked.
However when I click Submit button it make the entry for text field in database but does not upload the file to database.
What I want it to do is: when I click submit button, text field gets entered in database, file gets uploaded to database folder(and my program make its path entry to database), and new page which is loaded for the user to see.
Any help is appreciated. Thanks.
my php code
<?php
//ob_start();
$host="localhost";
$username="root";
$password="";
$db_name="newrep";
$table_name="members";
$conn=new mysqli('localhost','root','','newrep');
if(!$conn){
die("cannot connect.");
}
//else if(!mysql_select_db($db_name)){
// die(" cannot select database.");
//}
session_start();
use foundationphp\UploadFile;
echo "Session value: ".$_SESSION['texas'];
$currentuser=$_SESSION['texas'];
echo $currentuser;
$current_year=date("Y");
//code for upload starts here
require_once 'src/foundationphp/UploadFile.php';
if (!isset($_SESSION['maxfiles'])) {
$_SESSION['maxfiles'] = ini_get('max_file_uploads');
$_SESSION['postmax'] = UploadFile::convertToBytes(ini_get('post_max_size'));
$_SESSION['displaymax'] = UploadFile::convertFromBytes($_SESSION['postmax']);
}
$max = 2048 * 1024;
$result = array();
//upload code ended above
if(!isset($_SESSION['texas']))
{
header('Location:login_page.php');
exit();
}
else {
if(isset($_POST['title'])){
echo "reaching the else";
if(isset($_POST['upload'])){
//upload in POST is for upload
print_r($_FILES);
$destination = __DIR__ . '/uploaded/'; //for upload
//upload code try and catch
try {
$upload = new UploadFile($destination);
$upload->setMaxSize($max);
//$upload->allowAllTypes();
$upload->upload();
$result = $upload->getMessages();
}
catch (Exception $e) {
$result[] = $e->getMessage();
}
}
$error = error_get_last();
if ($result || $error){
//<ul class="result">
if ($error){
echo "{$error['message']}"; }
if ($result) {
foreach ($result as $message) {
echo "<li>$message</li>";}}}
$file_path_variable= $destination.$_SESSION['current_filename'];
echo $file_path_variable;
$title=$_POST['title'];
$query="INSERT INTO proposal(title_prop, userName_prop,whitepaper_prop,year_prop) VALUES('$title','$currentuser','$file_path_variable','$current_year')";
$result_query=mysqli_query($conn,$query);
echo " in elseif ";
if(!$result_query){
echo " cannot insert ";
}
else {
**header('Location: page3.php');
exit();**
//echo "successful entry ";
}
}
//ob_end_flush();
?>
HTML code here:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Online Application</title>
<!-- <link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"> -->
<link href="bootstrap.min.css" rel="stylesheet">
<head><script src="bootstrap.min.js"></script> </head>
<body>
<div id="O_o"><br><h4>Texas State University</h4></div>
<div id="wrapper">
<form action=**"<?php $_SERVER['PHP_SELF']?>"** method="POST" id="whitepaper" name="whitepaper" role="form" enctype="multipart/form-data">
<legend><h5><b>Online Application</b></h5></legend>
<h4 id="reference" name="reference" class="heading-reference"><b>Proposal Whitepaper</b></h4>
<fieldset>
<center>
<div class="form-group">
<?php echo "Year of Proposal: $current_year";?><br>
<label class="label_title control-label" for="title">Submit Title of your proposal:</label>
<input id="title" name="title" type="text" placeholder="" class="input_title form-control" >
<p class="help-block">All fields are required.</p><!--
<button type="submit" id="submit_button" name="btn-primary" class="btn btn-primary"> Submit Title </button>-->
</div>
<div class="form-group">
<label class="label_whitepaper control-label" for="file">Upload the whitepaper of your proposal here: <br>Only .docx , .doc and .pdf format extensions are permitted.</label>
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max;?>">
<p><input type="file" id="filename" name="filename[]" title="Browse for whitepaper" class="btn-primary" multiple
data-maxfiles="<?php echo $_SESSION['maxfiles'];?>"
data-postmax="<?php echo $_SESSION['postmax'];?>"
data-displaymax="<?php echo $_SESSION['displaymax'];?>"></p>
File should be no more than <?php echo UploadFile::convertFromBytes($max);?>.<br>
<!--<p><input type="submit" name="upload" value="Upload File" class="btn-primary">-->
<button id="submit" name="upload" class="btn-primary" >Submit and continue</button>
</div>
</center>
</fieldset>
</form>
</div>
<script src="js/checkmultiple.js"></script>
<script src="jquery.min.js"></script>
<script src="prettify.js"></script>
<script src="bootstrap.file-input.js"></script>
<script>
$(document).ready(function(){
$('input[type=file]').bootstrapFileInput();
});
</script>
</body>
</html>
<?php }
mysqli_close($conn);
?>
You need to include enctype='multipart/form-data' in your form tag:
<form action='<?php echo $_SERVER['PHP_SELF']?>' method="POST" name="form1" enctype='multipart/form-data'>
Without it, attachments cannot be sent through the form.
Update
Try the below code. I fixed some HTML errors as well.
<?php
//ob_start();
$host="localhost";
$username="root";
$password="";
$db_name="newrep";
$table_name="members";
$conn=new mysqli('localhost','root','','newrep');
if(!$conn){
die("cannot connect.");
}
//else if(!mysql_select_db($db_name)){
// die(" cannot select database.");
//}
session_start();
use foundationphp\UploadFile;
echo "Session value: ".$_SESSION['texas'];
$currentuser=$_SESSION['texas'];
echo $currentuser;
$current_year=date("Y");
//code for upload starts here
require_once 'src/foundationphp/UploadFile.php';
if (!isset($_SESSION['maxfiles'])) {
$_SESSION['maxfiles'] = ini_get('max_file_uploads');
$_SESSION['postmax'] = UploadFile::convertToBytes(ini_get('post_max_size'));
$_SESSION['displaymax'] = UploadFile::convertFromBytes($_SESSION['postmax']);
}
$max = 2048 * 1024;
$result = array();
//upload code ended above
if(!isset($_SESSION['texas']))
{
header('Location:login_page.php');
exit();
}else {
if(isset($_POST['title'])){
echo "reaching the else";
if(isset($_POST['upload'])){
//upload in POST is for upload
print_r($_FILES['fieldname']);
$destination = __DIR__ . '/uploaded/'; //for upload
//upload code try and catch
try {
$upload = new UploadFile($destination);
$upload->setMaxSize($max);
//$upload->allowAllTypes();
$upload->upload();
$result = $upload->getMessages();
}catch (Exception $e) {
$result[] = $e->getMessage();
}
}
$error = error_get_last();
if ($result || $error){
//<ul class="result">
if ($error){
echo "{$error['message']}"; }
if ($result) {
foreach ($result as $message) {
echo "<li>$message</li>";
}
}
}
$file_path_variable= $destination.$_SESSION['current_filename'];
//echo $file_path_variable;
$title=$_POST['title'];
$query="INSERT INTO proposal(title_prop, userName_prop,whitepaper_prop,year_prop) VALUES('$title','$currentuser','$file_path_variable','$current_year')";
$result_query=mysqli_query($conn,$query);
//echo " in elseif ";
if(!$result_query){
echo " cannot insert ";
}else {
header('Location: page3.php');
exit();
//echo "successful entry ";
}
}
//ob_end_flush();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Online Application</title>
<!-- <link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"> -->
<link href="bootstrap.min.css" rel="stylesheet">
<script src="bootstrap.min.js"></script>
</head>
<body>
<div id="O_o"><br><h4>Texas State University</h4></div>
<div id="wrapper">
<form action="<?php= $_SERVER['PHP_SELF']?>" method="POST" id="whitepaper" name="whitepaper" role="form" enctype="multipart/form-data">
<fieldset>
<legend><h5><b>Online Application</b></h5></legend>
<h4 id="reference" name="reference" class="heading-reference"><b>Proposal Whitepaper</b></h4>
<center>
<div class="form-group">
<?php echo "Year of Proposal: $current_year";?><br>
<label class="label_title control-label" for="title">Submit Title of your proposal:</label>
<input id="title" name="title" type="text" placeholder="" class="input_title form-control" >
<p class="help-block">All fields are required.</p><!--
<button type="submit" id="submit_button" name="btn-primary" class="btn btn-primary"> Submit Title </button>-->
</div>
<div class="form-group">
<label class="label_whitepaper control-label" for="file">Upload the whitepaper of your proposal here: <br>Only .docx , .doc and .pdf format extensions are permitted.</label>
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max;?>">
<p><input type="file" id="filename" name="filename[]" title="Browse for whitepaper" class="btn-primary" multiple
data-maxfiles="<?php echo $_SESSION['maxfiles'];?>"
data-postmax="<?php echo $_SESSION['postmax'];?>"
data-displaymax="<?php echo $_SESSION['displaymax'];?>"></p>
File should be no more than <?php echo UploadFile::convertFromBytes($max);?>.<br>
<!--<p><input type="submit" name="upload" value="Upload File" class="btn-primary">-->
<button id="submit" name="upload" class="btn-primary" >Submit and continue</button>
</div>
</center>
</fieldset>
</form>
</div>
<script src="js/checkmultiple.js"></script>
<script src="jquery.min.js"></script>
<script src="prettify.js"></script>
<script src="bootstrap.file-input.js"></script>
<script>
$(document).ready(function(){
$('input[type=file]').bootstrapFileInput();
});
</script>
</body>
</html>
<? }
mysqli_close($conn);
?>

PHP MySQL display image from database

Hi I have form to make new article with informations and image. I susccesfuly save all info and image to database (i guess). And when I want to display info and image so only info works.
See in picture.
Any help? Thanks a lot
Inserting_post.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>APK Market</title>
<link rel="stylesheet" type="text/css" href="../style/style.css">
<link href="../bootstrap/css/bootstrap.css" rel="stylesheet" media="screen">
<script src="../bootstrap/js/bootstrap.min.js"></script>
<script src="../bootstrap/js/bootstrap.js"></script>
</head>
<body>
<form method="post" action="insert_post.php" enctype="multipart/form-data">
<div class="new_post">
<div class="headtitle">Insert new post</div>
<div class="new_title">
<p>New title</p>
<input type="text" name="title">
</div>
<div class="new_author">
<p>Author</p>
<input type="text" name="author">
</div>
<div class="new_keywords">
<p>Keywords</p>
<input type="text" name="keywords">
</div>
<div class="new_image">
<p>Image</p>
<input type="file" name="image">
</div>
<div class="new_content">
<textarea name="content" cols="20" rows="8"></textarea>
</div>
<div class="submit">
<input type="submit" name="submit" value="OK">
</div>
</div>
</form>
<script src="https://code.jquery.com/jquery.js"></script>
<script src="../bootstrap/js/bootstrap.js"></script>
</body>
</html>
<?php
include("../includes/connect.php");
if(isset($_POST['submit']))
{
$games_date = date('y-m-d-h');
$games_title = $_POST['title'];
$games_author = $_POST['author'];
$games_keywords = $_POST['keywords'];
$games_image = $_FILES['image']['name'];
$games_tmp = $_FILES['image']['tmp_name'];
$games_content = $_POST['content'];
if($games_title=="" or $games_author=="" or $games_keywords==""
or $games_content=="")
{
echo"<script>alert('any field is empty')</script>";
exit();
}
else
move_uploaded_file($games_tmp,"../uploaded_images/$games_image");
$insert_query= "insert into games(games_title,games_date,games_author,games_image,
games_keywords,games_content)
values ('$games_title','$games_date','$games_author','$games_image',
'$games_keywords','$games_cont ent')";
}
if(mysql_query($insert_query))
{
echo "<center><h1>Post published seccesfuly!</h1></center>";
}
?>
display page:
<div class="content">
<?php
include('connect.php');
$select_posts = "select * from games";
$run_posts = mysql_query($select_posts);
while($row=mysql_fetch_array($run_posts))
{
echo '<p class="games_title_result">' .$games_title = $row['games_title'];
echo '<p class="games_image_result"><img src="<?php echo $row["games_image"];?>';
echo '<p class="games_content_result">' .$games_content = $row['games_content'];
echo '<p class="games_date_result">' .$games_date = $row['games_date'];
echo '<p class="games_author_result">' .$games_author = $row['games_author'];
}
?>
</div>
Here's my answer:
echo '<p class="games_image_result"><img src="uploaded_images/'.$row["games_image"].'" />';
You got a syntax error where you include a <?php and ?> inside your php, and on your echo at that.
So when you look at your img's src, it would have those.
Also, you forgot to close your img tag and your other p tags.
Your image tag isn't closed properly and the path to the image is not complete. You are only specifying the filename. I am not sure about your directory structure
echo '<p class="games_image_result"><img src="uploaded_images/<?php echo $row["games_image"];?>" />';
Display Image from DataBase using php
# SQL Statement
$sql = "SELECT `idimage` FROM `yourTableName` WHERE id=" . mysqli_real_escape_string($_GET['id']) . ";";
$result = mysqli_query("$sql") or die("Invalid query: " . mysqli_error());
# Set header
header("Content-type: image/your image name which type of your image");
echo mysqli_result($result, 0);
}
else
echo 'Please check the ID!';
?>
I wish it's may be help you

PHP logic error in a php form code

I'm unable to solve the logical error in the code. I'm not sure what is wrong though it seems the logic is correct
This is my php:
<?php require_once("includes/connection.php"); ?>
<?php
include_once("includes/form_functions.php");
if(isset($_POST['submit']))
{
$errors = array();
if(isset($_POST['txtSpace']))
{
$choice_spc_port = $_POST["txtSpace"];
}
if(isset($_POST['txtNumber']))
{
$choice_no = $_POST["txtNumber"];
}
if(isset($_POST['txtLocation']))
{
$choice_loc = $_POST["txtLocation"];
if($choice_loc =="txtSetXY")
{
$x = $_POST["txtXLocation"];
$y = $_POST["txtYLocation"];
if($x == "")
{
$message = "You forgot to enter X Value";
}
elseif($y == "")
{
$message = "You forgot to enter Y Value";
}
else
{
$choice_loc = $x . "," . $y;
}
}
}
$user_name = $_POST["txtUserName"];
$user_email = $_POST["txtUserEMail"];
$animal_name = $_POST["txtAnimalName"];
$disp_msg = $_POST["txtDispMsg"];
$comments = $_POST["txtComments"];
if(!isset($_POST['txtSpace']))
{
$message = "Please select Space Portion";
}
elseif(!isset($_POST['txtNumber']))
{
$message = "Please select the number of animals";
}
elseif(!isset($_POST['txtLocation']))
{
$message = "Please select the desired location of animal";
}
elseif($user_name == "")
{
$message = "Please enter your name.";
}
elseif($user_email == "")
{
$message = "Please enter your email.";
}
elseif($animal_name == "")
{
$message = "Please enter the name of the animal.";
}
elseif($disp_msg == "")
{
$message = "What message you want to dedicate to the animal?.";
}
else
{
// validation
$required_fields = array('txtUserName','txtUserEMail','txtAnimalName','txtDispMsg');
$errors = array_merge($errors, check_required_fields($required_fields, $_POST));
$user_name = trim(mysql_prep($_POST['txtUserName']));
$user_email = trim(mysql_prep($_POST['txtUserEMail']));
$animal_name = trim(mysql_prep($_POST['txtAnimalName']));
$disp_msg = trim(mysql_prep($_POST['txtDispMsg']));
if(empty($errors))
{
/*if($choice_loc == "txtSetXY")
{
$x = $_POST["txtXLocation"];
$y = $_POST["txtYLocation"];
$choice_loc = $x . "," . $y;
}*/
if($choice_no == "other")
{
$choice_no = $_POST["other_field"];
}
$insert = "INSERT INTO db_form (db_space_portion, db_number, db_location, db_user_name, db_user_email, db_animal_name, db_message, db_comments) VALUES ('{$choice_spc_port}', '{$choice_no}', '{$choice_loc}', '{$user_name}', '{$user_email}','{$animal_name}','{$disp_msg}','{$comments}')";
$result = mysql_query($insert);
if($result)
{
echo("<br>Input data is succeed");
}
else
{
$message = "The data cannot be inserted.";
$message .= "<br />" . mysql_error();
}
}
else
{
if(count($errors) == 1)
{
$message = "There was 1 error on the form.";
}
else
{
$message = "There were " . count($errors) ." errors on the form.";
}
}
}
}
else
{
$user_name = "";
$user_email = "";
$disp_msg = "";
$comments = "";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test Form</title>
<meta charset="utf-8">
<link rel="stylesheet" href="css/reset.css" type="text/css" media="all">
<link rel="stylesheet" href="css/layout.css" type="text/css" media="all">
<link rel="stylesheet" href="css/style.css" type="text/css" media="all">
<script type="text/javascript" src="js/jquery-1.9.0.min.js" ></script>
<script type="text/javascript" src="js/cufon-yui.js"></script>
<script type="text/javascript" src="js/cufon-replace.js"></script>
<script type="text/javascript" src="js/Copse_400.font.js"></script>
<script type="text/javascript" src="js/imagepreloader.js"></script>
<script type="text/javascript" src="js/functions.js"></script>
<!--[if lt IE 9]>
<script type="text/javascript" src="js/ie6_script_other.js"></script>
<script type="text/javascript" src="js/html5.js"></script>
<![endif]-->
</head>
<body id="page5">
<!-- START PAGE SOURCE -->
<div class="body7">
<div class="main">
<section id="content">
<div class="wrapper">
<article class="col24">
<div class="pad1">
<h4>Kindly Fill the form</h4>
<?php if(!empty($message)){ echo $message; } ?>
<?php if(!empty($errors)){ echo display_errors($errors);}?>
<form id="TestForm" name="TestForm" method="post" action="form.php">
<div>
<div class="wrapper"> <strong><span>*</span> Desired Space</strong>
<div class="formText">
<input type="radio" name="txtSpace" value="RJ"/>Space Top<br />
<input type="radio" name="txtSpace" value="SM" />Space Bottom<br />
</div>
</div>
<div class="wrapper"> <strong><span>*</span> Select the Number</strong>
<div class="formText">
<input type="radio" name="txtNumber" value="100"/>100
<input type="radio" name="txtNumber" value="200"/>200
<input type="radio" name="txtNumber" value="500"/>500
<input type="radio" name="txtNumber" value="1000"/>1000
<input type="radio" name="txtNumber" value="10000"/>10000
<input type="radio" name="txtNumber" value="other"/>other
<input type="text" name="other_field" id="other_field" onblur="checktext(this);"/>
</div>
</div>
<div class="wrapper"> <strong><span>*</span> Select X & Y Value</strong>
<div class="formText">
<input type="radio" name="txtLocation" value="txtSetXY"/> Specify Photo Location<br />
<div style="padding-left:20px;">
X: <input type="text" id="locField" name="txtXLocation"><br />
Y: <input type="text" id="locField" name="txtYLocation"><br />
</div>
<input type="radio" name="txtLocation" value="Default"/>Default
</div>
</div>
<div class="wrapper"> <strong><span>*</span> Your Name:</strong>
<div class="bg">
<input type="text" class="input" name="txtUserName">
</div>
</div>
<div class="wrapper"> <strong><span>*</span> Your Email:</strong>
<div class="bg">
<input type="text" class="input" name="txtUserEMail">
</div>
</div>
<div class="wrapper"> <strong><span>*</span> Name of the animal:</strong>
<div class="bg">
<input type="text" class="input" name="txtAnimalName">
</div>
</div>
<div class="wrapper">
<div class="textarea_box"> <strong><span>*</span> The Message you want for your favourite animal:</strong>
<textarea name="txtDispMsg" cols="1" rows="1"></textarea>
</div>
</div>
<div class="wrapper">
<div class="textarea_box"> <strong>Comments:</strong>
<textarea name="txtComments" cols="1" rows="1"></textarea>
</div>
</div>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</div>
</article>
</div>
</section>
</div>
</div>
</body>
</html>
Errors:
Check this php fiddle here.
line 25. This is never shown even if I leave x textfield blank
$message = "You forgot to enter X Value";
same is with line 29. This is never shown even if I leave y textfield blank
$message = "You forgot to enter Y Value";
However if I enter the values in x and y textfield i.e. in txtXLocation and in txtYLocation they are being saved in db meaning it is just not checking the validation.
Thanks in advance
make sure you have connection.php file in includes folder and you have given correct path to reach that file.

Convert WebsiteField to emailField

Seeking to convert this .php page (that works) with the website input to an email input
I have changed all the websiteField items to emailField including an email Regex but it brings back a error message from the server. 500 - Internal server error.
There is a problem with the resource you are looking for, and it cannot be displayed.
<?php
require "config.php";
require "connect.php";
if(isset($_POST['submitform']) && isset($_POST['txn_id']))
{
$_POST['nameField'] = esc($_POST['nameField']);
$_POST['websiteField'] = esc($_POST['websiteField']);
$_POST['messageField'] = esc($_POST['messageField']);
$error = array();
if(mb_strlen($_POST['nameField'],"utf-8")<2)
{
$error[] = 'Please fill in a valid name.';
}
if(mb_strlen($_POST['messageField'],"utf-8")<2)
{
$error[] = 'Please fill in a longer message.';
}
if(!validateURL($_POST['websiteField']))
{
$error[] = 'The URL you entered is invalid.';
}
$errorString = '';
if(count($error))
{
$errorString = join('<br />',$error);
}
else
{
mysql_query(" INSERT INTO dc_comments (transaction_id, name, url, message)
VALUES (
'".esc($_POST['txn_id'])."',
'".$_POST['nameField']."',
'".$_POST['websiteField']."',
'".$_POST['messageField']."'
)");
if(mysql_affected_rows($link)==1)
{
$messageString = 'You were added to our donor list! »';
}
}
}
?>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Thank you!</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body class="thankyouPage">
<div id="main">
<h1>Thank you!</h1>
<h2>Add Yourself to our Donor List. </h2>
<div class="lightSection">
<form action="" method="post">
<div class="field">
<label for="nameField">Name</label>
<input type="text" id="nameField" name="nameField" />
</div>
<div class="field">
<label for="websiteField">Web Site</label>
<input type="text" id="websiteField" name="websiteField" />
</div>
<div class="field">
<label for="messageField">Message</label>
<textarea name="messageField" id="messageField"></textarea>
</div>
<div class="button">
<input type="submit" value="Submit" />
<input type="hidden" name="submitform" value="1" />
<input type="hidden" name="txn_id" value="<?php echo $_POST['txn_id']?>" />
</div>
</form>
<?php
if($errorString)
{
echo '<p class="error">'.$errorString.'</p>';
}
else if($messageString)
{
echo '<p class="success">'.$messageString.'</p>';
}
?>
</div>
</body>
</html>
<?php
function esc($str)
{
global $link;
if(ini_get('magic_quotes_gpc'))
$str = stripslashes($str);
return mysql_real_escape_string(htmlspecialchars(strip_tags($str)),$link);
}
function validateURL($str)
{
return preg_match('/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,#?^=%&:\/~\+#]*[\w\-\#?^=%&\/~\+#])?/i',$str);
}
?>
This is the same page with the changes made to reflect email instead of website
<?php
require "config.php";
require "connect.php";
if(isset($_POST['submitform']) && isset($_POST['txn_id']))
{
$_POST['nameField'] = esc($_POST['nameField']);
$_POST['emailField'] = esc($_POST['emailField']);
$_POST['messageField'] = esc($_POST['messageField']);
$error = array();
if(mb_strlen($_POST['nameField'],"utf-8")<2)
{
$error[] = 'Please fill in a valid name.';
}
if(mb_strlen($_POST['messageField'],"utf-8")<2)
{
$error[] = 'Please fill in a longer message.';
}
if(!validate_email($_POST['emailField']))
{
$error[] = 'The email you entered may be invalid! Please check same.';
}
$errorString = '';
if(count($error))
{
$errorString = join('<br />',$error);
}
else
{
mysql_query(" INSERT INTO dc_comments (transaction_id, name, email, message)
VALUES (
'".esc($_POST['txn_id'])."',
'".$_POST['nameField']."',
'".$_POST['emailField']."',
'".$_POST['messageField']."'
)");
if(mysql_affected_rows($link)==1)
{
$messageString = 'You were added to our donor list! »';
}
}
}
?>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Thank you!</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body class="thankyouPage">
<div id="main">
<h1>Thank you for your support!</h1>
<h2>Add your name to the donor list. </h2>
<div class="lightSection">
<form action="" method="post">
<div class="field">
<label for="nameField">Name</label>
<input type="text" id="nameField" name="nameField" />
</div>
<div class="field">
<label for="emailField">Email</label>
<input type="text" id="emailField" name="emailField" />
</div>
<div class="field">
<label for="messageField">Message</label>
<textarea name="messageField" id="messageField"></textarea>
</div>
<div class="button">
<input type="submit" value="Submit" />
<input type="hidden" name="submitform" value="1" />
<input type="hidden" name="txn_id" value="<?php echo $_POST['txn_id']?>" />
</div>
</form>
<?php
if($errorString)
{
echo '<p class="error">'.$errorString.'</p>';
}
else if($messageString)
{
echo '<p class="success">'.$messageString.'</p>';
}
?>
</div>
</body>
</html>
<?php
function esc($str)
{
global $link;
if(ini_get('magic_quotes_gpc'))
$str = stripslashes($str);
return mysql_real_escape_string(htmlspecialchars(strip_tags($str)),$link);
}
function validate_email($str)
{
return preg_match('.*?#.*?\...*', $str);
}
?>
Why will the email not work as planned and is the approach correct?
I am working with this DonationScript
Your problem may be in your regexp, the * is an unknown modifier in your code example. Try this... Delete the validate email function completely. Then change
if(!validate_email($_POST['emailField']))
to
if (!filter_var($_POST['emailField'], FILTER_VALIDATE_EMAIL))
and see if that works for you.

SESSION variable value is not passing

I'm trying to pass a value from a select input control on an HTML form.
When I hardcode it, it gets echoed, when not, all I get is this:
The invention type did not go through correctly.
Here is my page1.php:
<?php
session_start();
$_SESSION['invtype'] = $invtype;
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
if (isset($_POST['Submit'])) {
if ($_POST['firstname'] != "") {
$_POST['firstname'] = filter_var($_POST['firstname'], FILTER_SANITIZE_STRING);
if ($_POST['firstname'] == "") {
$errors .= 'Please enter a valid first name.<br/><br/>';
}
} else {
$errors .= 'Please enter your first name.<br/>';
}
if ($_POST['lastname'] != "") {
$_POST['lastname'] = filter_var($_POST['lastname'], FILTER_SANITIZE_STRING);
if ($_POST['lastname'] == "") {
$errors .= 'Please enter a valid last name.<br/><br/>';
}
} else {
$errors .= 'Please enter your last name.<br/>';
}
if (!$errors) {header("location: offerform_switch.php");
}
else {
echo '<div style="color: red">' . $errors . '<br/>
</div>';
}
}
?>
<!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" lang="en" xml:lang="en">
<head>
<title>Offer Form, Part 1</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="inventron_sage_short.css" type="text/css" />
<link rel="stylesheet" href="form.css" type="text/css" />
</head>
<body>
<div id = "logo">
<img src = "img/top.jpg" alt = "logo" />
</div>
<div id = "wrapper">
<div id="stylized" class="myform">
<form id="form" action="page1.php" method="post">
<p>
<label for="firstname">FIRST NAME*:
</label>
<input type="text" name="firstname" id="firstname" value="<?php echo $firstname?>" />
</p>
<p>
<label for="lastname">LAST NAME*:
</label>
<input type="text" name="lastname" id="lastname" value="<?php echo $lastname?>" />
</p>
<div id = "category">Categorize your invention:</div>
<div class="spacer"></div>
<p>
<select id="invtype" name="invtype">
<option value="0" selected="selected">Select type</option>
<option value="product">PRODUCT</option>
<option value="software">SOFTWARE</option>
</select>
<input type="submit" name="Submit" value="Next!" />
</div>
</div>
</body>
</html>
Here is my offerform_switch.php:
<?php
session_start();
// echo variable from the session, we set this on our other page
echo $_SESSION['invtype'];
$invtype = $_SESSION['invtype'];
//connect to your database ** EDIT REQUIRED HERE **
mysql_connect("mysql.myserver.com","myuser","mypassword"); //(host, username, password)
//specify database ** EDIT REQUIRED HERE **
mysql_select_db("invention") or die("Unable to select database"); //select which database we're using
switch ($invtype){
case "product":
include("page2_product.php");
break;
case "software":
include("page2_software.php");
break;
default:
echo "The invention type did not go through correctly.";
}
?>
What am I doing wrong?
Thank you!
It should be
$_SESSION['invtype'] = $_POST['invtype'];
You're missing "session_id();" right below the "session_start();". I don't know why exactly it's required, but if I remember correctly, it is.

Categories