equivalent $_FILES["imageToUpload"]["tmp_name"] when I use file_get_contents() function - php

I have a function like this:
fitImageSizeAndSave($_FILES["imageToUpload"]["tmp_name"], $target_file) { ... }
That function works well. The first argument is $_FILES["imageToUpload"]["tmp_name"]. Ok, it's good when an user upload an image from his local computer. But sometimes he enters a external link and I get that image like this:
$image = file_get_contents($_POST['external_link']);
How can I make $image like $_FILES["imageToUpload"]["tmp_name"] for passing it to the function?

use file_put_contents() and then reference the temporary file that you've just put the data into
#Martin Sounds a great idea, may you please add an answer? –
$_FILES["imageToUpload"]["tmp_name"] is simply a string to a file location on the server, it is not a resuorce in itself.
$filePathLocation = $_SERVER['DOCUMENT_ROOT']."/some-temporary/file/storage";
$imageData = file_get_contents($_POST['external_link']);
if($imageData){
file_put_contents($imageData, $filepathLocation);
}
else {
$filepathLocation = $_FILES["imageToUpload"]["tmp_name"];
}
fitImageSizeAndSave($filepathLocation, $target_file) { ... }
The above, step by step:
Set a temporary storage location; possibly based on microtime() or something unique (database Id, if relevant) to limit different processes overwriting the same file path.
get the contents of the $_POST file URL. save to a string variable.
Check if variable is loaded ok; else use uploaded temporary file location THIS IS FOR ILLUSTRATION ONLY - You should have a more complete process for checking which data to use and the validity of said data already set up in your script.
Send this variable to your custom function, knowning it is populated with one or the other of the possibilities above.

The below is the PHP script to get image from url and save into your location machine or into own server
$imageurl ='http://i.ndtvimg.com/i/2015-08/mahesh-babu_630x450_81440064359.jpg';
$content = file_get_contents($imageurl);
if(file_put_contents('imagefolder/randomImageName.jpg', $content)){
echo "File uploaded through URL";
}else{
echo "File not uploaded...";
}

Related

What is the best way to get the parameters in PHP?

