Store Image from PHP to MYSQL - php

I have a PHP file with code as below with the functionality to save an image in a file directory , after uploading from mobile.
<?PHP
$data = file_get_contents('php://input');
echo $data;
exit ($data);
if (!(file_put_contents($_GET['filename'],$data) === FALSE)) echo "File xfer completed."; // file could be empty, though
else echo "File xfer failed.";
?>
We dont have much control on the front end side to change , so the logic of storing an image in MY SQL db should be from PHP script.
the $data echo results as below for an image of JPG format http://goo.gl/4AsU52
$data Echo :
Now , how do i store the $data value/its relative file directory in php into MYSQL DB?

Related

download file to my server with php with a url without file name

I can download a csv file via a fixed url. The url just doesn't have a file name.
When I open the url in a browser, the file export.csv is generated and after about 10 sec the download starts.
Now I want to download this export csv file directly to my own server,
I have the code below, but it doesn't work in my case.
Can you help me? my thanks are big
<?php
$url =
'https://www.example.com/product-export/link123456789';
$file_name = basename($url);
if (file_put_contents($file_name, file_get_contents($url)))
{
echo "File downloaded successfully";
}
else
{
echo "File downloading failed.";
}
?>
As the generated output filename is always export.csv, we may use the following to specify the filename:
$file_name = dirname(__FILE__) . "/export.csv";
(make sure the directory is write-permitted so that the php can save the file "export.csv")
Hence, the code will be:
<?php
$url = 'http://www.createchhk.com/SOanswers/export1a.csv';
//$file_name = basename($url);
$file_name = dirname(__FILE__) . "/export.csv";
if (file_put_contents($file_name, file_get_contents($url))) {
echo "File downloaded successfully";
} else {
echo "File downloading failed.";
}
?>
For your cronjob, it will be something like :
1 1 * * * php /path_to_the_php/test.php

Image upload to mysql

My site is able to upload a file but I don't understand how to get the path to the file for the database query. When someone uploads an image, the path to the image should get directly inserted into the users table in the userpic field. How can I achieve this?
<?PHP
if(isset($_FILES['file'])) {
move_uploaded_file($_FILES['file']['tmp_name'],'files/'.$_FILES['file']['name']);
session_start();
$username = $_SESSION['user'];
$userpic = ???? // <-- what am i supposed to call here to put the path to my image file
include ("connect.php");
$sql = $con->prepare('INSERT INTO users (username,userpic) VALUES (?,?)');
$sql->bind_param("ss",$username,$userpic);
$sql->execute();
$sql->close();
$con->close();
} else {
echo "no files";
}
?>
If you store files using the name provided by the client when the file is uploaded, you will potentially overwrite images (e.g. if two users upload me.png) - it would be much better to use the username to store the images, and then you don't even need the mysql table to connect users to their pics..
<?php
session_start();
$username = $_SESSION['user'];
if(empty($username)){
echo "Error: no username found";
}
else if(isset($_FILES['file']) ){
//create a path to move file to
$newpath = 'files/'.$username;
if (move_uploaded_file($_FILES['file']['tmp_name'], $newpath)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Error: Possible file upload attack!\n";
}
}
else{
echo "No Files to save";
}
In this code we use the username from the session, and check its not blank.
We then use this to store the image in your files folder.
Note this ignores a number of security issues:
Including ../ in your username which would cause the file to be saved outside of the files directory.
This may not be an issue if you have already validated the username, another solution would be to create a hash of the username and using this instead: $newpath = 'files/'.md5($username);
Not checking for errors, or verifying the file is indeed an image.
http://php.net/manual/en/features.file-upload.errors.php
PHP image upload security check list
How are these images going to be used after this?
If the files directory is within your htdocs, the contents will be available for all - it would probably be better to store it outside of your htdocs
e.g. $newpath = '/var/myappdata/userimages/'.md5($username);
You could then create another file userimage.php which reads the file:
<?php
session_start();
$username = $_SESSION['user'];
$path = '/var/myappdata/userimages/'.md5($username);
readfile($path);
This allows you to do additional checks e.g. that the user is allowed to see the image.
There is still a huge amount that could be covered here, hopefully this gives you enough to move forward, but do please read more about file upload security before putting this into production.
Your original question
If you did want to store information about the image in your database you could do something like this:
<?php
session_start();
include ("connect.php");
$username = $_SESSION['user'];
if(empty($username)){
echo "Error: no username found";
}
else if(isset($_FILES['file']) ){
//create a path to move file to
$filename = basename($_FILES['file']['name']);
$newpath = 'files/'.$filename;
if (move_uploaded_file($_FILES['file']['tmp_name'], $newpath)) {
echo "File is valid, and was successfully uploaded.\n";
$sql = $con->prepare('INSERT INTO users (username,userpic) VALUES (?,?)');
$sql->bind_param("ss",$username,$filename);
$sql->execute();
$sql->close();
$con->close();
} else {
echo "Error: Possible file upload attack!\n";
}
}
else{
echo "No Files to save";
}
As I said though - you will run into conflicts if two users upload the same file.
You aren't going to want to store the entire URL in the database. You just need the path to where it is on the server. That is the part where you are moving the tmp file to a new location. In your case it would be the following.
$userpic = 'files/'.$_FILES['file']['name'];

Php unlink file which is in use situation?

