I'm a noob trying to get some functionalities done on a website. Unfortunately, I have very little authorization, so I would like to create a comment box as simply as possible without the use of databases or jQuery, JavaScript.
I did a lot of searches and I believe the easiest way is to create a log-like HTML with a comment form, to which the PHP script would append the entered text. This is what I've managed to fabricate so far:
$file = "updates.html";
$fh = fopen($file, 'a');
$file = "updates.html";
$fh = fopen($file, 'a');
$comment = echo $_POST["update"] \n";
fwrite($fh, $comment);
fclose($fh);
The updates.html file has a comment box of which action points at a php file with the content above. Of course, it doesn't work, there is a parsing error, but I have no idea how to use the variable there (if that's the cause of the problem). I just can't figure out how to do it... Do you have any suggestions? Thanks!
don't know what you would like to do ....
<?php
if(isset($_POST['update'])) {
// if a request update exists
$file = "updates.html";
file_put_contents($file, $_POST['update']."\n",FILE_APPEND);
}
?>
You opened your file twice.
You don't need to echo your $_POST['update]
<?php
$file = "updates.html";
$fh = fopen($file, 'a');
$comment = $_POST["update"] . "\n";
fwrite($fh, $comment);
fclose($fh);
?>
This answer is for anyone who may have a similar question in future.
In as much as adding comment without a database is impractical it is doable. Below is how you can go about it.
Step 1: Create a file and save it with the .php extension like comment.php
Step 2. create the usual html form and set the form method = "post" and form action to the name of the file like action = "comment.php"
<h3> Add a comment here </h3>
<form action="comment.php" method="post">
<label for="name">Name:</label>
<input type="text" name="yourname"><br>
<label for="name">Comment:</label>
<textarea name="comment" id="comment" cols="30" rows="10"></textarea>
<input type="submit" value="submit">
</form>
`
Step 3.
Write a php script within the same file comment.php to process the data from the form. Remember to enclose the script in the php tag
<?php
$yourname = $_POST['yourname'];
$comment = $_POST['comment'];
// format the comment data into how you want it to be displayed on the page
$data = $yourname . "<br>" . $comment . "<br><br>";
//Open a text file for writing and save it in a variable of your chosen.
//Remember to use "a" not "w" to indicate write. Using 'w' will overwrite
// any existing item in the file whenever a new item is written to it.
$myfile = fopen("comment.txt", "a");
//write the formatted data into the opened file and close it
fwrite($myfile, $data);
fclose($myfile);
// Reopen the file for reading, echo the content and close the file
$myfile = fopen("comment.txt", "r");
echo fread($myfile,filesize("comment.txt"));
?>
Puting it in file may cause problem because you need some kind of delimiter, you could encode it with base64 and append \n in the end of an entry
$input = base64_encode(htmlspecialchars($_POST['update'])); //consider using strip_tags as well to avoid injections
file_put_contents("updates.html", $input."\n");
to get entries use
$entires = file("updates.html");
if(count($entries) > 0)
{
foreach($entries as $entry)
{
echo base64_decode($entry);
}
}
else
{
echo 'no entries so far';
}
You should consider using at least SimpleXml if you don't want to use Db.
Required Field
"; } else { $v_firstname = ""; } if ($lastname=="") { $v_lastname= "Required Field
"; } else { $v_lastname= ""; } if ($password=="") { $v_password= "Required Field
"; } else { $v_password= ""; } if ($password!=$passwordRetype) { $v_passwordRetype= "Password did not match!
"; } else { $v_passwordRetype= ""; } if ($gender=="") { $v_gender= "Required Field
"; } else { $v_gender= ""; } if ($student_id=="") { $v_student_id= "Required Field
"; } else { $v_student_id= ""; } if ($firstname!="" && $lastname!= "" && $password == $passwordRetype && $student_id!= "" && $email!= "" && $gender!= ""){ $checkme=mysql_query("SELECT * FROM members WHERE student_id = '$student_id'") or die(mysql_error()); $checkmyid=mysql_numrows($checkme); if($checkmyid > 0){ header("location:checkid.php"); }else{ mysql_query("INSERT INTO members (firstname, lastname, password,url, gender, student_id, status_id,photo,account_status) VALUES ('$firstname','$lastname','$password','$email','$gender','$student_id','0','default.jpg','0')")or die(mysql_error()); $wewness = mysql_query("SELECT * FROM members WHERE student_id = $student_id")or die(mysql_error()); $getid = mysql_fetch_array($wewness); $_SESSION['member_id'] = $getid['memberid']; $_SESSION['login'] = 'true'; $_SESSION['studentid'] = $student_id; header("location:registerexec.php"); } } } if(isset($_POST['login'])){ $studentid = $_POST['studid']; $pass = $_POST['password']; $query2 = mysql_query("SELECT * FROM members WHERE student_id = '$studentid' AND password = '$pass' ") or die (mysql_error()); while($studid = mysql_fetch_object($query2)) { echo "$studid->member_id"; } $numberOfRows = MYSQL_NUMROWS($query2); if ($numberOfRows == 0) { } else if ($numberOfRows > 0){ $wewness = mysql_query("SELECT * FROM members WHERE student_id = $studentid")or die(mysql_error()); $getid = mysql_fetch_array($wewness); if($getid['account_status']==0){ $_SESSION['login'] = 'maybe'; $_SESSION['member_id'] = $getid['member_id']; $_SESSION['studentid'] = $getid['student_id']; header('location:registerexec.php'); }elseif($getid['account_status']==2){ $_SESSION['login'] = 'true'; $_SESSION['member_id'] = $getid['member_id']; $_SESSION['studentid'] = $getid['student_id']; header('location:hometest.php'); }elseif($getid['account_status']==1){ $_SESSION['login'] = 'maybe'; $_SESSION['member_id'] = $getid['member_id']; $_SESSION['studentid'] = $getid['student_id']; header('location:fill.php'); } } } ?>
by glen
Related
I'm trying to make a system where an administrator can add multiple people at the same time into a database. I want this system to prevent the administrator from adding people with email addresses already existing in the database.
IF one of the emails in the _POST["emailaddress"] matches with one of the emailaddresses in the db, the user should get a message saying one of the emails already exists in the database. To achieve this, I've tried using the function array_intersect(). However, upon doing so I get a warning saying:
Warning: array_intersect(): Argument #2 is not an array in ... addingusers.php on line 41
At first i thought it had something to do with the fact my second argument was an associative array, so I tried the function array_intersect_assoc, which returns the same warning. How can I solve this?
The code on addingusers.php
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors',1);
$conn = mysqli_connect('localhost','*','*','*');
$condition = false; // this is for the other part of my code which involves inserting the output into db
$name = $_POST["name"];
$affix = $_POST["affix"];
$surname = $_POST["surname"];
$emailaddress = $_POST["emailaddress"];
$password = $_POST["password"];
//amount of emailaddresses in db
$checkquery2 = mysqli_query($conn, "
SELECT COUNT(emailaddress)
FROM users
");
$result2 = mysqli_fetch_array($checkquery2);
// the previously mentioned amount is used here below
for($i=0; $i<$result2[0]; $i++){
// the actual emails in the db itself
$q1 = mysqli_query($conn, "
SELECT
emailaddress
FROM
users
");
// goes through all the emails
$result_array1 = array();
while ($row1 = mysqli_fetch_assoc($q1)) {
$result_array1[] = $row1;
}
$query1 = $result_array1[$i]["emailaddress"];
}
// HERE LIES THE ISSUE
for($i=0; $i<count($emailaddress); $i++){
if (count(array_intersect_assoc($emailaddress, $query1)) > 0) {
echo "One of the entered emails already exists in the database...";
echo '<br><button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.history.back();
}
</script><br>';
$condition = false;
}
else{
$condition = true;
}
}
EDIT
as the comments point out, $query1 is indeed not an array it is a string. However, the problem remains even IF i remove the index and "[emailaddress]", as in, the code always opts to the else-statement and never to if.
$query1 is not an array, it's just one email address. You should be pushing onto it in the loop, not overwriting it.
You also have more loops than you need. You don't need to perform SELECT emailaddress FROM users query in a loop, and you don't need to check the intersection in a loop. And since you don't need those loops, you don't need to get the count first.
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors',1);
$conn = mysqli_connect('localhost','*','*','*');
$condition = false; // this is for the other part of my code which involves inserting the output into db
$name = $_POST["name"];
$affix = $_POST["affix"];
$surname = $_POST["surname"];
$emailaddress = $_POST["emailaddress"];
$password = $_POST["password"];
$q1 = mysqli_query($conn, "
SELECT
emailaddress
FROM
users
");
// goes through all the emails
$result_array1 = array();
while ($row1 = mysqli_fetch_assoc($q1)) {
$result_array1[] = $row1['emailaddress'];
}
$existing_addresses = array_intersect($emailaddress, $result_array1);
if (count($existing_addresses) > 0) {
echo "Some of the entered emails already exists in the database: <br>" . implode(', ', $existing_addresses);
echo '<br><button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.history.back();
}
</script><br>';
$condition = false;
}
else{
$condition = true;
}
I have this script that checks a submitted form. It checks if all fields are all filled out, and checks if the user has submitted the form before. It also checks if the entered data is already in the database or not. When I try to check if the entered data is in the database, it always returns false. My question is: How can I efficiently check if the POST values are the same?
Code:
<?php
error_reporting(E_NOTICE ^ E_ALL);
$Name = $_POST['name'];
$ID = $_POST['id'];
$Topic_1 = $_POST['1'];
$Topic_2 = $_POST['2'];
$Topic_3 = $_POST['3'];
$Topic_4 = $_POST['4'];
$Topic_5 = $_POST['5'];
$Topic_6 = $_POST['6'];
$Topic_7 = $_POST['7'];
$Topic_8 = $_POST['8'];
$Topic_9 = $_POST['9'];
$Topic_10 = $_POST['10'];
$Topic_11 = $_POST['11'];
$Topic_12 = $_POST['12'];
$Topic_13 = $_POST['13'];
$Topic_14 = $_POST['14'];
$Topic_15 = $_POST['15'];
$IP = $_SERVER['REMOTE_ADDR'];
$Connect = new mysqli("127.0.0.1", "root", "", "Data");
$Check = 'SELECT * FROM Submissions WHERE School_ID = "'.$ID.'" AND IP = "'.$IP.'"';
$Insert = 'INSERT INTO Submissions (Name, School_ID, Topic_1, Topic_2, Topic_3, Topic_4, Topic_5, Topic_6, Topic_7, Topic_8, Topic_9, Topic_10, Topic_11, Topic_12, Topic_13, Topic_14, Topic_15, IP) VALUES ("'.$Name.'", "'.$ID.'", "'.$Topic_1.'", "'.$Topic_2.'", "'.$Topic_3.'", "'.$Topic_4.'", "'.$Topic_5.'", "'.$Topic_6.'", "'.$Topic_7.'", "'.$Topic_8.'", "'.$Topic_9.'", "'.$Topic_10.'", "'.$Topic_11.'", "'.$Topic_12.'", "'.$Topic_13.'", "'.$Topic_14.'", "'.$Topic_15.'", "'.$IP.'")';
if($Name && $ID != "")
{
if($Result = $Connect->query($Check))
{
$Rows = $Result->num_rows;
if($Rows == 0)
{
if($_POST != $_POST)
{
if($Go = $Connect->prepare($Insert))
{
if($Go->execute())
{
echo 'Thanks';
}
else
{
echo 'There Was An Error';
}
}
else
{
echo 'There Was An Error';
}
}
else
{
echo 'No Two Values Can Match.';
}
}
else
{
echo 'You Cant Vote Twice.';
}
$Result->close();
}
else
{
echo 'There Was An Error.';
}
}
else
{
echo 'Please Fill Out All Fields';
}
$Connect->close();
Your if statement should look like
if($name != "" && $check != "")
Here's the error:
if($_POST != $_POST)
You do probably want to compare the result from the db with the $_POST instead.
$Row = $Result->fetch_assoc();
if($Row != $_POST)
Prior to doing a comparison use var_dump() on the variables to check what they actually contain.
var_dump($Name);
var_dump($ID);
exit();
Then check for a negative or positive match.
if( !empty($Name) && empty($ID) ){
exit('ah, name filled in but not id ...');
}
You can even spoof that in a separate file.
<?php
$Name = 'Bob';
$ID = ''; // or use 0 or any test you want
var_dump($Name);
var_dump($ID);
if( !empty($Name) && empty($ID) ){
exit('ah, name filled in but not id ...');
}
Isolating problems like this will help you develop incrementally, get something working, then add more lines till you arrive at your destination.
To check if not two POST values are the same:
array_diff($_POST, array_unique($_POST));
What you looking for is following
$_POST['1'] = 'a';
$_POST['2'] = 'b';
$_POST['3'] = 'c';
$_POST['4'] = 'a';
$_POST['5'] = 'd';
$results = array_unique($_POST);
var_dump($results);
returns:
array
1 => string 'a' (length=1)
2 => string 'b' (length=1)
3 => string 'c' (length=1)
5 => string 'd' (length=1)
You can't really so easily check if a person did submit a form before.
One way is to add one more hidden field to form if the request came with POST.
Something like that:
<form method="POST" action="">
<?php
if(isset($_POST['submit'])) {
echo '<input type="hidden" name="second_post" value="1">';
} ?>
<!-- Other form items -->
<input type="submit" name="submit" value="1">
</form>
Then you can check is it a second time with:
if(isset($_POST['second_post'])) {
// Second time of form post;
} else {
// First (or zero) time post.
}
I am passing the string value through link in the URL to the next page like this <a href="ApplicationRegister.php?plan=trial">
In the ApplicationRegister.php page, i am getting this value like this $plan = $_GET["plan"];
and i will put this into a session variable like this $_SESSION['plans'] = $plan;
Here i am getting the value. but after the if statement i am not getting the value for this plan even after using Session variable.
My complete code is like this
$plan = $_GET["plan"];
echo $plan;
$_SESSION['plan'] = $plan;
$plans = $_SESSION['plan'];
echo $_SESSION['plans'];
include('connect.php');
If (isset($_POST['submit']))
{
$CompanyName = $_POST['CompanyName'];
$CompanyEmail = $_POST['CompanyEmail'];
$CompanyContact = $_POST['CompanyContact'];
$CompanyAddress = $_POST['CompanyAddress'];
$StoreName = $_POST['StoreName'];
echo $plans;
$myURL ="$_SERVER[HTTP_HOST]";
$myURL =$StoreName.'.'.$myURL;
if (stripos($myURL, 'www.') !== 0) {
$myURL = 'www.' . $myURL;
}
if (stripos($myURL, 'http://') !== 0) {
$myURL = 'http://' .$myURL;
}
if(stripos($myURL, '.com') !== 0) {
$myURL = $myURL . '.com';
}
echo $plans;
$RegistrationType = $_POST['RegistrationType'];
$Status = "Active";
$sql = "select * from plans where planname = '$plans'";
echo $sql;
mysql_query($sql) or die (mysql_error());
$planID = $row['planid'];
$query1 = "select count(CompanyEmail) from ApplicationRegister where CompanyEmail = '$CompanyEmail'" ;
$result1 = mysql_query($query1) or die ("ERROR: " . mysql_error());
$msg = "";
while ($row = mysql_fetch_array($result1))
{
if($row['count(CompanyEmail)'] > 0)
{
$msg = "<font color='red'> <b>This E-mail id is already registered </b></font> ";
break;
}
}
if($msg == "")
{
$query2 = "select count(URL) from ApplicationRegister where URL = '$myURL' ";
$result2 = mysql_query($query2) or die ("ERROR: " . mysql_error());
$msg = "";
while ($row = mysql_fetch_array($result2))
{
if($row['count(URL)'] > 0)
{
$msg = "<font color='red'> <b>This Stroename is already registered </b></font> ";
break;
}
}
if($msg == "")
{
$sql = "INSERT INTO ApplicationRegister(planid, CompanyName, CompanyEmail, CompanyContact, CompanyAddress, RegistrationType, ApplicationPlan, ApplicationStatus, URL, CreatedDate) VALUES ('$planID', '$CompanyName', '$CompanyEmail', '$CompanyContact', '$CompanyAddress', '$RegistrationType', '$plans', '$Status', '$myURL', NOW() )";
mysql_query($sql) or die(mysql_error());
$id = mysql_insert_id();
$_SESSION['application_id'] = $id;
if($plans == "trail")
{
header("Location: userRegister.php");
exit();
}
else
{
header("Location : PaymentGateway.php");
exit();
}
}
}
}
?>
Only in the beginning it holds the value , if i try to display it within theIf (isset($_POST['submit'])) it shows blank value for plans. Do not know what to do. Plz suggest
EDITED
Even after using like this, its the same. i do not know what may be the problem :(
$plan = $_GET["plan"];
echo $plan;
$_SESSION['plans'] = $plans;
echo $_SESSION['plans'];
// $plan = +$plan;
include('connect.php');
If (isset($_POST['submit']))
{
$CompanyName = $_POST['CompanyName'];
$CompanyEmail = $_POST['CompanyEmail'];
$CompanyContact = $_POST['CompanyContact'];
$CompanyAddress = $_POST['CompanyAddress'];
$StoreName = $_POST['StoreName'];
echo $_SESSION['plans'];
EDITED
In ApplicationRegister.php, i have passed the hiddenvalue which i got fro\m previous page like this
<input type="hidden" name="plan" value="<?php echo $plan ?>"/>
then POST method i have used this. Now i am getting the value for it. Thanks to all
EDITED
if($PlanName == "trail")
{
header("Location: userRegister.php");
exit();
}
else
{
header("Location : PaymentGateway.php");
exit();
}
It's because you're not calling session_start() at the top of the page. You need that for your sessions to persist across requests (which is the point of sessions)
As well as not calling session_start();, this code is wrong:
$plan = $_GET["plan"];
echo $plan;
$_SESSION['plan'] = $plan;
$plans = $_SESSION['plan'];
echo $_SESSION['plans'];
It should be:
$plan = $_GET["plan"];
echo $plan;
$_SESSION['plan'] = $plan;
$plans = $_SESSION['plans'];
echo $_SESSION['plans'];
You are setting $_SESSION['plan'] and then trying to access $_SESSION['plans'].
Also, are you clicking a link or submitting a form? You say that you have a link, yet your code tries to access values passed from a form.
If you are using a form, don't use links. Instead, use a select element to select a plan, and then change $plan = $_GET["plan"]; to $plan = $_POST["plan"];.
EDIT:
For the redirection problem, try this code:
echo "<pre>** Plan Name: **\n";
var_dump($PlanName);
echo "</pre>";
if($PlanName == "trail")
{
header("Location: userRegister.php");
exit();
}
else
{
header("Location: PaymentGateway.php");
exit();
}
and see what it outputs.
When someone clicks the link, it's going to set the variable properly. However, it's not going to hit the $_POST['submit'] logic, because it's not a post, just a get. Then, assuming your actually posting to that page at a later point, trying to access anything in $_GET will be null, and will then reset the session variable to null.
Your first page should have code something like this
<form action="ApplicationRegister.php" method="post">
<select name="plan">
<option value="trial">Trial</option>
</select>
<input type="submit"/>
</form>
Then, you check for $_POST['plan'] and $_POST['submit']
(Sorry for my bad english)
Well, I've 3 errors in my code.
Error's:
First of all it's show : Notice: Undefined index: form in C:\xampp\htdocs\evantechbd\index.php on line 461. When i run this form.
if any error found it's show error message, well, but correct field is empty. Example: In this form there is 4 fields. a) upload image, b) select discussion c) subject and d) message. Suppose you upload a image, select a discussion and write a subject but forgot to write message. Then It's show "Message Required" and every filed is empty. I don't want empty field which is correct.
After successfully submitted the form it's show "Discussion was submitted ". But after that if i refresh the page it's send the data to database. But I did not click submit button. why this happen?
Here is my code:
<?php
if ($_POST['form'] == "Submit") {
$err = array();
$filed = addslashes($_FILES['file']['tmp_name']);
$img_named = addslashes($_FILES['file']['name']);
$img_type = addslashes($_FILES['file']['type']);
#$imgd = addslashes(file_get_contents($_FILES['file']['tmp_name']));
function getExtension($str)
{
$i = strrpos($str, ".");
if (!$i) {
return "";
}
$l = strlen($str) - $i;
$ext = substr($str, $i + 1, $l);
return $ext;
}
$extension = getExtension($img_named);
$extension = strtolower($extension);
$image_named_uniq = uniqid() . '.' . $extension;
$upload_path_dis = 'user/manage/discussionimg/';
$diss = $_POST['type'];
$sub = $_POST['sub'];
$msg = $_POST['msg'];
$date = "On " . date("F Y h:i:s A");
if (!isset($_SESSION['uname']))
$err[] = "You need to login";
else {
$uname = $_SESSION['uname']; //session username
if (empty($sub) && empty($msg) && empty($filed))
$err[] = "All field required";
else {
if (empty($sub))
$err[] = "Subject Requried";
if (empty($msg))
$err[] = "Message Requried";
if (empty($filed))
$err[] = "SORRY, you have to be upload a image";
}
}
if (!empty($err)) {
foreach ($err as $er) {
echo "<font color=red>$er</font><br/>";
}
}
else {
$sql = mysql_query("INSERT INTO discussion VALUES ('', '$imgd', '$image_named_uniq',
'$diss', '$sub', '$msg', '$uname', '$date' ) ");
if (!$sql)
echo "Can't submit your discussion" . mysql_error();
if (!move_uploaded_file($_FILES['file']['tmp_name'], $upload_path_dis . $image_named_uniq)) {
die('File Not Uploading');
} else {
echo "Discussion was submitted";
}
}
}
?>
Many Thanks for your help!!
Kanta.
Try changing your first if condition as follows
if (isset($_POST['submit']))
Now most of web sites uses client side validations using javascript. You can use jquery frame work to make things easier. However since you already uses validations after the POST event. You have to set values to relevant fields as bellow code. It will set tha value of the subject.
<input type="text" name="sub" value="<?php if(isset($_POST["sub"])) echo $_POST["sub"]; ?>" size="46"/>
Yes if you refresh the code it will again do the post and insert. You have to do few controls. However these things depend on your data.
a. Make unique key indexes in the database
b. Check for existing record before the insertion.
c. Redirect your page to the same page after few seconds once the user see the successful message.
I am bulding a small ajax chat site and am adding an image upload with msg functionality built in PHP, MySQL and jquery with ajax. My code currently will let you upload a message, I can get the image ready for upload and store URL for the database.
But I need to pass the variable to another if statement checking when the user submits a message.
I cannot seem to get it across and into my database.
Tryed global var, other stuff - think must be missing something. It is probably something obvious, excuse the code I am a graphic designer learning code!
$imageurl = "";
if (isset($_FILES["file"])) {
//properties of uploaded file
$name = $_FILES["file"] ["name"];
$type = $_FILES["file"] ["type"];
$size = $_FILES["file"] ["size"];
$temp = $_FILES["file"] ["tmp_name"];
$error = $_FILES["file"] ["error"];
if ($error > 0) {
die("Error uploaded file!");
}
else
{
if ($type == "video/avi" || $size > 2000000) {
?>
<br>
<p><?die("format is not allowed or size too big!");?></p>
<?
}
else
{
move_uploaded_file($temp, "msg_image/" . $name);
}
}
//store url for insertation
$imageurl = "msg_image/" . $name;
echo '<p>You added a ' . $name . ' to your message</p>';
return $imageurl;
}
/////need the var in here to store and update mysql database
if (isset($_POST['message'])) {
$tostore = $imageurl;
$username = protect($_POST['username']);
$message = protect($_POST['message']);
$time = time();
$sql = "INSERT INTO messages
(username, msgcontent, imageurl, msgtime)
VALUES ('$username', '$message', '$tostore', $time)";
$result = mysql_query($sql);
}
Your "return $imageurl" statement is stopping your script prematurely.
http://php.net/manual/en/function.return.php
i.e.
echo "hello";
return "world";
echo "!";
will only return
hello