Using only PHP and HTML to act like JavaScript - php

I have an assignment for school, and I'm not sure how the teacher wants us to accomplish a task.
We need to get an uploaded file as a temp file only (index.php)
Output size of file (upload.php)
User can confirm save of file or not (upload.php)
So, I have the majority down, but my problem lies with creating the temp file into a permanent file.
index.php
<html>
<form action="http://mysite.org/~me/upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file"><br />
<input type="submit" value="Now upload it!">
</form>
</html>
upload.php
<?php
if (($_FILES["file"]["type"] == "application/vnd.ms-excel"))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
}
}
?>
<form action="" method="POST">
<input type="submit" value"YES please save">
<form>
<?php
if (isset($_POST['submit']))
{
//Code for saving file
echo 'File saved!';
}
?>
Is it possible to go about it this way? My last echo statement does not work, so I'm doubtful the file save would be as well.

Hopefully the following comments can help you with the part you are stuck on.
In case you hadn't realized it already, any files uploaded with PHP are deleted once the PHP request that handled the uploaded file terminates. This means, if you don't do anything with the temp file from the upload, it will be deleted when the PHP script terminates.
One function of interest to you will be move_uploaded_file() which will move the temporary file from the upload to a permanent location of your choice.
Since the file will be uploaded and then you have to display the size and ask the user to confirm the upload, you will have to move the temp file to a permanent temporary location where it is kept when the user hasn't confirmed they want to keep the upload.
I'm not sure if you have been introduced to sessions yet, but if not, you will probably need some hidden form element that will keep track of what file they uploaded, otherwise you can keep this info in the session.
Then when the person submits the form saying they want to keep the file, you can move it again to a permanent location, or if they say no, then delete the file. The problem is, if they never say yes or no, then the file remains on the system.
Hope that helps.

Yep, this should work. Your if statements will catch the form submission and then echo your string there. A few little errors in your markup:
<input type="submit" value"YES please save">
Should be
<input type="submit" value="YES please save" name="submit">

Your final if statement in PHP is looking for a post variable named 'submit' but your <input type="submit"> tag has no name.

