PHP - How to upload file uri from mobile device to web server? - php

I'm trying to build an mobile app that is capable to upload images to server. However, there's some problem with my php script, when I upload data URI of a screenshot, it works fine, but when I upload file URI of an image, the image uploaded into web server is broken. Can anyone help me to check what is wrong with the script?
<?php
//Generate a folder if it doesn't exist
if (!file_exists('user_images/'))
{
mkdir('user_images', 0755, true);
}
//Get submitted data by user
if (isset($_POST['CanvasPic'])) {
$img1 = $_POST['CanvasPic'];
} else {
$img1 = '';
}
if (isset($_POST['name'])) {
$name = $_POST['name'];
} else {
$name = '';
}
define('UPLOAD_DIR', 'user_images/');
//Remove some useless string before to create image properly
//Decode base64 then generate new name
if ($img1) {
$img1 = str_replace('data:image/jpeg;base64,', '', $img1);
$img1 = str_replace(' ', '+', $img1);
$data1 = base64_decode($img1);
$file1 = UPLOAD_DIR . $name . "_" . uniqid() . '.jpeg';
$success = file_put_contents($file1, $data1);
}
//Output a URL where is saved.
$locator = $file1;
//Display a text, otherwise if error happened.
print $locator ? $file1 : 'Could not save the file!';
?>

I think you php $_FILES superglobals array it is better to file or image uploading using php script to mobile device.
base64_decode()- it time consuming process to upload file to server.

Try below code.
$name = isset($_POST['name']) ? $_POST['name'] : '';
$uploadFileName = $name."_".uniqid().".jpeg";
define('UPLOAD_DIR', 'user_images/');
if (move_uploaded_file($_FILES['CanvasPic']['tmp_name'],UPLOAD_DIR.$uploadFileName)) {
echo "Uploaded.";
} else {
echo "File was not uploaded.";
}

Related

Error saving the path of an image in my database

I want to save the path of an image in my database, these images are generated with html2canvas and are saved in a directory, but when I generate them and save them in my database, a non-existent image name is generated and that is the one that stores me.
This is the code of how the image is saved in the database:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
include './save.php';
$file = './images';
$route = $file. "/". $imgName;
$insert = $conexion->query("INSERT INTO images (img) VALUES ('$route')");
if ($insert) {
echo "<script>alert('successfully registered image')</script>";
}
else {
echo '<script>("Ups...Something's wrong")</script>';
}
}
This is the code that decodes the image for me and saves it in the folder:
$image = json_decode(file_get_contents("php://input"));
$image = $image->capture;
$image = str_replace("data:image/png;base64,", "", urldecode($image));
$image = base64_decode($image);
$imgName = "Image_" . uniqid() . ".png";
file_put_contents("images/$imgName", $image);

File upload URL

I am trying to upload a canvas image to my server using AJAX, the AJAX is working fine, however when I give the server the URL it converts it and adds backslash in at every folder in the URL, and I cant see how. I need it to stop adding these backslashes into the string.
if(isset($_POST['saveCanvas']) && $_POST['saveCanvas'] == "1"){
$img = $_POST['canvasURL'];
$img = str_replace('data:image/png;base64','',$img);
$img = str_replace(' ', '+',$img);
$data = base64_decode($img);
$file = "https://example.com/wp-content/plugins/my-plugin/images" . uniqid() . '.png';
$success = file_put_contents($file, $data);
$return = [];
$return['success'] = 1;
$return['message'] = 'Image Uploaded! ' . $file;
echo json_encode($return);
}
This is what I want the output to look like https://example.com/wp-content/plugins/my-plugin/images and this is the current output https:\/\/example.com\/wp-content\/plugins\/my-plugin\/images5f7d97548917d.png
If I am not mistaken, this happens because you are JSON encoding your return array. Did you try to just returning $file upon success?
Based on your current issue I would suggest you do this on your php.
if(isset($_POST['saveCanvas']) && $_POST['saveCanvas'] == "1"){
$img = $_POST['canvasURL'];
$img = str_replace('data:image/png;base64','',$img);
$img = str_replace(' ', '+',$img);
$data = base64_decode($img);
$file = "https://example.com/wp-content/plugins/my-plugin/images" . uniqid() . '.png';
echo file_put_contents($file, $data) ? $file : 0;
}
This will check if the file has been uploaded and return a file name or the integer 0.
When the response reaches your ajax, the ajax will check the response.
if its 0, it will be counted as false so you can do.
if(response){
//success code
}else{
//fail code
}
For example
alert(response ? 'Image Uploaded! '+ response : 'Failed to upload');

