What I'm trying to do is save the binary file sent through CURL from another server.
The php uploader I have is:
<?php
define("UPLOAD_DIR", "/tmp/");
if (!empty($_FILES["myFile"])) {
$myFile = $_FILES["myFile"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
}
So i have this on my site as such:
example.com/uploader.php
On server number 2, I run the command:
curl --request POST --data-binary "#binary.jpg" http://example.com/uploader.php
and then I check my /tmp/ folder for the file named binary.jpg but it is not there, what is the issue here ?
Thanks.
It may at location where you run curl command. For example if you run at /home/student then binary. Jpg is at the location /home/student/binary. Jpg
After running curl command, are you getting successful transfer message?
In the code, if (!empty($_FILES["myFile"])) { , you are specifically checking field named myFile of array $_FILES and then doing stuff. While the curl command does not suggest that the binary file is being sent with name myFile. You can sepcify the name of the POST fields in you curl command and issue will be resolved hopefully. (Also try printing the whole $_POST and $_FILES array in code for debugging purposes)
Related
i have the following code in android
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(getContext(), uploadId, url_upload_cert)
.addFileToUpload(path, "pdf") //Adding file
.addParameter("name", name) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload();
and in php
<?php
//importing dbDetails file
require_once __DIR__ . '/db_connect.php';
//this is our upload folder
$upload_path = 'android/';
//Getting the server ip
$server_ip = gethostbyname(gethostname());
//creating the upload url
//$upload_url = 'http://'.$server_ip.'/pavo_project/'.$upload_path;
$upload_url='/src';
//response array
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//checking the required parameters from the request
if(isset($_POST['name']) and isset($_FILES['jpg']['name'])){
// connecting to db
$db = new DB_CONNECT();
//getting name from the request
$name = $_POST['name'];
//getting file info from the request
$fileinfo = pathinfo($_FILES['jpg']['name']);
//getting the file extension
$extension = $fileinfo['extension'];
//file url to store in the database
$file_url = $upload_url . $name . '.' . $extension;
//file path to upload in the server
$file_path = $upload_url . $name . '.'. $extension;
//trying to save the file in the directory
try{
//saving the file
move_uploaded_file($_FILES['jpg']['tmp_name'],$file_path);
}catch(Exception $e){
$response['error']=true;
$response['message']=$e->getMessage();
}
//closing the connection
// mysqli_close($db);
}else{
$response['error']=true;
$response['message']='Please choose a file';
}
//displaying the response
echo json_encode($response);
}
?>
when i run the android code it runs succesfully with no error but when i check the image in the src folder its not there
The same things happens when i test the script using postman
Am using wamp server on windows .
what might be the reason causing this?
Check the writing permissions of your folder.
For example in Linux, a level above your folder you can user the following command:
sudo chmod -R 777 <your-folder-name>
And that might let the php code save the file inside of it, because it will grant the permissions to write/read/delete to every user.
Also you can check the php.ini file, and check if the line:
file_uploads = On
Has the On value
If that doesn't work you can check for a default php.ini file and try replacing your php.ini file with that.
I am uploading files to a server using php and while the move_uploaded_file function returns no errors, the file is not in the destination folder. As you can see I am using the exact path from root, and the files being uploaded are lower than the max size.
$target = "/data/array1/users/ultimate/public_html/Uploads/2010/";
//Write the info to the bioHold xml file.
$xml = new DOMDocument();
$xml->load('bioHold.xml');
$xml->formatOutput = true;
$root = $xml->firstChild;
$player = $xml->createElement("player");
$image = $xml->createElement("image");
$image->setAttribute("loc", $target.basename($_FILES['image']['name']));
$player->appendChild($image);
$name = $xml->createElement("name", $_POST['name']);
$player->appendChild($name);
$number = $xml->createElement("number", $_POST['number']);
$player->appendChild($number);
$ghettoYear = $xml->createElement("ghettoYear", $_POST['ghetto']);
$player->appendChild($ghettoYear);
$schoolYear = $xml->createElement("schoolYear", $_POST['school']);
$player->appendChild($schoolYear);
$bio = $xml->createElement("bio", $_POST['bio']);
$player->appendChild($bio);
$root->appendChild($player);
$xml->save("bioHold.xml");
//Save the image to the server.
$target = $target.basename($_FILES['image']['name']);
if(is_uploaded_file($_FILES['image']['tmp_name']))
echo 'It is a file <br />';
if(!(move_uploaded_file($_FILES['image']['tmp_name'], $target))) {
echo $_FILES['image']['error']."<br />";
}
else {
echo $_FILES['image']['error']."<br />";
echo $target;
}
Any help is appreciated.
Eric R.
Most like this is a permissions issue. I'm going to assume you don't have any kind of direct shell access to check this stuff directly, so here's how to do it from within the script:
Check if the $target directory exists:
$target = '/data/etc....';
if (!is_dir($target)) {
die("Directory $target is not a directory");
}
Check if it's writeable:
if (!is_writable($target)) {
die("Directory $target is not writeable");
}
Check if the full target filename exists/is writable - maybe it exists but can't be overwritten:
$target = $target . basename($_FILES['image']['name']);
if (!is_writeable($target)) {
die("File $target isn't writeable");
}
Beyond that:
if(!(move_uploaded_file($_FILES['image']['tmp_name'], $target))) {
echo $_FILES['image']['error']."<br />";
}
Echoing out the error parameter here is of no use, it refers purely to the upload process. If the file was uploaded correctly, but could not be moved, this will still only echo out a 0 (e.g. the UPLOAD_ERR_OK constant). The proper way of checking for errors goes something like this:
if ($_FILES['images']['error'] === UPLOAD_ERR_OK) {
// file was properly uploaded
if (!is_uploaded_File(...)) {
die("Something done goofed - not uploaded file");
}
if (!move_uploaded_file(...)) {
echo "Couldn't move file, possible diagnostic information:"
print_r(error_get_last());
die();
}
} else {
die("Upload failed with error {$_FILES['images']['error']}");
}
You need to make sure that whoever is hosting your pages has the settings configured to allow you to upload and move files. Most will disable these functions as it's a sercurity risk.
Just email them and ask whether they are enabled.
Hope this helps.
your calls to is_uploaded_file and move_uploaded_file vary. for is_uploaded_file you are checking the 'name' and for move_uploaded_file you are passing in 'tmp_name'. try changing your call to move_uploaded_file to use 'name'
Understanding that the following question is not best practices by any means. The tool i am building is for personal use and will not be accessible to the internet in general. With that being said here is the idea or outline of what i am trying to accomplish.
PHP:
define("UPLOAD_DIR", "/var/www/html/uploads/");
if (!empty($_FILES["SANUpload"])) {
$myFile = $_FILES["SANUpload"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
$val = shell_exec("tar -xvf $parts -C /var/www/html/uploads 2>&1");
echo '$val';
}
The goal is once it gets uploaded I need to sort the files and put them in the correct spots. The upload will ALWAYS be a TAR file because the scripts that i built for it the ONLY output is a tar file.
My goal is to extract the tar file in uploads directory and then run move commands to move the files where they need to be. Then do a clean up and delete any files in the UPLOADS dir.
I found this example on here :
$val = shell_exec("tar -xvf $parts -C /var/www/html/uploads 2>&1");
echo '$val';
This is another component i am looking at as well:
try {
$phar = new PharData('myphar.tar');
$phar->extractTo('/full/path'); // extract all files
$phar->extractTo('/another/path', 'file.txt'); // extract only file.txt
$phar->extractTo('/this/path',
array('file1.txt', 'file2.txt')); // extract 2 files only
$phar->extractTo('/third/path', null, true); // extract all files, and overwrite
} catch (Exception $e) {
// handle errors
}
The problem I am having with PharData is that it doesn't like the $path or $name variables. The same can be said for the example above PharData. Since the upload script could have different names I need to have the ability to unzip the file as a variable or to use a variable in the php script.
Technically - the script I have would keep the tar name the same however I could see a use case where someone might change that. So want to make sure that I have the option to address that.
So question is how do i extract a tar file - utilizing a variable name rather than have it spelled out and the actual name of the file all in PHP?
Figured out the issue - i needed to utilize the UPLOAD_DIR . $name in the pharData.
try {
$phar = new PharData(UPLOAD_DIR . $name);
$phar->extractTo(UPLOAD_DIR); // extract all files
} catch (Exception $e) {
// handle errors
}
I'm converting an image to a binary file in IOS, which works just fine. This will be handled by my php script which is suppose to upload this image to my ubuntu server. The problem is i keep getting file=unsuccessful. i've tried different directory paths, but cant seem to solve this issue.
This $directory will return this: /var/www/User/core/ios/
<?
if(!empty($_POST))
{
$message = $_POST['message'];
$directory = $_SERVER['DOCUMENT_ROOT'] . '/User/core/ios/';
$file = basename($_FILES['userfle']['upload']);
$uploadfile = $directory . $file;
var_dump($_FILES);
$randomPhotoID = md5(rand() * time());
echo 'file='.$file;
echo $file;
if (move_uploaded_file($_FILES['userfle']['tmp_name'], $uploadfile)) {
echo 'successful';
}
else
{
echo 'unsuccessful';
}
}
else
{
echo('Empty post data');
}
?>
Check the error file of your php(you can make sure if you enabled the error log in php.ini),
if you don't have the permission or for some other reasons it can't move the file ,there will be a record in that file.
Some time you can try the command setenforce 0 if you confirm you(I means the user of apache) have the permission to move the file but it not work.
By the way if the file you want to move is not upload by post, there is no error log and the move function will return false.
i have just come across what i think i need for my front end multi uploader script in joomla.
Mootools fancy upload looks great! but i am having trouble when i uncomment the script that uploads the images inside the uploads folder?
All i have done is uncommented the default script inside the test file and created a folder called uploads which i set to 757 and also tried 777
But for some reason the uploader now returns some strange error about md 5 hash stuff?
eastern_beach_jetty.jpgAn error occured:
Warning: md5_file(/tmp/phpUjHol4) [function.md5-file]: failed to open stream: No such file or directory in /home/user/www.mydomain.com.au/test/server/script.php on line 133
{"status":"1","name":"eastern_beach_jetty.jpg","hash":false}
The fancy uploader website from where i got the script is here http://digitarald.de/project/fancyupload/
Any help on this would be so greatly apprecited,
thank you.
John
Coincidentally, I did the same mistake as you, the reason is that the first move tmp file to the destination folder, and then referring to the tmp file, which no longer exists, because it is in the target folder. I know that the late response, but it was as if someone had the same problem.
Not:
move_uploaded_file($_FILES['Filedata']['tmp_name'], '../uploads/' . $_FILES['Filedata']['name']);
$return['src'] = '/uploads/' . $_FILES['Filedata']['name'];
if ($error) {
(...)
} else {
(...)
// $return['hash'] = md5_file($_FILES['Filedata']['tmp_name']);
// ... and if available, we get image data
$info = #getimagesize($_FILES['Filedata']['tmp_name']);
if ($info) {
$return['width'] = $info[0];
$return['height'] = $info[1];
$return['mime'] = $info['mime'];
}
}
Yes:
if ($error) {
(...)
} else {
(...)
// $return['hash'] = md5_file($_FILES['Filedata']['tmp_name']);
// ... and if available, we get image data
$info = #getimagesize($_FILES['Filedata']['tmp_name']);
if ($info) {
$return['width'] = $info[0];
$return['height'] = $info[1];
$return['mime'] = $info['mime'];
}
}
move_uploaded_file($_FILES['Filedata']['tmp_name'], '../uploads/' . $_FILES['Filedata']['name']);
$return['src'] = '/uploads/' . $_FILES['Filedata']['name'];