Running php in JavaScript - php

I am making an application on my server, where the user uploads an image through some HTML combined with javascript.
The user finds an image on the computer through
<form action="uploadimage.php" method="post"
enctype="multipart/form-data">
<label for="file">Filnavn:</label>
<input type="file" name="file" id="file" value="100000" />
Then the point behind the javascript, is to validate on the users image
if(picture_headline.value == "" || picture_uploaded.value == "" || !ischecked)
{
// Don't execute, stay on same site
}
else
{
// execute php and upload image
}
the php is an upload image php script
<?php
// The file is being uploaded into the folder "upload"
$target = "/navnesutten.eu/facebook/uploads/";
// add the original filename of our target path
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
// Moves the uploaded file into correct folder
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
?>
I must say I am a bit confused here, since I have only been working with html, php and javascript for a few days now.
Am I totally off or what?
I found some "simple" examples online, which I put on my server through cuteFTP, but everytime i press upload, the website just sends me to the .php file and says the site doesn't exist.

Like Boann points out you're trying to access a non-existent file in your PHP code ("uploaded" and "uploadedfile" rather than "file" (which is what you named the field in your HTML form)).
But regarding "running PHP from JavaScript": You don't have to. The JavaScript should only return false if the form is invalid. If it's valid you don't need to do anything and the form will submit, in turn running your PHP script:
form.onsubmit = function () {
if (!formIsValid()) {
return false;
}
};
If the form is invalid it won't submit (the return false bit (you could use event.preventDefault() instead)), if it is valid nothing will happen and the form will do what it does (ie submit the data to the server).

Each array key in $_FILES corresponds with the name attribute of a file field in the form, so to match your form it should be 'file' rather than 'uploaded' or 'uploadedfile':
<?php
// The file is being uploaded into the folder "upload"
$target = "/navnesutten.eu/facebook/uploads/";
// add the original filename of our target path
$target = $target . basename( $_FILES['file']['name'] ) ;
$ok=1;
// Moves the uploaded file into correct folder
if(move_uploaded_file($_FILES['file']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['file']['name']). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}

Related

How to recieve an image (file) with PHP that was submitted over a POST request

