Using PHP, but NOT using mysql(because I'm required not to by my mentor) I'm trying to create user login form where once submitted,
program will scan another file if information exists.
if user has no preceding info, they create one.
I'm trying to find a way to append these new user pass/username to an array, which will be located in a different file from the file containing user/pass input form.
when user goes back and fill out their newly created info and logs in,
program checks if the entered info(variables) are indeed contained inside the array.
So...I'm trying to do something like:
<?php
include "fileContainingArray.php";
print <<<here
<form method="post">
<input type="text" name="user"/>
<input type="text" name="pass"/>
<input type="submit" name="login"/>
</form>
<form method="post">
<input type="text" name="newuser"/>
<input type="text" name="newpass"/>
<input type="submit" name="createnew"/>
</form>
here;
if(isset($_POST["createnew"])){
/////append newly created login info to an array w/usernames and array w/passwords
}
if(isset($_POST["login"])){
if (in_array('username', $user) && in_array('password', $password)) {
///grants access///
}
so the question is, is it possible, and if so how can I append new variables to an existing array from a different file?
any help would be great!!thanks!!
An array from the other file should be readily accessible from the current file.
$anotherArray['index'] = $newVar;
OR
array_push($anotherArray, "index", $newVar);
However, I think you are trying to get a proper login/logout system working. In this case, you should set up a database, probably MySQL.
Variables are flushed when PHP session ends, so no permanent users can be created, and storing data in a 'text' file is very inefficient and can lead to problems with access etc.
Check http://www.php.net/manual/en/function.serialize.php. You can serialize PHP objects (e.g. a User object that you could define) into a file and then unserialize it. You could build up place to store your user data like that that is not a data base. I'm not saying that's any kind of advisable for a production environment.
Related
I'm trying to create a cookie for a web page. The cookie value will vary based on the users name. Does PHP have an input type function? I just want to add an input field to the page an then the PHP will use that to define the users name for the page. I have the create cookie code, just can't figure out how to get the name from the screen and insert it to the cookie code. Appreciate any suggestions. This is on a WP website.
Not natively because php does not execute in browser, it executes on your server, but it can be used to write an HTML input.
The syntax would look something like this:
echo '<input type="text" name="myinput">';
or
?>
<input type="text" name="myinput">
<?php
You would then use a form post, CURL, or AJAX function to send the data back to the server where a second PHP script would process the input.
That said, it would help to post your create cookie code, since you may not even need to send it back to the server, but just handle it all in the browser using Javascript in which case your submit button only needs to pass the input to a Javascript function instead of posting it.
Is this something you are looking for?
Here it just takes the value user input from the browser and set it as a cookie
<?php
if(isset($_POST['name']) && !empty($_POST['name'])){
setcookie('setcookie_name',$_POST['name']); // setting cookie
}
?>
<form action="" method="post">
<input name="name" value="" placeholder="Enter your name" />
<input name="submit" type="submit" value="Submit"/>
</form>
I need to populate an associative array from a form input. Each time the user clicks submit it runs the PHP script, then it redirects them back to the form in which they can add another key value pair to the array.
<form action="submit.php" method="post" name="form-one">
<input type="text" name="name">
<input type="text" name="id">
<button type="submit">Submit</button>
</form>
<?php
//Add input vales to associative array dynamically
?>
So each time the form gets processed, I need the name and id saved in a key value pair, adding on the previous one that was saved.
Well, that will be a bit trickier, as a php script is executed every time a form is passed and then terminated. What you could do is persist the previous data somewhere, to a database, or serialize it to a file, then simply read the file on execution, and then append your newest entry on top of that.
Another way of going about it is by using sessions. You could store the array in a session variable e.g. $_SESSION['array'], and simply append to that each time your form gets processed.
That is not a good solution, can't you directly work with the data that gets submitted? In your procss you would have to put the values into the session, that makes the handling unnecessary troublesome later on.
if(isset($_POST['form-one'])){
$_SESSION[formData[$_POST['id']]] = $_POST['name'];
}
This would put the array formdata in your session-array, the id becomes index and name the value.
just wanted to find out the safest way to do something so it is not vulnerable.
Say I have a url like www.mysite.com?name=nick
This loads a static html page with a form. One of the forms fields is
<input type="text" id="pName" value="" name="pName" readonly>
What is the best way to get the url param into the value of this input? Basically, I have an app which will be used by several people in different locations. I need a way to identify who is using it, so I thought I could just add their name into the url and then inject this into my form.
Any information appreciated,
UPDATE
Going off the comments, I have added this to the top of index.php
<?php
session_start();
if (!isset($_SESSION['pName'])) {
$_SESSION['pName'] = $_GET['pName'];
}
?>
And then the input is like so
<input type="text" id="pName" value="<?php $_SESSION['pName'] ?>" name="pName" readonly>
Would this be acceptable?
Use session and put $_SESSION['YourSessionVariable'] into textbox.
<?php
$valueForTextbox = '';
if(isset($_POST['yourSubmitName'])){
$_SESSION['pName'] = $valueForTextbox = $_POST['pName'];
}else if(isset($_SESSION['pName'])){
$valueForTextbox = $_SESSION['pName'];
}
?>
<input type="text" id="pName" value="<?php echo $valueForTextbox;?>" name="pName" readonly>
Why ?
What if I change url GET parameter ? It will be security issue as well..
Also if I have to maintain that data in many pages(say a wizard to complete) And if I delete some parameters from URL, it will create issue.
Query string will be unnecessarily big with GET parameters which can easily saved in sessions.
Edit :
When form is Not submitted. Fetch value from Database rather than taking from Query string. And after form submit put value in SESSION. Form posting will keep updating value for that session variable.
If the user is to be defined in the URL, you must check on the server, if the user is authorized.
Since you need to have a safe method to identify the authorized user, the identification happens before the form is called, for example through login.
On login you store the user's name on the server, usually in the session, then you forward him to the form.
If a user tries to call the form for another, not identified user, you will realize this on the server. The form comes back, but the user does not match the username stored in the session.
Now, as you already have the user in the session, the question arises, if you really need the user in the url. Reasons for that could be, that you want more than one form open at a time, or you have authorized access to the form of other users (for example admin access).
I´ve a multipart form with a mixture of default inputs (text, select etc.) and a file upload (<input type="file">).
I´m using a combination of form validation class and upload library of Codeigniter for form submission. That works great.
I´ve only one problem for what I haven´t found a solution yet: If the user selects an image but misses to fill another required field (like "name"), then the form validation class blocks the request and shows an error message to the customer.
But now I´ve the problem, that the image was already submitted successfully and I don´t want to let the user add the file again. So I want to pre-fill the file input with this data.
I´ve tried different things like:
<input type="file" name="image" value="<?php echo set_value('image','');?>" />
and also spent time on finding a solution on the web but without success.
On the server side, you do not get any information about where the file is located on the client's computer, so in the scenario of a user uploading an image successfully but the user hasn't filled out the rest of the fields properly, you have to simply omit the input type="file" field entirely but keep a store of where the file is located on your server. There's a few ways to go about this, but it all involves taking the absolute location of the uploaded file and:
Inserting it back as a hidden value using <input type="hidden" name="uploadedFile" value="<?php echo $absPath; ?>" /> then checking for the existence of $_POST['uploadedFile'] and utilizing it appropriately. But this isn't a solid idea as you're now exposing server paths to the end-user (opens yourself up to malicious attack.)
Starting a session and saving the absolute path in the $_SESSION variable while presenting the user with a simple token in their re-attempt form.
I'd stick with method 2, so assuming you've done all the work to validate the form and upload the file and your file is located in $absFilePath, you could do the following:
session_start(); // This needs to be at the very top of you PHP file
// ...
$formToken = md5(time());
$_SESSION['uploadedFile'][$formToken] = $absFilePath;
Then render the token as a hidden variable using:
if (!empty($_SESSION['uploadedFile'][$formToken]))
echo '<input type="hidden" name="formToken" value="'.$formToken.'" />';
and hide the file upload portion using
if (empty($_SESSION['uploadedFile'][$formToken]))
echo // <input type="file" output here...
finally inside of your form submission code check for the existence of a formToken value before attempting to load $_FILES['image'] using isset($_POST['formToken']), and handle it using:
$absFilePath = $_SESSION['uploadedFile'][$_POST['formToken']];
Bam! Now you have your absolute file path as if the file had been uploaded just like before.
Since you haven't given enough code, I can only given you enough instruction to get you started, but this should be more than enough.
I have a basic PHP form page that contains quite a large amount of data that will be saved into about 4-5 different tables in MySql once it is all done. Since constructing this save routine will take a bit of PHP I'm looking to have the POST action to not point at PHP_SELF and instead a separate PHP file for processing.
Where all general data such as phone numbers, email, zip codes, etc. will be validated prior to the submit is passed to the processor script, if an error is returned by the processor...
What is the best practice way to point back to the original form page (HTTP_REFERER) while maintaining data input?
Form page:
<form action="processor.php" action="post">
<!-- lots of fields -->
<input type="submit" id="submitButton" name="Save" value="Save" />
</form>
Processor page:
<?php
if ( isset($_POST['date']) && ($_SERVER['HTTP_REFERER'] == "form.php") )
{
$errors = false;
//attempt to put data in database
if ( $errors )
{
//Pass back to the form.php page with error message and all data intact
}
}
?>
I have come across this problem before, how we solved this was to put all the fields into a session, then redirect back to form.php using header("Location: form.php");
When the data was posted to the form, we stored the $_REQUEST into a $_SESSION['post']; if the validation failed, we sent it back to the form, populated the fields and unset the session.
So for example
$_SESSION['post']['field_a'] = $_REQUEST['field_a'];
$_SESSION['post']['field_b'] = $_REQUEST['field_b'];
With some fancy naming conventions you can just loop this to make it easy.
Then on the Form page, we just checked to see if there was some data, or just echo the data regardless.
$str_field_a = #$_SESSION['post']['field_a'];
...
<input name="field_a" value="<?php echo $str_field_a; ?>" />
...
unset($_SESSION['post']);
This is probably a messy way of doing this, but it has proven effective for our purposes. Just thought I'd share.
I would send a post back to form.php containing errors and values. I use the same method in my personal project.
if ( $errors ) {
?><form action="form.php" method="post" name="error">
<input type="hidden" name="errcode" value="<?php echo $errorcodes; /*or whatever message*/ ?>" />
<input type="hidden" name="anotherdata" value="anothervalue" />
<?php /*you can add all post datas here as hidden field*/ ?>
</form>
<script type="text/javascript">document.error.submit();</script><?php
}
And this is similar to my form.php
//first I set default blank variables for form
$formvalue="";
$formnumericvalue="";
//i set them, yay!
//if I get values from post.php, I update the values
if (isset($_POST['iserror'])) { //you can either echo a error message or update current data here, I'm showing this for both
$formvalue=$_POST['formvalue'];//don't forget to validate these!
$formnumericvalue=$_POST['formnumericvalue']; //don't forget to validate these!
}
//I also do this method for edit forms
//and finally I show the form
?>
<form name="form" method="post" action="post.php">
<input type="text" name="formvalue" value="<?php echo $formvalue; ?>" />
</form>
I think you can do that using an array of error.
Set error flag false (if error occurs then set it true and so not store in database).
Check element 1, if error then store it in array $error['name'] = 'value'
Similarly check all elements, and store using same procedure.
In the end if error flag is set to false do not store in database and (if on the same page, you will be able to access the array on form where you want to display error message. )
if(isset($error['elementname'])) echo $error['elementname'];
below the page.
However, the best approach is to use an Object Oriented approach.
[UPDATE]
storing php objects on html form element and passing php objects through GET method?
how to send redirect page pass variables as post variables from a php script
Also I guess, storing the whole object in SESSION would not be a bad approach