I will completely clarify my question, sorry to everybody.
I have code writed in files from a website that now is not working, the html code is on pages with php extension, in a folder of a Virtual Host in my PC using Wampserever. C:\wamp\1VH\PRU1, when the site was online there was a folder where was a file called image.php. This file was called from other pages inside the site like this: (a little code of a file, C:\wamp\1VH\PRU1\example.php)
"<div><img src="https://www.example.com/img/image.php?f=images&folder=foods&type=salads&desc=green&dim=50&id=23" alt="green salad 23"></div>"
And the result was that the images was showed correctly.
Now, like i have this proyect in local, and i HAVE NOT the code of that image.php file i must to write it myself, this way the images will be showed the same way that when the site was online.
When the site was online and i open a image returned by that image.php file the URL was, following the example, https://example.com/images/foods/salads/green_50/23.png.
Now how the site is only local and i have not that image.php file writed because i'm bot sure how to write it, the images obviously are not showed.
In C:\wamp\1VH\PRU1\example.php the code of files was changed deleting "https://www.example.com/img/image.php?" for a local path "img/image.php?".
And in the same folder there is anothers: "img" folder (here must be allocated the image.php file), and "images" folder, inside it /foods/salads/green_50/23.png, 24.png.25.png..............
So i have exactly the same folder architecture that the online site and i changed the code that i could only, for example replacing with Jquery "https://www.example.com/img/image.php?" for "img/image.php?" but wich i can not do is replace all the code after the image.php file to obtain a image file.
So i think that the easiest way to can obtain the images normally is creating that IMAGE.PHP file that i have not here in my virtual host.
I'd like to know how to obtain the parameters and return the correct URL in the image,php file.
The image of the DIV EXAMPLE must be C:/wamp/1VH/PRU1/images/foods/salads/green_50/23.png
I have in my PC the correct folders and the images, i only need to write the image.php file.
Note that there are "&" and i must to unite the values of "desc=green&dim=50&" being the result: green_50 (a folder in my PC).
TVM.
You probably want something like this.
image.php
$id = intval($_GET['id']);
echo '<div><img src="images/foods/salads/green_50/'.$id.'.png" alt="green salad '.$id.'"></div>';
Then you would call this page
www.example.com/image.php?id=23
So you can see here in the url we have id=23 in the query part of the url. And we access this in PHP using $_GET['id']. Pretty simple. In this case it equals 23 if it was id=52 it would be that number instead.
Now the intval part is very important for security reasons you should never put user input directly into file paths. I won't get into the details of Directory Transversal attacks. But if you just allow anything in there that's what you would be vulnerable to. It's often overlooked, so you wouldn't be the first.
https://en.wikipedia.org/wiki/Directory_traversal_attack
Now granted the Server should have user permissions setup properly, but I say why gamble when we can be safe with 1 line of code.
This should get you started. For the rest of them I would setup a white list like this:
For
folder=foods
You would make an array with the permissible values,
$allowedFolders = [
'food',
'clothes'
'kids'
];
etc...
Then you would check it like this
///set a default
$folder = '';
if(!empty($_GET['folder'])){
if(in_array($_GET['folder'], $allowedFolders)){
$folder = $_GET['folder'].'/';
}else{
throw new Exception('Invalid value for "folder"');
}
}
etc...
Then at the end you would stitch all the "cleaned" values together. As I said before a lot of people simply neglect this and just put the stuff right in the path. But, it's not the right way to do it.
Anyway hope that helps.
You essentially just need to parse the $_GET parameters, then do a few checks that the file is found, a real image and then just serve the file by setting the appropriate content type header and then outputting the files contents.
This should do the trick:
<?php
// define expected GET parameters
$params = ['f', 'folder', 'type', 'desc', 'dim', 'id'];
// loop over parameters in order to build path: /imagenes/foods/salads/green_50/23.png
$path = null;
foreach ($params as $key => $param) {
if (isset($_GET[$param])) {
$path .= ($param == 'dim' ? '_' : '/').basename($_GET[$param]);
unset($params[$key]);
}
}
$path .= '.png';
// check all params were passed
if (!empty($params)) {
die('Invalid request');
}
// check file exists
if (!file_exists($path)) {
die('File does not exist');
}
// check file is image
if (!getimagesize($path)) {
die('Invalid image');
}
// all good serve file
header("Content-Type: image/png");
header('Content-Length: '.filesize($path));
readfile($path);
https://3v4l.org/tTALQ
use $_GET[];
<?php
$yourParam = $_GET['param_name'];
?>
I can obtain the values of parameters in the image.php file tis way:
<?php
$f = $_GET['f'];
$folder = $_GET['folder'];
$type = $_GET['type'];
$desc = $_GET['desc'];
$dim = $_GET['dim'];
$id = $_GET['id'];
?>
But what must i do for the image:
C:/wamp/1VH/PRU1/images/foods/salads/green_50/23.png
can be showed correctly in the DIV with IMG SRC atribute?

saving a file in php without saving in a folder in yii php

