Is there a way to upload a file to server using php and the filename in a parameter (instead using a submit form), something like this:
myserver/upload.php?file=c:\example.txt
Im using a local server, so i dont have problems with filesize limit or upload function, and i have a code to upload file using a form
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<html>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="fileForm" enctype="multipart/form-data">
File to upload:
<table>
<tr><td><input name="upfile" type="file"></td></tr>
<tr><td><input type="submit" name="submitBtn" value="Upload"></td></tr>
</table>
</form>
<?php
if (isset($_POST['submitBtn'])){
// Define the upload location
$target_path = "c:\\";
// Create the file name with path
$target_path = $target_path . basename( $_FILES['upfile']['name']);
// Try to move the file from the temporay directory to the defined.
if(move_uploaded_file($_FILES['upfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['upfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
}
?>
</body>
Thanks for the help
Image Upload Via url:
//check
$url = "http://theonlytutorials.com/wp-content/uploads/2014/05/blog-logo1.png";
$name = basename($url);
try {
$files = file_get_contents($url);
if ($files) {
$stored_name = time() . $name;
file_put_contents("assets/images/product/$stored_name", $files);
}
}catch (Exception $e){
}
If you're doing this localy do you have the need to use "upload" mechanisms? otherwise if you're sending something externaly you could use cURL to upload the file, and run the PHP script on the CLI, quick google: http://dtbaker.com.au/random-bits/uploading-a-file-using-curl-in-php.html
if you want to use url to send the name of the file like below:
www.website.com/upload.php?hilton_plaza_party.jpg
There is a script to do that. Here: http://valums.com/ajax-upload/
Related
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 ).
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.
I am using php to upload and move a file to a desired location...
while using move_uploaded_file, it says that the file has moved successfully but the file does not show up in the directory.
THE HTML AND PHP CODE IS BELOW...
<form action="test_upload.php" method="POST" enctype="multipart/form-data">
<fieldset>
<label for="test_pic">Testing Picture</label>
<input type="file" name="test_pic" size="30" /><br />
</fieldset>
<fieldset>
<input type="submit" value="submit" />
</fieldset>
</form>
THe php goes like :
<?php
$image_fieldname = "test_pic";
$upload_dir = "/vidit";
$display_message ='none';
if(move_uploaded_file($_FILES[$image_fieldname]['tmp_name'],$upload_dir) && is_writable($upload_dir)){
$display_message = "file moved successfully";
}
else{
$display_message = " STILL DID NOT MOVE";
}
?>
when i run this page and upload a legitimate file - the test_upload.php echoes file uploaded successfully. but when i head on to the folder "vidit" in the root of the web page. the folder is empty...
I am using wamp server .
You need to append filename into your destination path. Try as below
$doc_path = realpath(dirname(__FILE__));
if(move_uploaded_file($_FILES[$image_fieldname]['tmp_name'],$doc_path.$upload_dir.'/'.$_FILES[$image_fieldname]['name']) && is_writable($upload_dir)){
$display_message = "file moved successfully";
}
else{
$display_message = " STILL DID NOT MOVE";
}
See PHP Manual for reference. http://php.net/manual/en/function.move-uploaded-file.php
<?php
$image_fieldname = "test_pic";
$upload_dir = "/vidit";
$display_message ='none';
if (move_uploaded_file($_FILES[$image_fieldname]['tmp_name'],$upload_dir . '/' . $_FILES[$image_fieldname]['name'] && is_writable($upload_dir)) {
$display_message = "file moved successfully";
} else {
$display_message = " STILL DID NOT MOVE";
}
?>
Added indenting as well. The file name needs to be applied, or it's like uploading the file as a extensionless file.
Use this it may work
$upload_dir = "vidit/";
$uploadfile=($upload_dir.basename($_FILES['test_pic']['name']));
if(move_uploaded_file($_FILES['test_pic']['tmp_name'], $uploadfile) ) {
}
Create tmp directory in root(www) and change directory path definitely it works
/ after your directory name is compulsory
$upload_dir = $_SERVER['DOCUMENT_ROOT'].'/tmp/';
I am using the simple script below to upload a zip file via php and then unzip it on my server.
The file will be a zipped folder. When the upload is complete I want to echo a link to the new folder.
So for instance if I upload a zip file containing a folder called "bar", after the success message I want to echo "http://foo.com/bar".
Any help much appreciated.
<?php
if($_FILES["zip_file"]["name"]) {
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$type = $_FILES["zip_file"]["type"];
$name = explode(".", $filename);
$accepted_types = array('application/zip', 'application/x-zip-compressed',
'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$message = "The file you are trying to upload is not a .zip file. Please try again.";
}
$target_path = "/home/var/foo.com/".$filename; // change this to the correct
site path
if(move_uploaded_file($source, $target_path)) {
$zip = new ZipArchive();
$x = $zip->open($target_path);
if ($x === true) {
$zip->extractTo("/home/var/foo.com/"); // change this to the correct site path
$zip->close();
unlink($target_path);
}
$message = "Your .zip file was uploaded and unpacked.";
} else {
$message = "There was a problem with the upload. Please try again.";
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1
/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
<?php if($message) echo "<p>$message</p>"; ?>
<form enctype="multipart/form-data" method="post" action="">
<label>Choose a zip file to upload: <input type="file" name="zip_file" /></label>
<br />
<input type="submit" name="submit" value="Upload" />
</form>
</body>
</html>
Taking a quick glance over everything, I'd say
$message = "Your .zip file was uploaded and unpacked. Files";
from what I gather on your script your telling it to upload directly to the servers directory path of the domain. Appending $filename as the folder name to that path so it creates a folder as such accordingly. From that its hardcoding the domain like you would to any other link and then appending the same filename variable to the end of it so it shows the same folder you just uploaded to.
This is just my guess overall though again only taking a quick glance and all.
From a detailed look at your code, I would say that I can give a few comments:
1) You should use mkdir() to create a new directory in the uploads directory of your site (I assume it's the root in this case).
2) You don't need to move uploaded file before unzipping it. Simply unzip it into the newly created directory. Make sure there isn't already another directory with the same name. The uploaded file should be deleted automatically by PHP, so no need to unlink.
3) In reference to:
$name = explode(".", $filename);
What happens if the filename has more than one dot? You should really use substr() with strrpos() to get everything after the last dot.
4) After uploading, just echo the path http://www.yoursite.com/newdir - don't see the problem. If you can be more specific about what you are having difficulty with, please comment.
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.