The file is saved to a temporary location when the upload completes. You can access this temporary file with $_FILES['file]['tmp_name'] BUT the file will be removed at the end of the request if you do nothing about it. This means that when the user clicks YES please save button, the file will not be available any more.
This means that you have to save the file to a disk in the first place, when you first call the upload.php file. There is no way to keep the file "in memory" while the user decides whether or not to save the file permanently.

Related

LAMP - file doesn't appear under tmp directory

I am uploading an image using an HTML form.
When I get the full path to the image, it outputs something like this:
'/tmp/phpkIv1BY/10259944_770025219687938_1184503840380306483_n.jpg'
but when I go to the /tmp folder, the sub-folder phpkIv1BY doesn't even exist! What's going on here?
Reason for this behaviour
All uploaded files are temporarily stored in the folder location as defined in
(In php.ini)
upload_tmp_dir =
(Read more about this: http://php.net/upload-tmp-dir)
These temporarily stored files are no longer exist after that php script execution(As mentioned in previous answer request life span) finished.
Do the following to view uploaded file while script executing.
upload.html
<html>
<body>
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
upload_file.php
<?php
if ($_FILES["file"]["error"] > 0) {
echo "Error: " . $_FILES["file"]["error"] . "<br>";
} else {
$fp=fopen("/tmp/write.log","w+");
fputs($fp,"Original Name:".$_FILES["file"]["name"].";temporay Name:".$_FILES["file"]["tmp_name"]."\n");
fclose($fp);
sleep(50000);
}
?>
Upload file by upload.html
In another terminal apply tail in /tmp/write.log after uploading image(Because sleep time is too much so you able to find the image)
#tail -f /tmp/write.log
Copy that temporary file into any place and place the extension of original image file
For example my printed log line is
Original Name:digits.png;temporay Name:/tmp/phpOKlpoK
(Needed to do this with root privilages)
#cp /tmp/phpOKlpoK /home/sandeep/Desktop/file.png
#chown sandeep.sandeep /home/sandeep/Desktop/file.png
So this is the uploaded file that you.
(
Instead of doing all these steps for checking uploaded images you can use move_uploaded_file()
)
I can not find anywhere if PHP might create a temporary folder for temporary uploaded files. But what is certain is that uploaded files are kept temporary and as soon as the request is done, they are removed. So if you think you can find some uploaded file in the /tmp folder, think again.
If you would like some uploaded file to live longer than a request life span, then you need to move it somewhere safe using move_uploaded_file().

Pass uploaded file between PHP scripts

I've got a page where users can upload a HTML file for use as a theme. The HTML file has some checks performed on it before some options are displayed to the user. The user fills out the form in relation to the HTML file, and submits the form. However, due to the file in the temp folder being destroyed after the script has ended, I do not know how to get the HTML file once the form has been filled out and re-submitted short of making the user re-upload the file, which relies on them uploading the same file, and also makes them upload something twice, which is counter-intuitive and could be an issue with large files.
Here is the code (cut down to make it easier to read/understand). The form submits to itself, so the same PHP file is used for both "steps".
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Form has been submitted
$files = $_FILES['file'];
<form method="POST">
/* Options about the uploaded HTML file are generated using PHP and displayed here */
<input type="submit">
</form>
} else {
?>
<form method="POST" enctype="multipart/form-data">
<label for="file">Theme File(s)</label>
<input type="file" name="file[]" multiple="multiple">
<input type="submit">
</form>
<?php
}
I tried using <input type="file" name="file[]" multiple="multiple" value="<?php echo $files; ?> >, but this did not work, and would also require the user to re-upload the files, which could be any issue if the files get too big.
I was thinking there might be a way to pass the file internally, and have a check whether a file has been uploaded or passed to the script instead of <input type="file" name="file[]" multiple="multiple">, but I could not find a way to do that.
You need to create your own temporary file, and pass the name between your two scripts.
So for example, in your "first script" (i.e. when the file has first been uploaded) you would:
$uniqName = uniqid('upload_', TRUE);
$tmpFile = "/tmp/$uniqName.html";
move_uploaded_file($_FILES['file']['tmp_name'][0], $tmpFile);
And then when you generate the form from the result of this upload, you would add
<input type="hidden" name="uniqName" value="<?php echo $uniqName; ?>" />
...so that when you get to your "second script" (after the questionnaire form is submitted) you can access the file through:
$tmpFile = "/tmp/".basename($_REQUEST['uniqName']).".html";
Of course, this is subject to the possibility of people failing to submit to second form so you end up with "orphaned files" littering your temporary directory, so you will need to implement some form of check that deletes files after thet have been inactive for a certain amount of time - you can base this on the last modified time of the files.
EDIT
Here is an example of how you can randomly run a job to keep the /tmp dir tidy without a cron job:
$probabilityDivisor = 10; // 1/10 chance of running
$uploadTTLSecs = 1800; // 30 minutes
if (mt_rand(1, $probabilityDivisor) / $probabilityDivisor == 1) {
foreach (glob('/tmp/upload_*') as $file) {
// Iterate files matching the uniqids you generate
if (time() - filemtime($file) >= $uploadTTLSecs) {
// If file is older than $uploadTTLSecs, delete it
unlink($file);
}
}
}
This operates in a similar way to the PHP session garbage collectors. Because of the simplicity of the operations, this should not adversely affect the user experience in any meaningful way.
You could try the following:
Use move_uploaded_file() and move the file from the temp location to a permanent location on the server. Be sure to give the file your moving a unique name like 'file-' . time() . '.jpg' or something.
Soon after uploading, register a Session variable and put the file name in it.
After everything is over you could delete the file using unset()
Now the file is located safely on your server and you also have access to it via the session.
Hope this helps :)

bool(false) Uploading a file

