I have a form which I want to validate with PHP. The poster upload from Uploadcare's widget is part of that form.
Sometimes users have to go backward in the form to fix stuff - an incorrect email, etc. I want to have the chosen upload file persist within that form.
This works when the back button is clicked, but I cant rely on that. I'm using PHP POST variables to reload and repopulate the form.
My question: can I use a POST variables with the Uploadcare input button to make it "remember" and reload the chosen picture the user has previously uploaded?
My current code.
<input type="hidden"
role="uploadcare-uploader"
data-preview-step="true"
data images-only="true"
name="adposter"
style="display: inline-block;" />
Is it possible to do something like:
<input type="hidden"
role="uploadcare-uploader"
data-preview-step="true"
data-images-only="true"
name="adposter"
style="display: inline-block;"
value="<?php print isset($_POST["adposter"]) ? htmlspecialchars($_POST["adposter"]) : ""; ?>"
/>
As one would with other fields? Obviously the Uploadcare input widget has its own way of doing things, hence the query.
As the documentation says:
The value of [role=uploadcare-uploader] input is either empty or CDN link with file UUID.
If you externally set the value of the input and trigger the DOM change event, it will be reflected in the widget. For example, setting it to a file UUID or a CDN link will show that file as uploaded in the widget. You can do this on a live widget or even before it's actually loaded.
So your second snippet should work correctly.
You may also want to know the way to set widget's value via JS:
var widget = uploadcare.Widget('[role=uploadcare-uploader]');
widget.value("https://ucarecdn.com/e8ebfe20-8c11-4a94-9b40-52ecad7d8d1a/billmurray.jpg");
Sorted this. It can be done with Value. Great!
https://uploadcare.com/documentation/widget/#input-value
You can use $_POST to pass on variables from the one form to another just as you described using hidden fields. But this is not very efficient and as you write the information back to the client, they could change that.
A better way to save these kind of variables is to make use of $_SESSION:
The session support allows you to store data between requests in the
$_SESSION superglobal array. When a visitor accesses your site, PHP
will check automatically (if session.auto_start is set to 1) or on
your request (explicitly through session_start()) whether a specific
session id has been sent with the request. If this is the case, the
prior saved environment is recreated.
http://php.net/manual/en/intro.session.php
So after the image was uploaded you store the image id in a $_SESSION:
session_start();
$_SESSION['imageid'] = 123456;
Then even forms later you can access the imageid simply by using the $_SESSION variable again:
session_start();
var_dump($_SESSION['imageid']);
int 123456
See the php documentation for more information on sessions: http://php.net/manual/en/book.session.php
Related
I am new to PHP and am taking the PHP course on W3Schools. In the form handling part of the course, I read that there are two methods of handling form data: POST and GET. I understand that depending on the method used, a superglobal variable is created which stores the data as key-value pairs. And at the destination page, the data is retrieved from this variable (using $_POST["key"] or $_GET["key"]).
But my question is: Where is the superglobal variable ($_POST or $_GET) stored? If it is on that same page on which the form exists, how can it be accessed by another destination page specified in the action attribute of the form tag?
Is it that the same set of these superglobal variables are accessible by all the pages on the server (contrary to my present belief that each page has its own set of those)?
The code below should make my question more clear:
File index.php
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
File welcome.php
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>
W3Schools explains as follows:
When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST method.
To display the submitted data you could simply echo all the variables.
How do the variables $_POST["name"] and $_POST["email"] reach welcome.php?
Superglobals do not refer to the lifetime of a variable, but the scope in which the variable can be accessed.
Session variables can be accessed by other pages.
Also, regarding your comment "If that is the case, how can the second.php display the form data entered in first.php?"
first.php should save data to a database. second.php should read data from the database. If you are very new, I would suggest looking in to MySQL as a database. It plays very well with PHP.
When you send a request to a web server (i.e. apache, nginx), the request is parsed into pieces to be understood. Then, in PHP's case, the file requested is sent to the PHP interpreter with the data from the request.
In your example, you want a form to send a POST request to the page welcome.php. (If you're new to requests methods GET/POST/etc, then w3schools has a simple explanation on that: http://www.w3schools.com/tags/ref_httpmethods.asp) Your form has the method set to post, this can be get but it generally never is. If a user pressed a submit button within a tag, then the form sends to the request to the page set in action using the method set in method. Your form will send a POST request with the data name="..." and email="...".
When this request reaches PHP, all data sent to it will be stored in the method global variable. All post request place their data in $_POST, all get requests place their data in $_GET.
So when you submit your forms POST request, the page welcome.php will be requested by your browser (Firefox/Chrome) using the method POST and sending the data name and email in that request. On your server, PHP will open the file welcome.php and place the data into the $_POST array. Then, since $_POST is global, anywhere within welcome.php will have access to this variable.
If you manually go to the page welcome.php, you will be performing a GET request. Generally, only way to send a post request is through a form. So manually going to that page will have $_POST set to an empty array.
When I was learning PHP, I almost always had these lines at the top of the page so I knew what was going on:
<pre><?php print_r($_GET);?></pre>
<pre><?php print_r($_POST);?></pre>
This will print out the arrays in a pretty format, and the tags will make sure they're formatted correctly in the browser (since print_r uses newline characters, and browsers ignore those unless in pre tags).
You could also swap print_r with var_dump to get way more info about the variable.
This is a simple answer, there's way more to web technologies. And once you understand PHP enough I'd move into frameworks like CakePHP or CodeIgniter which takes away a lot of the little bits. It's important to understand the basics first though.
Regarding your edit:
<form action="welcome.php" method="post">
The method="post" bit means that when the user hits "Submit" (or whatever triggers action="welcome.php") the data will be collected from the form element and sent as POST data to the action target -- since it's a php file, you can then access this data through the superglobal, $_POST, as you've noted.
The name property in each of the inputs inside the form sets the key for each element of the POST data that is sent, and whatever the user entered in the input will be the corresponding value to that key.
For instance, if the user entered "foo" for the name, and "bar" for the email, your $_POST data in welcome.php should look something like:
Array
(
[name] => foo
[email] => bar
)
Just learning about passing variables from page to page in php, and trying to find the best way to do so for me, as I have to pass ~10 variables between 5 pages. On the first page, does it make sense to have a form:
<form method="post">
<input type="hidden" name="test" value="<?php $test ?>" />
</form>
Then on the next page could I receive this variable using POST? I would not like to have an ACTUAL form, just use it as a storage area for my variables. Also, what do I use for action= if the second page is called second.php.
Any help is appreciated, thanks
Short Answer: Forms only work when submitted. You probably want to use sessions.
Longer Answer:
It does not make sense to have a form without user input. That's what it exists for.
the action= attribute on a form reflects where the form would be submitted. If the processing page is second.php then the action= attribute should point there.
Sessions are not the only possibility. PHP can also set cookies, and if the server doesn't care about the data (only being used as a medium), you can use HTML5's localStorage.
Really, if you need to be passing 10 variables through all five pages, you're probably better off using sessions. You can store all of them as part of the $_SESSION variable and access them from any page as long as the session is kept alive.
You can't use $_POST variables to store data in a user's session.
You should use:
Sessions
Cookies
HTML5 storage
It depends on what you want to do, you have various options:
1. Using a form and post as you outlined. In this case, on page 1 your action="second.php"
2. Passing the data via URL using GET
3. Sessions, as stated by the previous two posts
4. Cookies
If I understand your question correctly you could try the following to POST your values without having the form appear on the page or actually be on the page at all. You need to have the jQuery library referenced in order to use this code.
function hiddenPost(param1) {
$('<form />')
.hide()
.attr({ method: "post" })
.attr({ action: "http://my-URL-here.com/SomePage.php" })
.append($('<input />')
.attr("type", "hidden")
.attr({ "name": "post_data" })
.val(param1)
)
.append('<input type="submit" />')
.appendTo($("body"))
.submit();
}
You can retrieve the POST values on the page you POST to in the same manner as if it was a regular POST with a form tag.
For PHP:
var postData = $_POST["post_data"];
Hope that helps.
I swear i couldn't find a simple working solution for this.
On a form i have inputs that have names containing "[]" and i cant change the names of the inputs because they are part of a script.
I want to php POST the values of those inputs at the next page, after the form submit.
Example of input
<input type="text" name="CustomFields[13]" id="CustomFields_13_1" value="">
Anyone knows how to accomplish it?
I want to do it using PHP only
If the name is CustomFields[13], then you can access it at $_POST['CustomFields']['13'].
You "cannot" POST something with PHP. It's always the client that POSTs to the server. PHP is running on server side.
I recommend that you use sessions and save there the values that you need to have available in next pages.
This is how you set a session:
session_start();
$_SESSION['CustomField'] = "test";
And this is how you get it:
session_start();
echo $_SESSION['CustomField']; //Should display "test"
I'm trying to store the redirect URL for use a few pages later but I'm having trouble figuring out how to get it from one place to another.
Usually I'd just pass a variable thru the URL, but since my redirect URL contains URL variables itself, this doesn't exactly work.
To give you a better idea of what I'm trying to do, here's the structure.
PAGE 1: User can click a link to add content on PAGE 2
PAGE 2: User enters text. Submitting the form on this page calls "formsubmit.php" where the MySQL data entries are handled. At the end of this I need to redirect the user to PAGE 1 again. The redirect URL needs to exactly match what was originally on PAGE 1
Does anyone have any suggestions on how to go about this?
You should use $_SESSION to store the variable in session memory. As far as specifics go with how to handle this in particular, you should be able to figure it out (store the variable, check if it exists later, if so redirect etc etc) but $_SESSION is going to be much more efficient / less messy than trying to pass things back and forth in query strings.
To declare a session variable you would do something like this:
$_SESSION['redirUrl'] = "http://www.lolthisisaurl.com/lolagain";
And then to reference it you just do
$theUrl = $_SESSION['redirUrl'];
Here is some material to get you started: http://php.net/manual/en/reserved.variables.session.php
I would recommend either using session variables, or storing the redirect url in a hidden form parameter. Session variables are pretty simple; just initialize the session (once, at the top of each page), and then assign variables to the $_SESSION global var:
<?php
session_start();
...
$_SESSION['redirect_url'] = whatever.com;
...
Hidden form parameters work by sending the data from page to page as form data. On the backend, you would add code that would put the URL to be stored in a form variable:
<input type='hidden' name='redirect_url' value='<?php echo $redirect_url; ?>';
On each page, you can take the URL out of the $_POST or $_GET variable (whichever is appropriate) and insert it into a hidden form in the next page.
You can use urlencode and urldecode to pass a string that contains elements that would otherwise break a url in a url query.
I can see two possible solutions :
get the previous page from document.referrer ([edit] find more info on this SO thread : getting last page URL from history object - cross browser?)
store the previous url via a session variable ([edit] MoarCodePlz pointed this out in his answer)
Regards,
Max
You can add this hidden field in to your form:
<input type="hidden" name="referer" value="<?php echo $_SERVER['HTTP_REFERER']; ?>">
Then use header() to redirect to this page:
header('Location: '. $_POST['referer']);
I am that kind that spends more time looking for bugs in web projects and correct them, but I still have one question about the use of the GET and POST method
To summarize , I often use the GET method for queries that may be coming from links or simple buttons example :
Click me
and for forms (signup,login, or comment) I use the post method. but the question is:
sometimes (Multi-steps signup for e.g), I may need to pass the info collected from the form in page 1 to a page 2 (where the user can find a captcha for e.g). in order to send them to the database if the captcha test is Okey. But the question is , how to pass those info to a next page via a POST method without using a hidden form?
Do I need to recreate a POST method from scratch with a socket?
thank you
You can use JavaScript (jQuery):
First u need to load jQuery ( using google as host or you download it):
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js"></script>
Then...
<script type="text/javascript">
$(document).ready(function() {
$('#Link').click(function() {
$.post("example.php", { n: "203000"} );
});
});
</script>
<a id="Link" href="#">Click me</a>
Edit:
after that save it in the SESSION in example.php
$ _SESSION['N'] = (int) $_POST['n'];
When this value will be stored on the server side. And tied to the client session, until he closes browser or that it set the time for that session on the server side runs out.
Edit2:
There is also another possibility to post requst, yes ..
But I do not like this method myself ...
And here is the form used, something the OP did not want.
<form name="myform" action="example.php" method="POST">
<input type="hidden" name="n" value="203000">
<a id="Link" onclick="document.myform.submit()" href="#">Click me</a>
</form>
Use sessions to store the data until you submit them:
http://de.php.net/manual/en/intro.session.php.
Using sessions has a big advantage,
once you have verified the data you can store it.
Always keep in mind that users may manipulate POST requests!
If the problem is to pass info between pages like in a multi-step form you should use session (if you are using PHP).
By the way for send a POST request without form you need to use CURL like in this example
The statement is a HTML language statement used by a browser to initiate a POST/GET data relation. The Browser is the execution environment.
You can use other languages (and their execution environment) like Java, Java Script, C#, etc. to initiate HTTP POST/GET data relations.
Sorry if I'm not understanding you correctly, but from what I'm reading, you want to access form data entered on page 1 (using a form with a post method) on page 2? If so, use the $_POST autoglobal array. For example, $nameOnPage2 = $_POST['nameFromPage1']. You don't have to create a form on the second page for this.