I have a file: success.jpg
I would like to send this file over an HTTP POST request and have it land in a public directory on my server.
I have a simple HTML form and PHP processor that work if I'm uploading from the browser: php.net/manual/en/features.file-upload.post-method.php
I'm trying to drop the use of a form altogether and just pass data over POST to a URL (e.g. myimageserver.com/public/upload.php).
It seems that I can use the PHP function move_uploaded_file and it even talks about using POST here: http://php.net/manual/en/function.move-uploaded-file.php but it doesn't provide the code which can receive and store a file that has been uploaded with POST.
Has anyone ever done something similar?
If you want to upload using a mobile app for example, you have to send via POST the base64 content of the image with the mimetype or the file extension of it, and then use something like this:
Send the content base64 encoded and urlescaped.
Receive the content and do base64 decode and then urldecode.
Then in PHP just do:
<?php
$base64decodedString = base64_decode(urldecode($_POST['yourInputString']));
$fileName = $_POST['fileNameString'];
file_put_contents($fileName, $base64decodedString);
This will generate a file with the content
You couold read this example http://www.w3schools.com/php/php_file_upload.asp
which basically does something like this:
<?php
$target_dir = "uploads/";
$target_dir = $target_dir . basename( $_FILES["uploadFile"]["name"]);
$uploadOk=1;
if (move_uploaded_file($_FILES["uploadFile"]["tmp_name"], $target_dir)) {
echo "The file ". basename( $_FILES["uploadFile"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
The key is on the $_FILES global array.
To check if there were an error before appliying that example, you could use this example:
if ($_FILES['file']['uploadFile'] === UPLOAD_ERR_OK) {
/**
* Do the upload process mentioned above
**/
} else {
/**
* There were an error
**/
}
This is the basic HTML form to upload files
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="myFile" />
<input type="submit" value="Send" />
</form>
How to upload your file?
<?php
$uploaddir = '/www/uploads/'; //physical address of uploads directory
$uploadfile = $uploaddir . basename($_FILES['myFile']['name']);
if(move_uploaded_file($_FILES['myFile']['tmp_name'], $uploadfile)){
echo "File was successfully uploaded.\n";
/* Your file is uploaded into your server and you can do what ever you want with */
}else{
echo "Possible file upload attack!\n";
}
?>
Some details
- How to get the physical address of uploads directory?
Just create an index file into your upload dir and run this code
<?php echo getcwd();?>
It's done, if you need more details, just feel free to ask.
AGAIN THIS IS THE BASIC WAY.

prevent uploading of large and unsupported files in image upload form

i have a php form with an image upload option as follows
<input type="hidden" name="old_picture" value="<?php if (!empty($old_picture)) echo $old_picture; ?>" />
<label for="new_picture">Picture:</label>
<input type="file" id="new_picture" name="new_picture" />
and php script something like
if (!empty($new_picture)) {
if ((($new_picture_type == 'image/gif') || ($new_picture_type == 'image/jpeg') || ($new_picture_type == 'image/pjpeg') ||
($new_picture_type == 'image/png')) && ($new_picture_size > 0) && ($new_picture_size <= MM_MAXFILESIZE) &&
($new_picture_width <= MM_MAXIMGWIDTH) && ($new_picture_height <= MM_MAXIMGHEIGHT)) {
if ($_FILES['file']['error'] == 0) {
// Move the file to the target upload folder
$target = MM_UPLOADPATH . basename($new_picture);
if (move_uploaded_file($_FILES['new_picture']['tmp_name'], $target)) {
// The new picture file move was successful, now make sure any old picture is deleted
if (!empty($old_picture) && ($old_picture != $new_picture)) {
#unlink(MM_UPLOADPATH . $old_picture);
}
}
else {
// The new picture file move failed, so delete the temporary file and set the error flag
#unlink($_FILES['new_picture']['tmp_name']);
$error = true;
echo '<p class="error">Sorry, there was a problem uploading your picture.</p>';
}
}
}
else {
// The new picture file is not valid, so delete the temporary file and set the error flag
#unlink($_FILES['new_picture']['tmp_name']);
$error = true;
echo '<p class="error">Your picture must be a GIF, JPEG, or PNG image file no greater than ' . (MM_MAXFILESIZE / 1024) .
' KB and ' . MM_MAXIMGWIDTH . 'x' . MM_MAXIMGHEIGHT . ' pixels in size.</p>';
}
}
every thing works fine but problem occurs when as a test i tried to upload a .zip file the image was not loaded but it flushed my database. all the entries for that user were deleted.
now i want a some suggessions about how to prevent this
thanks in advance
On the client side, there is not much you can do that you can actually rely on. But it can help prevent accidental problems.
Add this attribute to the file upload control to limit file types: accept="image/gif, image/jpeg"
Your validation needs to happen on server side if you want to be sure about what you are getting.
Check $_FILES['uploadctl']['size'] for the size of the file and see if it exceeds your limits.
You can force php to limit what size file uploads it accepts by setting upload_max_filesize in php.ini. Default for this is pretty low.
You cant really trust that the extension of an uploaded file is actually correct. Just because it says .jpg doesn't mean it really is. If all you are accepting is images, you should be able to verify the mimetype with getimagesize(). If you are accepting a larger range of files, check the file with Fileinfo.
If the entries in the database were deleted, you probably have a logic problem in code that you are not showing here.

PHP can't upload files to server?

I have a php file that uploads images like jpegs and png onto a folder called uploads that is stored on the apache server and in the same location as the php file.
I have checked the code of both the HTML and the PHP and both seem to be perfectly fine, however whenever I try to upload a file I always get an error message and the file doesn't get uploaded.
It would be much appreciated if someone with more experience than me can look at my code and tell me why it is behaving in this manner.
Here is the HTML form:
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload Your File</title>
</head>
<body>
<?php
// put your code here
?>
<form enctype="multipart/form-data" method="post" action="fileHandler.php">
Select File:
<input name="uploaded_file" type="file"/><br/>
<input type="submit" value="Upload"/>
</form>
</body>
</html>
and here is the PHP file that is executed when the form is submitted:
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
* PHP file that uploads files and handles any errors that may occur
* when the file is being uploaded. Then places that file into the
* "uploads" directory. File cannot work is no "uploads" directory is created in the
* same directory as the function.
*/
$fileName = $_FILES["uploaded_file"]["name"];//the files name takes from the HTML form
$fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"];//file in the PHP tmp folder
$fileType = $_FILES["uploaded_file"]["type"];//the type of file
$fileSize = $_FILES["uploaded_file"]["size"];//file size in bytes
$fileErrorMsg = $FILES["uploaded_file"]["error"];//0 for false and 1 for true
$target_path = "uploads/" . basename( $_FILES["uploaded_file"]["name"]);
echo "file name: $fileName </br> temp file location: $fileTmpLoc<br/> file type: $fileType<br/> file size: $fileSize<br/> file upload target: $target_path<br/> file error msg: $fileErrorMsg<br/>";
//START PHP Image Upload Error Handling---------------------------------------------------------------------------------------------------
if(!$fileTmpLoc)//no file was chosen ie file = null
{
echo "ERROR: Please select a file before clicking submit button.";
exit();
}
else
if(!$fileSize > 16777215)//if file is > 16MB (Max size of MEDIUMBLOB)
{
echo "ERROR: Your file was larger than 16 Megabytes";
unlink($fileTmpLoc);//remove the uploaded file from the PHP folder
exit();
}
else
if(!preg_match("/\.(gif|jpg|jpeg|png)$/i", $fileName))//this codition allows only the type of files listed to be uploaded
{
echo "ERROR: Your image was not .gif, .jpg, .jpeg or .png";
unlink($fileTmpLoc);//remove the uploaded file from the PHP temp folder
exit();
}
else
if($fileErrorMsg == 1)//if file uploaded error key = 1 ie is true
{
echo "ERROR: An error occured while processing the file. Please try again.";
exit();
}
//END PHP Image Upload Error Handling---------------------------------------------------------------------------------------------------------------------
//Place it into your "uploads" folder using the move_uploaded_file() function
$moveResult = move_uploaded_file($fileTmpLoc, $target_path);
//Check to make sure the result is true before continuing
if($moveResult != true)
{
echo "ERROR: File not uploaded. Please Try again.";
unlink($fileTmpLoc);//remove the uploaded file from the PHP temp folder
}
else
{
//Display to the page so you see what is happening
echo "The file named <strong>$fileName</strong> uploaded successfully.<br/><br/>";
echo "It is <strong>$fileSize</strong> bytes.<br/><br/>";
echo "It is a <strong>$fileType</strong> type of file.<br/><br/>";
echo "The Error Message output for this upload is: $fileErrorMsg";
}
?>
make sure that the directory structure has write permissions. You can check within php by using is_writeable. By checking from within PHP you will also be making sure that the PHP user has write access.
Check the folder permissions on the server. If incorrect, you can modify your php.ini file.

PHP Upload Script not Functioning Properly with New Host

I have set up a php script which creates a directory and uploads a file to that directory. My issue is that when I use the script to create the directory, the file will not upload entirely. I ran the exact same script on a different host and the upload process works just fine. Plus, if I manually create the upload directory and apply chmod 777 via ftp then the transfer works just fine. Could there be some sort of a setting with the hosting provider that needs to be altered to allow the function to work just right?
Here is the upload form:
<form action="/uploadFile.php" method="post"
enctype="multipart/form-data">
<label for="img_preview">Preview Image:</label>
<input type="file" name="img_preview" id="img_preview" />
<br />
<input type="hidden" name="id" value="newDirectory" />
<input type="submit" name="submit" value="Upload Flyer" />
</form>
Here is my PHP script (uploadFile.php):
$thisdir = getcwd();
$new_dir = $_POST['id'];
$full_dir = $thisdir . "/upload/" . $new_dir;
function chk_dir($full_dir) {
if(is_dir($full_dir)) {
echo 'welcome back';
} else {
return mkdir($full_dir);
}
}
chk_dir($full_dir);
chmod($full_dir, 0777);
?>
<?php
//upload image
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["img_preview"]["error"] . "<br />";
}
else
{
}
//set image restrictions
?>
<?php
if ((($_FILES["img_preview"]["type"] == "image/gif")
|| ($_FILES["img_preview"]["type"] == "image/jpeg")
|| ($_FILES["img_preview"]["type"] == "image/pjpeg"))
&& ($_FILES["img_preview"]["size"] < 80000))
{
if ($_FILES["img_preview"]["error"] > 0)
{
echo "Please only upload an image for previewing (jpg or gif)...<br>
Also, check to make sure the filesize is less than 8MB" . $_FILES["img_preview"]["error"] . "<br />";
}
else
{
//check the image into new directory
if (file_exists("upload/". $new_dir ."/". $_FILES["img_preview"]["name"]))
{
echo "It seems that " . $_FILES["img_preview"]["name"] . " already exists.";
}
else
{
move_uploaded_file($_FILES["img_preview"]["tmp_name"],
"upload/" . $_POST['id'] . "/" . $_FILES["img_preview"]["name"]);
echo "image file has transferred successfully!";
}
}
}
else
{
echo "Invalid file please contact for assistance.";
}
?>
Also, when I run the script no errors are produced and the file echos "image file has transferred successfully!" but then when I check for the file in the new location it is completely void. Thank you for your time in this issue.
First of all, your script has a security hole. Never use passed $_POST data to create system directories. And never use 0777 for anything.
The move_uploaded_file() returns false on a failure and you would still get your success message even if it failed (in your code)
Turn on display_errors and error logging and try again.
Looks like your question already contains the answer(the upload works when you create the directory via FTP).
I guess the new server has safe_mode enabled, so it will check the UID of the fileowners on file-operations.
What happens:
your script creates a directory, owner will be the webserver
your script(owner of the script usually is the ftp-user) tries to chmod the directory
the script(owner:ftp) cannot chmod the directory(owner:webserver) , because the UIDs are different.
solution: use ftp_mkdir() for creation of directories.
you have used move_uploaded_file() independently. If it returns false then also sucsess message will be printed.
Try
if ( move_uploaded_file($_FILES["img_preview"]["tmp_name"],
"upload/" . $_POST['id'] . "/" . $_FILES["img_preview"]["name"])) {
echo "sucess";
}else{
echo "fail";
}
After that you will get what is the main problem. Also use debugging point by
print_r($_FILES) before move_uploaded_file().
This may not be the answer to your question, but still it's worth your attention, I hope. Don't rely on the type of the file sent via $_FILES, this is just the mime-type sent by the browser as far as I remember, it can be easily compromized. Use getimagesize() function to get true image type as well as height/width.
Same goes for the source file name, but that shouldn't pose a security hole.

Upload files not working, whats wrong with this code?

This is the PHP code used for the upload:
$upload = "uploads/";
$upload = $upload . basename($_FILES['bgimage']['name']);
if (move_uploaded_file($_FILES['bgimage']['tmp_name'], $upload)) {
echo "The file has been uploaded successfully.";
} else { echo "Error"; }
When I test the script, it says "The file has been uploaded successfully." but when I check the FTP server, it hasn't really...
Also, if you need to know, here's the HTML codes:
Form tag:
<form name="profilestyle" action="account.php?action=profiletheme" method="post" enctype="multipart/form-data">
Input tag:
<input type="file" name="bgimage" />
Extra Information:
Yes, I remembered the CHMod the uploads directory
Odd, the code looks fine as far as I can see.
Can you use file_exists() to check whether the file exists, but maybe is not visible to your FTP user?
if (move_uploaded_file($_FILES['bgimage']['tmp_name'], $upload)) {
echo "The file '$upload' has been uploaded successfully.";
if (file_exists($upload)) echo "And it exists! It is ".filesize($upload)." bytes big.";
else echo "But it doesn't exist.";
} else { echo "Error"; }
You also need to check $_FILES['bgimage']['error'] to make sure it is equal to UPLOAD_ERR_OK and is not an error code.
Please try the following test code
$upload = "uploads/";
$upload = $upload . basename($_FILES['bgimage']['name']);
sprintf('<pre>Debug: moving file from %s to %s</pre>',
$_FILES['bgimage']['tmp_name'],
$upload
);
if (move_uploaded_file($_FILES['bgimage']['tmp_name'], $upload)) {
echo "The file has been uploaded successfully.";
sprintf('<pre>Debug: realpath=%s, filesize=%d</pre>',
realpath($upload),
filesize($upload)
);
}
else {
echo "Error";
}
and esp. keep an eye on the realpath=xyz output.

Categories