Am saving a file as a long blob in php by first saving it in a folder then to a db, the problem is that the server has write permissions so i would like to save it directly
This is what i have tried (This works perfectly):
if(isset($_POST['image'])){
$id = 0;
$image = $_POST['image'];
$tmp_image = date('YmdHisu').'.jpg';
file_put_contents($tmp_image, base64_decode($image));
$sql = "INSERT INTO fingerprint(template)
VALUES ('".addslashes(file_get_contents($tmp_image))."')";
try
{
$connection=Yii::app()->db;
$command=$connection->createCommand($sql);
$rowCount=$command->execute(); // execute the non-query SQL
echo "saved successifully";
unlink($tmp_image);
}
catch(Exception $ex)
{
echo 'Query failed' , $ex->getMessage();
unlink($tmp_image);
}
}
How can i save this in a blob field in mysql without first having to save it in a folder then saving to db
Let's assume you've sent the file via Android using POST method to your server running Yii1.
First of all the physical file is contained in the $_FILES variable and in the $_POST variable, as you said, contains a string of the file encoded in base 64 format (i write this for a clear answer).
$_FILE DOCUMENTATION
Now this is how you can try to upload the file with the standard MVC yii way using yii code:
It's true that you're uploading your file from an external device but Yii came in your help with CUploadedFile Class:
Call getInstance to retrieve the instance of an uploaded file, and then use saveAs to save it on the server. You may also query other information about the file, including name, tempName, type, size and error.
In particular you should use the function getInstancesByName that returns an array of instances starting with specified array name.
$temp = CUploadedFile::getInstanceByName("image"); // $_FILES['image']
and with this you can access to the file data:
$temp->name; // Name of the file
$temp->type; // Type of the file
$temp->size; // Size of the file
// etc etc..
$temp->saveAs("/your/path/" . $tmp_image . $temp->type); // Save your file
for final you can check if the file was saved and execute your query:
if($temp->saveAs("/your/path/" . $tmp_image . $temp->type)) {
// File is saved you can execute the query for save the record in your db
} else {
// Something went wrong.
}
You can also transfer this logic in a model.
check this link for more infos
Hope this will help you.

How to display a message if file already exists

I have a javascript function in one page and in another page I have a php script which concentrates on file uploading. At the moment my files are uploading successfully which is great news. My question though is that I want to use the php to check if a file already exists in the folder but I want to use the javascript function to display an message to state file already exists if this is true. How can this be done?
Below is the php code which checks if file exists:
if (file_exists("upload/" . $_FILES["fileImage"]["name"]))
{
}
Below is the Javascript function when file stops uploading. at moment if file doesn't upload it displays a message stating there is an error while uploading file and it displays a message if file is successfully uploaded, but I want an extra message where if file doesn't upload but this is because the file already exists, then I want it to display a message stating file already exists.
function stopImageUpload(success){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
}
P.S Please no one put in their answer why don't I just put an echo in the php code, I don't want to do it like that because the user never actually navigates to the php script.
In yours PHP code that checks if file exists do
else{
echo 2;
}
In yours JS code in else clausule do
if(success == 2){
result = '<span class="emsg">File already exist!</span><br/><br/>';
}
That is a quick solution, but it gives You a way to do more complex file handling via JS/PHP. For example. When PHP returns a data 1, then everything is ok, when 2 then file exists, when 3 then file is too large, when 4 then file with bad extension, when 5 then something else, and so on.
This method I have encountered when learning C/C++(in C this way is like a standard thing). This way You can give info how some parts of code went.
Still, I would generete a a random name for file, if the name is irrelevant, and if name of file is important then wold use AJAX to check it, and display info about it, or maybe append a number after file name (file(1).xyz, file(2).xyz, file(3).xyz). That depends on what You are trying to achieve.
You say.
P.S Please no one put in their answer why don't I just put an echo in
the php code, I don't want to do it like that because the user never
actually navigates to the php script.
you need to execute some php code anyway. so you will have to do this one way or another. then , display the information to the user using whatever way you want.
since we dont have all the code i assume you have a input[type=file] in the html code , so you need to use ajax with the value of the input. send it to your server , check if the filename already exists , then respond with true or false with ajax from php and execute the code in javascript that will tell the user if the file exists or not. you can use jQuery to do that :
$("#myInput").on("change",function(event){
$.getJSON("checkFileService.php",{filename:$(event.currentTarget).val()},
function(datas){
if(datas.exists === true){
doSomething();
else{
doSomethingElse();
}
}
}
Check the jQuery ajax api for more infos
you'll have to write a php script that outputs some json string like {"exists":true} in order for the client script to work.
#safarov Can you show me an example of a function to see if file already exists, then write different name for new uploaded file?
Save/upload a simple text file named "filenamecounter.txt",
containing only text 1 in it.
<?php
//Get the original name of file
$tmp_name = $_FILES["filename"]["tmp_name"];
//Get/Read File Name Counter
$filenamecounter = file_get_contents('filenamecounter.txt');
//If it is less than 10, add a "0"/Zero to make it like 01,02,03
if (strlen($filenamecounter) <= 1){
$filenamecounter = str_pad($filenamecounter, 2, '0', STR_PAD_LEFT);
}
//Assign Filename + Variable
$name = "filename".$filenamecounter.".txt";
//Save file with new name
move_uploaded_file($tmp_name, $name);
//write quotecounter to file.
$filenamecounter++;
file_put_contents("filenamecounter.txt", $filenamecounter);
?>

PHP - upload and overwrite a file (or upload and rename it)?

I have searched far and wide on this one, but haven't really found a solution.
Got a client that wants music on their site (yea yea, I know..). The flash player grabs the single file called song.mp3 and plays it.
Well, I am trying to get functionality as to be able to have the client upload their own new song if they ever want to change it.
So basically, the script needs to allow them to upload the file, THEN overwrite the old file with the new one. Basically, making sure the filename of song.mp3 stays intact.
I am thinking I will need to use PHP to
1) upload the file
2) delete the original song.mp3
3) rename the new file upload to song.mp3
Does that seem right? Or is there a simpler way of doing this? Thanks in advance!
EDIT: I impimented UPLOADIFY and am able to use
'onAllComplete' : function(event,data) {
alert(data.filesUploaded + ' files uploaded successfully!');
}
I am just not sure how to point THAT to a PHP file....
'onAllComplete' : function() {
'aphpfile.php'
}
???? lol
a standard form will suffice for the upload just remember to include the mime in the form. then you can use $_FILES[''] to reference the file.
then you can check for the filename provided and see if it exists in the file system using file_exists() check for the file name OR if you don't need to keep the old file, you can use perform the file move and overwrite the old one with the new from the temporary directory
<?PHP
// this assumes that the upload form calls the form file field "myupload"
$name = $_FILES['myupload']['name'];
$type = $_FILES['myupload']['type'];
$size = $_FILES['myupload']['size'];
$tmp = $_FILES['myupload']['tmp_name'];
$error = $_FILES['myupload']['error'];
$savepath = '/yourserverpath/';
$filelocation = $svaepath.$name.".".$type;
// This won't upload if there was an error or if the file exists, hence the check
if (!file_exists($filelocation) && $error == 0) {
// echo "The file $filename exists";
// This will overwrite even if the file exists
move_uploaded_file($tmp, $filelocation);
}
// OR just leave out the "file_exists()" and check for the error,
// an if statement either way
?>
try this piece of code for upload and replace file
if(file_exists($newfilename)){
unlink($newfilename);
}
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $newfilename);