I have had problems with a simple php script in which I can upload a file to a certain folder. I have tried multiple ways in doing this and I still have not had success.
Any errors in my code or advice on how to correct the issue will be taken gracefully.
Main Php Code:
<p>Browse For a File on your computer to upload it!</p>
<form enctype="multipart/form-data" action="upload_photos.php" method="POST">
Choose Photo:
<input name="userfile" type="file" /><br />
<input type="submit" value="Upload Photo" />
<?PHP
if ($userfile_size>250000)
{$msg=$msg."Your uploaded file size is more than 250KB so please reduce the file size and then upload.<BR>";
$file_upload="false";}
else{
if (!($userfile_type<>"image/jpeg" OR $userfile_type<>"image/tiff" OR $userfile_type<>"image/png"))
{$msg=$msg."Your uploaded file must be of JPG, PNG, or tiff. Other file types are not allowed<BR>";
$file_upload="false";}
}
?>
</form>
</label>
</form>
Php code that is called upon on click (upload_photos.php)
<?php
$target_path="uploads/";
chmod("uploads/", 0755);
$target_path=$target_path . basename( $_FILES['uploadedfile']['name']);
$test=move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path);
if($test) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
var_dump($test);
}
?>
I do not understand why my end results [upon clicking "Upload Files" Button] include only the following results:
"There was an error uploading the file, please try again!bool(false)"
One more thing: I have also tried using the full computer folder path for $target_path and chmod.
Does anybody see what I am doing wrong?
You have <input name="userfile" but then use $_FILES['uploadedfile'] in your script - use one or the other.
Other than that, make sure the chmod worked and the folder is writable.
bool(false) is the output of var_dump($test);, indicating that move_uploaded_file is returning false.
As a basic debugging step, you should try var_dump($_FILES) to make sure you're accessing the right element of that array (I can tell from your code that you aren't, the index will be the name attribute of your <input type="file"/> element).
You have at least one other serious flaw in your logic... The PHP code in your upload form doesn't make any sense. That block of PHP code will execute server-side before the user has ever uploaded a file. It can't possibly work. The two variables you're checking, $userfile_size and $userfile_type, are not defined anywhere.
In my case, I forgot to create a folder where I want to upload. So check once the specified upload path is available or not.

PHP: File upload always returning nothing

Hey guys I'm working on a file uploader and I have come across a problem. In my code I am checking to see if a file has been selected via the file upload form, here is the form code:
<form method="post" action="actions/save.php?id=<?print($id);?>" enctype="multipart/form-data">
Listing Photo: <input type="file" name="file"/>
<input class="add" type="submit" name="submit" value="Save"/>
</form>
The user selects the file to upload then clicks the "Save" button. Now in my uploading code i am trying to check if the file form has been set like this:
$file = $_POST['file'];
if(isset($file)) {
//Continue
} else {
//Go back
}
Now my problem is that even if the file input is set (File selected) it goes to the "Go back" part of the code.
Any suggestions or a different way of checking?
Any help is appreciate, Thanks.
When you upload files through form, you should have $_FILES superglobal array with that file, so try
print_r($_FILES['file'])
to see what it cointains (size, error code, path ...)
Uploaded files end up in $_FILES, not in $_POST
see: http://nl.php.net/manual/en/reserved.variables.files.php for documentation and examples
You should have access to uploaded files using the $_FILES array. See also the reference documentation.

In the next page $_FILES["myfile"]["tmp_name"] = NULL

I had upload file with POST and it seems to works fine, but after I go to the next page I can't use the file with the location in the global varible: $_FILES["myfile"]["tmp_name"]
because it's null. I don't know why, I used this code before and it worked fine...
Here is the code:
www/step1.php
if (isset($_POST["check_if_press"]) && $_POST["check_if_press"] == "Upload")
{
if (!empty($_FILES["myfile"]["tmp_name"]))
{
header("Location: ./step2_1.php");
}else echo "Please select a file";
}
<form action="<?php echo $PHP_SELF; ?>" method="post" enctype="multipart/form-data">
Upload file: <input type='file' name='myfile' /><br />
<input type='Submit' name='check_if_press' value='Upload' />
</form>
www/step2_1.php
echo $_FILES["myfile"]["tmp_name"];
Now I get NULL printed on the screen.
When I used POST without the arguments :
action="<?php echo $PHP_SELF
But with:
action="./step2.php"
Instead, It work, but than I cant use the upload check .
Thanks,
Yonatan.
The file is only present in $_FILES within the scope of the post. What's happening here is:
User is posting a file to step1
step1 is doing something with the file, then telling the user to go to step2 (by means of the location header)
In response to the location header, user is making a GET request to step2, no posted file is associated
You're going to need to either post the file directly to step2 (which you said worked, just didn't have the logic of step1) and put your server-side file checking logic there, or in step1 store the file somewhere on the server (either save it to the file system, store it in a database, maybe store it in session which I don't recommend, etc.) where it can be accessed by step2.
step2 is a completely separate request from step1 and doesn't have access to anything within the scope of step1.
The temporary file is deleted at the end of your post script, so you'll need to copy it to another location before you redirect:
if (!empty($_FILES["myfile"]["tmp_name"]))
{
//COPY THE FILE TO ANOTHER LOCATION HERE...
header("Location: ./step2_1.php");
}else echo "Please select a file";
}

Categories