How to let users upload a file to server - php

I have a page, and I want it to allow users to upload a file to my server so that I can see it later. I have already gotten started, but when you click submit, it takes you to 500 error. Here is what code I have so far:
HTML:
<form action="uploadfile.php" enctype="multipart/form-data" method="POST">
Choose File:
<input name="userfile" type="file">
<p></p>
<p class="section-content"><input type="submit" value="Upload File"></p>
</form>
PHP: (named uploadfile.php)
<?php
$path = "files/"; $path = $path . basename( $_FILES['userfile']['name']);
if(move_uploaded_file($_FILES['userfile']['tmp_name'], $path)) {
echo "Success uploading". basename($_FILES['userfile']['name']);
} else{
echo "Error when uploading file.";
}
?>
In HTML, there is a button to choose the file and one to submit. The submit button takes you to uploadfile.php, and that appears as 500 - internal server error. Note that it does not just say 'Error when uploading file' like it should when there is an error.
I am new to PHP, so I don't know if I am doing something completely wrong, or maybe there is a way to do it in Javascript, which I am slightly more experienced in?
Thank you in advance.
Edit: I have tried 2 different browsers (Chrome and Edge)

corrected
use $_SERVER['DOCUMENT_ROOT'] instead of basename()
$path = $_SERVER['DOCUMENT_ROOT'].'/your root file name/files';
$name = $_FILES['userfile']['name'];
$tmp_name = $_FILES['userfile']['tmp_name'];
move_uploaded_file($tmp_name, $path.'/'.$name);

Related

PHP move_uploaded_file not successful and no warning is shown

I am learning PHP through w3schools and the upload file php code does not seem to work. At first, there are warning shown that said "unable to open stream" but as I refreshed multiple times (trying to debug) the warning stopped showing but it still failed to upload the file.
Thus I decided to simplify the code (omitting all the features) and focus on uploading only. Some basic information, I am using an apache server on my localhost device. Below are the simplified code
<html>
<head><title>File upload test page</title></head>
<body>
<form action="upload_test.php" method="POST" enctype="multipart/form-data">
<input type="file" name="uploadedfile">
<input type="submit" value="Upload File">
</form>
</body>
</html>
<?php
$target = "uploads/";
$target = $target . basename($_FILES["uploadedfile"]["name"]);
if (move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], $target)) {
echo "The file ". htmlspecialchars( basename( $_FILES["uploadedfile"]["name"])). " has been uploaded. <br>";
} else {
echo "Sorry, there was an error uploading your file. <br>";
}
?>
The error keeps persisting. I am very new to php so any help would be much appreciated. Thank you!
"unable to open stream", means process user of apache have no write permission for dir "uploads/", try to change user of "uploads/" (such as "chown apache.apache uploads") or change permission of the dir (such as "chmod 777 uploads"). And if u can not get useful message next time, try this to catch exception maybe u can get
some useful messages
<?php
$target = "uploads/";
$target = $target . basename($_FILES["uploadedfile"]["name"]);
try{
if (move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], $target)) {
echo "The file ". htmlspecialchars( basename( $_FILES["uploadedfile"]. ["name"])). " has been uploaded. <br>";
} else {
echo "Sorry, there was an error uploading your file. <br>";
}
}catch(Exception $e){
var_dump($e->getMessage());
}

Upload file to server using PHP and HTML

I have a problem loading the file to the server in PHP and HTML using move_uploaded_file () when I put PHP files in this way http://mydomin.com/uploadfile.php succeed the process and if this way http://mydomin.com/uploadfiles/uploadfile.php The the process fails
code php
<?php
if (isset($_FILES['image'])) {
$idApp = uniqid();
$uploadDir = '../images/';
$uploadedFile = $uploadDir . $idApp . ".jpg";
if(move_uploaded_file($_FILES['image']['tmp_name'], $uploadedFile)) {
echo"Success: ".$_FILES['image']['tmp_name']. $uploadedFile;
} else {
echo"error 2";
}
} else {
echo"error 3";
}
?>
code html
<form action="add.php" method="POST" enctype="multipart/form-data">
<input type='file' name='image' id='image'>
<div align='center''><input type='submit' id='myButton' value='add'></div>";
</form>
check your upload path
$uploadDir = '../images/';
Try to use this path './images/' or best use absolute path.
check your script location by using
var_dump(__DIR__)
this will show you where is your .php file is ( also called as absolute path ). Thus simply you can see where you made a mistake to assign a folder for file uploading(image in your case ).

File upload in php not working on remote server

Here is the code which I am using
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file"><br><br>
<input type="submit" value="submit" name="submit">
</form>
PHP code :
<?php
$name = $_FILES['file']['name'];
$tmp_name = $_FILES['file']['tmp_name'];
$location = "/var/www/tmp/";
if(move_uploaded_file($tmp_name, $location.$name)){
echo 'File uploaded successfully';
} else {
echo 'You should select a file to upload !!';
}
?>
I checked the permissions of the folder as well as checked the php.ini file but still always I am getting 'You should select a file to upload '
Can anybody please help me out on this issue ?
Thank you so much!
Give the full path of your file here
$location = "var/www/tmp/";
I think it will work. If its ok then store your servername in a variable and pass there.
Your Location should be like this:
// document root will give you the server root then you can add any directory after that (in your case its tmp I guess)
$location = $_SERVER['DOCUMENT_ROOT'] . '/your_preferred_dir/'
note: when you mention your preferred location you will have to make
sure that this location should exists otherwise it will cause error.
And not hardcoded as yours because it can change from server to server.
Hope this helps...

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.

Upload images to remote servers. PHP

I do the image hosting and I have a problem..
I have 3 servers.
First - Site/script
Any two servers for images.
How I Can upload image from "one" server (script) to second and third servers?
<?php
if (isset($_POST['upload']))
{
$blacklist = array('.php', '.phtml', '.php3', '.php4', '.php5');
foreach ($blacklist as $item)
{
if(preg_match('#' . $item . '\$#i', $_FILES['file']['name']))
{
echo "We do not allow uploading PHP files\n";
exit;
}
}
$uploadDir = PROJECT_ROOT . 'upload/'; // 1ST SERVER (THIS SERVER)
$uploadFile = $uploadDir . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile))
{
echo "File is valid, and was successfully uploaded.\n";
}
else
{
echo "File uploading failed.\n";
}
}
?>
<form name="upload" method="post" enctype="multipart/form-data">
Select the file to upload: <input type="file" name="file"/>
<input type="submit" name="upload" value="upload"/>
</form>
You could use ftp. PHP has fairly easy way to do this. Check this link.
http://www.php.net/manual/en/book.ftp.php
If you already have HTTP servers runing on the other servers, use cURL. Usage:
Call curl_init
Call curl_setopt
Call curl_exec
The HTTP request can be configured using curl_setopt. Especially of interest are the options CURLOPT_URL, CURLOPT_POST and CURLOPT_POSTFIELDS.
You can use Zend_Http Client to upload the files to other servers per HTTP the same way an HTML Upload Form would do it. You can find all the information you need here in the Section "File Uploads": http://www.zendframework.com/manual/en/zend.http.client.advanced.html
For getting started you should read also this:
http://www.zendframework.com/manual/en/zend.http.client.html
Basically the code you need is:
require_once('Zend/Http/Client.php');
$client = new Zend_Http_Client("http://serverurl/path");
$client->setFileUpload(...);
$client->request();

Categories