Upload video from iPad - PHP

Stuck on some weird errors. Created an ipad web app to upload video from ipad gallery to my web server. Showing invalid file format, same video directly from desktop browser, working fine. Is there any issue with iPad or any mime type issue. See my code.
<?php
ini_set('max_execution_time', 2400);
$path = "uploads/";
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
$valid_formats = array("mp4", "MP4","jpg","avi","AVI");
list($txt, $ext) = explode(".", $name);
$errors = array();
$form_data = array();
if(!empty($name))
{
if(in_array($ext,$valid_formats))
{
if ($size<(1024*1024*1024*1024*1024*1024*1024*1024*1024*1024*1024*1024*1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
} else {
$errors['imgsize'] = 'Image file size max issue.<br/>';
}
} else{
$errors['imgformat'] = 'Invalid file format..<br/>';
}
}
if (!empty($errors)) {
$form_data['success'] = false;
$form_data['errors'] = $errors;
} else {
$form_data['success'] = true;
$form_data['posted'] = '1';
move_uploaded_file($tmp, $path.$actual_image_name);
}
//Return the data back to form.php
header('Content-type: application/json');
echo json_encode($form_data);
?>
I faced the similar issue, what ipad/iphone does it compresses & change the format to MOV whatever the format is. If you are uploading mp4, it will convert to MOV. Since your code does not check MOV format so its throwing an error. Add mov format and it will work. You are welcome :)

Php file upload strange behaviour, occasionally upload is empty

I use this script to upload files via POST from my android app to my server. 95% of the time it works ok, but sometimes the upload folder of my clients is empty. The file is sent definitely, because I get the name and phone numbers (without a file selected the app will not pass any data), but the uploaded file is not written to disk on the server. I am not an expert in php, maybe I have missed something:
My upload php script:
$file_path = "uploads/{$_POST['name']}/";
if (!file_exists("uploads/{$_POST['name']}")) {
mkdir("uploads/{$_POST['name']}", 0777, true);
} else {
echo 'folder already exists!';
}
$newfile = $_POST['name'] . "_" . date('m-d_H-i-s') . '.zip';
$filename = $file_path . $newfile;
if(!file_exists($filename)) {
if(move_uploaded_file($_FILES['zipFile']['tmp_name'], $filename)) {
echo "success";
}
} else {
echo 'file already exists';
}

Uploading an image with rackspace

So i have the following codes that uploads an image to the dir /uploads.
<?php
// If you want to ignore the uploaded files,
// set $demo_mode to true;
$demo_mode = false;
$upload_dir = 'uploads/';
$allowed_ext = array('jpg','jpeg','png','gif');
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
$pic = $_FILES['pic'];
if(!in_array(get_extension($pic['name']),$allowed_ext)){
exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
}
if($demo_mode){
// File uploads are ignored. We only log them.
$line = implode('', array( date('r'), $_SERVER['REMOTE_ADDR'], $pic['size'], $pic['name']));
file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);
exit_status('Uploads are ignored in demo mode.');
}
// Move the uploaded file from the temporary
// directory to the uploads folder:
if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
exit_status('File was uploaded successfuly!');
}
}
exit_status('Something went wrong with your upload!');
// Helper functions
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
?>
I tried to change the code a bit. So instead of uploading to the directory, i wanted it to upload to my rackspace. I am using the following codes (which works with my other file uploads)
// cloud info
$username = ""; // username
$key = ""; // api key
// Connect to Rackspace
$auth = new CF_Authentication($username, $key);
$auth->authenticate();
$conn = new CF_Connection($auth);
// Get the container we want to use
$container = $conn->get_container('ContainerName');
// store file information
$localfile = $_FILES['pic']['tmp_name'];
$filename = $_FILES['pic']['name'];
// upload file to Rackspace
$object = $container->create_object($filename);
$object->load_from_filename($localfile);
?>
I replaced the part where the image uploads to the dir /upload to the above one. It's not working.
I am using this HTML5 drag & drop uploader.
http://tutorialzine.com/2011/09/html5-file-upload-jquery-php/
Help please.
I had a problem similar to this. The issue I had was that the object doesn't have the file type associated with it. Someone probably can explain it better as I am a PHP newb, but this is what I used for it to work for me:
$object = $container->create_object($filename);
$object->content_type = "image/jpeg"; //This is where the issue is
$object->load_from_filename($localfile);

Categories