In my personal experience, you cannot delete something that's in use, I think unlink() will not work if the target file is in use, how do you handle that?
<?php unlink ("notes.txt"); // how to handle if file in use? ?>
unlink returns a boolean that you can use to detect if deletion was successful or not:
<?php
$file = fopen('notes.txt','w');
fwrite($file,'abc123');
$resul = unlink("notes.txt"); // ◄■■■ ATTEMPT TO DELETE OPEN FILE.
if ( $resul )
echo "File deleted";
else echo "File NOT deleted (file in use or protected)";
fclose($file);
?>
You might see a warning message on screen, so turn off warnings and let your code (the if($resul)) handle the problem.
Edit :
It's possible to detect whether the file is in use or it is protected by using the function is_writable, next code shows how :
<?php
$file = fopen("notes.txt","w"); // ◄■■■ OPEN FILE.
fwrite($file,"abc123");
$resul = unlink("notes.txt"); // ◄■■■ ATTEMPT TO DELETE FILE.
if ( $resul ) // ◄■■■ IF FILE WAS DELETED...
echo "File deleted";
elseif ( is_writable( "notes.txt" ) ) // ◄■■■ IF FILE IS WRITABLE...
echo "File NOT deleted (file in use)";
else echo "File NOT deleted (file protected)";
fclose($file);
?>
To test previous code, open the properties of the file and set it to readonly and hidden, then run the code.

Uploading files using php very slow in xampp

I am new for developing.I have opted for php to learn coding.So I might make mistake as I learn by myself, kindly clarify my doubts.
I have problem in uploading files using php to a folder.What I really do is, I upload a file and the file is saved in a folder and the name of the file alone inserted in the database. While uploading the file I do copy the file to another folder which will be used for the editing purpose so that the original file will not be disturbed.Here the problem I get is, the file is uploaded successfully as well as the name too inserted in database. But it take much time to get upload even the size of the file is small.It works good while I test using my local but when I come in real time this issue(slow uploading) I face. What the person incharge in uploading do is, uploading a file and opening a new browser and upload another file. When the new browser is opened the files get uploaded but in the previous browser it is still in process. The code I have written to copy the file to another folder is not executed as the new browser is opened to upload another set of files. I am using xamp cp v3.2.1.To minimize the execution time I have set the default Maximum execution time to 30. But unable to upload file fastly.
Below is my php coding:
<?php
// connect to the database
include('connect-db.php');
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
$file_array=($_FILES['file_array']['name']);
// check to make sure both fields are entered
if ($udate == '' || $file_array=='')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($udate, $file_array, $error);
}
else
{
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
if(isset($_FILES['file_array']))
{
$name_arrray=$_FILES['file_array']['name'];
$tmp_name_arrray=$_FILES['file_array']['tmp_name'];
for($i=0;$i <count($tmp_name_arrray); $i++)
{
if(move_uploaded_file($tmp_name_arrray[$i],"test_uploads/".str_replace(' ','',$name_arrray[$i])))
{
// save the data to the database
$j=str_replace(' ','',$name_arrray[$i]);
echo $j;
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
$provider = mysql_real_escape_string(htmlspecialchars($_POST['provider']));
$existfile=mysql_query("select ubatch_file from batches");
while($existing = mysql_fetch_array( $existfile)) {
if($j==$existing['ubatch_file'])
echo' <script>
function myFunction() {
alert("file already exists");
}
</script>';
}
mysql_query("INSERT IGNORE batches SET udate='$udate', ubatch_file='$j',provider='$provider',privilege='$_SESSION[PRIVILEGE]'")
or die(mysql_error());
echo $name_arrray[$i]."uploaded completed"."<br>";
$src = 'test_uploads';
$dst = 'copy_test_uploads';
$files = glob("test_uploads/*.*");
foreach($files as $file){
$file_to_go = str_replace($src,$dst,$file);
copy($file, $file_to_go);
/* echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Uploaded.\");
window.location = \"uploadbatches1.php\"
</script>";*/
}
} else
{
echo "move_uploaded_file function failed for".$name_array[$i]."<br>";
}
}
}
// once saved, redirect back to the view page
header("Location:uploadbatches1.php");
}
}
?>
It takes much time because, each and everytime all the files are copied to the newfolder. This exceeds the execution time.Only copying the uploaded files makes uploading and copying files fast.

replacing the process with file url instead of file upload in php

am uploading a Pdf file and passing it to getExtact function to extract pages from file which is being uploaded if any error in extraction we will send the file to decryptPDF function for which the input parameters are filename and filetempname for both the functions but here am using a file upload process i want to use file url like www.domainname.com/docs/1.pdf so that all the functions which are written already can be used : Below is my code
//here for the above variable values are coming from uploaded file here i want to use file url and all the pdf are in my own server
$FileName = $_FILES['inputfile']['name'];
$TempFileName = $_FILES['inputfile']['tmp_name']; $Folderpath='/home/domain/public_html/pdftest/temp';
try {
.
GetExtract($TempFileName,$FileName);
} catch (Exception $e) {
$responce = DecryptPDF($Folderpath,$Filename,$TempFileName);
if($responce == ''){
$Inputfile = $Folderpath.'/un_'.$Filename;
GetExtract($Inputfile,$FileName);
}else{
echo $responce;
}
As per my knowledge,local server $PATH is "/var/www/".Try putting your inputfiles in that location.Then only you can access the files using url.

Categories