How to attach mysql_insert_id in a file upload?

how do we attach mysql_insert_id() in a file uploads so that each file gets unique name ? I did try the following code but didn't work. please advice. Yhanks
$id = mysql_insert_id();
$dest = trim($uploaddir. $id. basename($_FILES['photo']['name']));
This should be
if(false !== ($id = mysql_insert_id())
{
$dest = sprintf("%s%d_%s",$uploaddir,$id,trim(basename($_FILES['photo']['name']));
if(!file_exists($dest))
{
//move_uploaded_file
}else
{
//You cant program :(
}
}else
{
//DB Error.
}
You should write your code so you add the file to the directory before you add to database.
Get the data from $_FILES
Sanitize the data and validate the file Size,Ext,Headers,Name
Make sure the file does not already exists
Generate a UniqueID and create a hash from a static string, Example 1
Store the file on the server and verify its move ok
Add meta data to the database along with the unique ID and file location
Bobs your uncle.
Example 1:
define('FILE_NAME_SALT','MySecret$alt');
$uid = md5(rand(0,100) . $uid . FILE_NAME_SALT . $FileName);
Store file like HASH.ext
This is a problem that you can take some steps to solve yourself before asking. For starters, print out $id. Is it a valid Id? Or is it FALSE (it might be). Then echo out $uploaddir, $_FILES['photo']['name'], and basename($_FILES['photo']['name']). Finally, echo out $dest. I'd be rather surprised if you don't catch the mistake by doing these simple debugging exercises.
You could use a hashing function to do this. For example, md5 or sha1 are good choices for unique filenames. You could use a filename that the md5() function returns given the file's initial name.

Categories