I want to send an already existing image stored in the $_FILES['the_file']. The $_FILES['the_file'] is from the page "img_upload.php" for uploading that image, then it is sent to the "form.php" page where the rest of the form is, and then sent to the processing page named "add_product.php"
My problem is that I want to send the $_FILES['the_file'] from the form on "form.php" page to "add_product.php" page (with the rest of the form from "form.php"). How can I do that?
Here is my code:
// img_upload.php
<form action="form.php" method="post" enctype="multipart/form-data">
<input type='file' name='the_file' class='image-selector'>
<button type="submit">Insert the picture</button>
</form>
// form.php
<?php
$file = $_FILES['the_file'];
$fileName = $_FILES['the_file']['name'];
$fileSize = $_FILES['the_file']['size'];
$fileTmpName = $_FILES['the_file']['tmp_name'];
$fileType = $_FILES['the_file']['type'];
?>
<p>Picture name: <?php echo $fileName; ?></p>
<form action="../Includes/add_product.php" method="post" enctype="multipart/form-data">
<?php
echo "<input type='hidden' name='file' value=".$file.">";
?>
<input type="text" name="price" placeholder="Name the price">
<input type="text" name="sent_from" placeholder="Sent from">
<input type="text" name="category" placeholder="Select the category">
<button type="submit">Insert the product</button>
</form>
If you want to include it in a hidden input then you'll need to encode it as a string. The usual way to do that is to base64 encode it.
This question covers how to do that.
When you insert the string into the document, do make sure you make use of htmlspecialchars so you don't expose yourself to XSS attacks.
That approach involves sending the file to the server, then sending it (in a less compressed form) back to the browser, then sending it back to the server again.
This is not bandwidth efficient!
Usually the approach for this would be the same the file on the server and then send an id (e.g. the file name) back to the client (and have some logic for cleaning up old files left over from the user abandoning the process part way through).
Related
so I have 2 pages . On the first page I have a form , where I need to input values and the other page receives those values and saves them. Then I go back to page 1 , input new values and those new values get saved again on page 2 , right next to the previous values. Basically like a shopping list. The problem is that i'm really new to PHP and I can't really find solution how to save these forms next to each other. Massive thanks to anyone who replies.
Page 1 :
<fieldset style="width:fit-content; margin:170px; auto 10px; font-size: 30px; justify-content:center;">
<form action="./site2.php" method="post" >
<legend>Product add</legend>
<label>SKU:<br />
<input type="text" name="SKU" pattern="[0-9.]+" required id="SKU" /></label><br />
<label>Name:<br />
<input type="text" name="name" required id="name" /> </label><br>
<label>Price($):<br />
<input required id="price" pattern="[0-9.]+" type="text" name="price" ></label><br />
<input type="submit" name="Submit" value="Save" >
<input type="reset" value="Cancel">
Page 2 :
<form action="site1.php" method="get">
<?php
session_start();
$data=array();
if(!isset($_SESSION['data'])){
$_SESSION['data'] = array();
}
if (isset($_POST)) {
$_SESSION['data'][] = $_POST['SKU'];
$_SESSION['data'][] = $_POST['name'];
$_SESSION['data'][] = $_POST['price'];
}
foreach($_SESSION['data'] as $d){
}
?>
<form id="form-list" >
<fieldset style="width: fit-content; margin:130px; auto 10px; font-size: 20px; justify-content:center; " >
SKU: <?php echo $d; ?><br>
Product name: <?php echo $d; ?><br>
Price($): <?php echo $d; ?><br>
<input type="checkbox" value="asd" id="test" name="test" />
</form>
It looks like you have read a little, and are trying to build something based on that reading. Good start. but I think you need to take a further dive into the litterature.
Concepts
PHP is a server side language. everything inside the <?php and ?> tags is executed on the server, and not on the client.
HTML is a (most often) client side markup (display) language, and is executed on the client (in the browser)
When you have both php and html in a php file (and it is sent with the proper headers) the php code is executed, and any echo or print or <?="hello world"?> is converted to text on your html page, and the resulting file is executed by the client's browser
Anything in your $_SESSION is available to your PHP sections as they are executed, providing the session (set by the cookie or a path parameter) is the same
What your code is doing
Page 1 (site1.php)
Displays a html form (could in reality be just a .html file instead, if you have no other php in the file)
Page 2 (site2.php)
starts a <form> element which would submit the form to site1.php
parses the submitted form data and saves it in a session variable
parses an empty foreach loop
displays some html elements with an apparently unset php variable $d
creates a checkbox
closes the <form> without a sumbit button, which means you never get back to site1.php
Solution 1: Do everything in a single php file
<!-- input part -->
<html>
<body>
<fieldset style="width:fit-content; margin:170px; auto 10px; font-size: 30px; justify-content:center;">
<form action="" method="post" >
<legend>Product add</legend>
<label>SKU:<br />
<input type="text" name="SKU" pattern="[0-9.]+" required id="SKU" /></label><br />
<label>Name:<br />
<input type="text" name="name" required id="name" /> </label><br>
<label>Price($):<br />
<input required id="price" pattern="[0-9.]+" type="text" name="price" ></label><br />
<input type="submit" name="Submit" value="Save" >
<input type="reset" value="Cancel">
<!-- form input handling -->
<?php
session_start();
$data=array();
if(!isset($_SESSION['data'])){
$_SESSION['data'] = array();
}
if (isset($_POST)) {
$_SESSION['data'][] = $_POST['SKU'];
$_SESSION['data'][] = $_POST['name'];
$_SESSION['data'][] = $_POST['price'];
}
foreach($_SESSION['data'] as $d){
echo "SKU: ".$d['SKU']."<br>".
"Product name: ".$d['name']."<br>".
"Price($): ".$d['price']."<br>";
}
?>
<!-- some link to save.php where you push $_SESSION['data'] to your persistent databse (MySQL/PostgresQL/whatever)-->
</body>
Solution 2 (advanced):
keep your setup with site1.php and site2.php, but keep site2.php as pure php without html, and return the data as json or xml
use ajax (javascript) to submit the form to site2.php and parse the return data to a visible format
have a third file (e.g. save.php) where you do the saving to a dbms
Solution 3: keep your code and fix the issues
put your display code inside the foreach (see my code)
remove the <form> from site2.php and simply add a add more items link at the bottom to go back to the input page
So a couple of things here, if you want to save your values on another page, you're going to need some sort of intermediary to save your values. This is where databases / caches shine.
Just use your preferred storage utility, and call it in your shopping cart with a SELECT / foreach loop.
I'm working on a website for fun where the user enters something into two <input> elements in a form, presses submit, and then the text is logged to a .txt file, then the user is sent to a page for confirmation.
Is this possible to do with a form, and does it require javascript?
The basic structure of something like this would be:
<form method="post" action="">
<input type="text" />
<input type="text" />
<button type="submit"></button>
</form>
Thats possible without javascript.
You need to give each input a name and replace button with input.
Here is a start:
<?php
if (isset($_POST['field1']) && isset($_POST['field2'])) { // check if both fields are set
$txt=$_POST['field1'].' - '.$_POST['field2'];
file_put_contents('test.log',$txt."\n",FILE_APPEND|LOCK_EX); // log to test.log (make sure that file is writable (permissions))
header('Location: http://www.google.com/search?q='.$txt); // google as example (use your confirmation page here)
exit();
}
?>
<form method="post" action="">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" >
</form>
You can use $_POST['field1'] and $_POST['field2'] to get the values and log them.
FILE_APPEND is used to add new content to the end of the file instead of overwriting it.
LOCK_EX is used to aquire a write lock for the file (in case multiple users post at the same time)
I succeeded in storing all the image information as a blob in MySQL via the form tag and php.
Now I'm trying to make an update form using PHP5. However, I'm not sure how to take all the information back from MySQL and show it to users that an image has been already posted.. like any other typical forum / blog pages that shows previously added files.
Any suggestions..? Thank you.
<form method="post" enctype="multipart/form-data" action="UpdateNewsPHP.php">
Title : <input name='TitleFieldToAdd' type='text' size='20' value='<?php echo $row["Title"] ?>'/> <br/>
Thread : <textarea name='ThreadFieldToAdd' cols="40" rows="10"><?php echo $row["Thread"] ?></textarea> <br/>
<!-- Here I have no clue how to deal with them... :( -->
Image : <input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
<input type="file" id='ImageFieldToAdd' name="files[]" /> <br/>
<input id="submit" type="submit" name="submit" value="Upload me!">
and this is the information I store in MySQL
$title = $_REQUEST['TitleFieldToAdd'];
$thread = $_REQUEST['ThreadFieldToAdd'];
$file_content = file_get_contents($_FILES['files']['tmp_name'][0]);
$file_content = mysql_real_escape_string($file_content);
$file_name = $_FILES['files']['name'][0];
$file_size = $_FILES['files']['size'][0];
$file_type = $_FILES['files']['type'][0];
$datePosted = date("Y-m-d");*/
The proper way is to leave your file upload stuff asis. If a file has already been uploaded, you display it another section of the form. Imgs can be embedded with an <img> tag (pointing at another script which retrieves/serves up the raw image data from the database). Non-displayable fields (pdf, zip, etc..) you can just put in a direct download link.
Then your form will look something like
[input1]
[input2]
You previously uploaded: [link/image to uploaded data]
[input file] - would you like to replace this data?
As such, your form building script would not actually retrieve the uploaded file data. Just its metadata (type/size).
I've created a HTML and PHP form to pretty much just input data into a MySQL table.
I've got a file upload field, but it doesn't upload a file. I don't want it to upload anything to the server, all I want is for it to grab the location of the file selected and input that into the database.
It works perfectly fine on Internet Explorer, but doesn't work on any other browser, I assume it's because of security issues it imposes.
My input code:
<input type="file" id="filename" name="filename" />
And of course when the form is submitted some PHP code runs through to insert the data into the database. I've tried JavaScript to copy value of that field to to another field but again because of security issues that doesn't work.
Does anyone know of a way I can do this in JavaScript? Or even Flash? To be honest, anything similar to these would do, just something that works in browsers other than IE.
Thanks.
EDIT -
Here's my code:
<?php
if (isset($_POST['submit'])) {
$name = addslashes(htmlentities($_POST['name']));
$filename = addslashes(htmlentities($_POST['filename']));
if (#mysql_query("INSERT INTO movies SET
name='$name',
doc_filename='$filename'")) {
echo '<p>Movie added.</p><p>Manage movies.</p>';
} else {
echo '<strong>Error:</strong> '.mysql_error().'';
}
} else {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="newspost" enctype="multipart/form-data">
<div class="form-row">
<label for="fm_title">Movie file path: </label><br />
<input type="file" id="filename" name="filename" />
</div><br />
<div class="form-row">
<label for="fm_title">Movie name: </label><br />
<input type="text" class="input-width" name="name" value="<?php if (!empty($_POST['name'])) { echo $_POST['name']; } ?>" />
</div>
<div class="form-row">
<input type="submit" name="submit" value="Submit" />
</div>
</form>
<?php
}
?>
all I want is for it to grab the location of the file selected and input that into the database.
This is no longer possible using HTML - for security reasons, the location of the selected file is not accessible in the file input's DOM element anymore. Most browsers use C:\Fakepath\ instead.
You might be able to get hold of this information using a Flash or Java based uploader (edit: see e.g. this page in the AS3 manual) SWFUpload's API could be worth a look. It could be that you need to build your own Flash or Java solution for this, though.
how you are posting the data of the form? I am not able to see any way of form post. No Submit button or onclick or onchange event of javascript? and also how you suppose this line to give output
<input type="text" class="input-width" name="name" value="<?php if (!empty($_POST['name'])) { echo $_POST['name']; } ?>" />
as its already in else part of the line
if (isset($_POST['submit']))
Well, I've got a page with HTML like this:
<form method="post" action="" enctype="multipart/form-data">
<!-- Some more markup -->
<form method="post" action="" enctype="multipart/form-data">
<input type="submit"name="reset_ph" value="<?php _e('Reset styles'); ?>" />
<input type="hidden" name="subaction" value="reset_ph" />
</form>
<p><input name="update" type="submit" value="<?php _e('Save changes'); ?>" style="padding:3px;" /></p>
<input type="hidden" name="action" value="update" />
</form>
Then PHP code:
//updating main form
if(isset($_FILES['phtfile']['name']) && $_REQUEST['action']=='update'){
$def_path = TEMPLATEPATH.'/img/author/';
$file_path = $def_path.basename($_FILES['phtfile']['name']);
$file_path = str_replace('\\','/',$file_path);
$file_css_path = get_bloginfo('template_url');
$file_css_path = $file_css_path.'/img/author/'.basename($_FILES['phtfile']['name']);
$isfile = move_uploaded_file($_FILES['phtfile']['tmp_name'],$file_path);
if ($isfile) { update_option('own_pht_url', $file_css_path);}
}
//update subform
if ($_POST['subaction']=='reset_ph'){
global $photo_path;
update_option('own_pht_url', $photo_path.'tmp.jpg');
}
Subform contains a button, that resets image shown to default one (via setting path to image to default). Main form contains the image upload dialog, and should change path to image to a new one, should the file be uploaded. But updating the main form, updates the subform, and path is set to default.
I've figured a workaround, by changing the button to a checkbox, but I'm still interested, does updating the master form always updates every sub-form inside it? No ways around it?
Thank you for your time.
Nested forms are known to cause problems. You can check out this thread:
Why WHATWG disallows nested forms in HTML 4 and HTML5?