Trouble passing a variable from one function to another in PHP? - php

I have two functions and I am stumped on how to pass a variable between them. Here is what I have so far.
function copy_photo ($image_url, $image_description){
$rand_string = rand(0001, 9999);//create simple random string
$image_type = substr(strrchr($image_url,'.'),1);//get image type
$local_directory = "./images/";//folder to put photo
$local_image_name = $local_directory . $image_description . "-" . $rand_string . $image_type;//full directory and new image name to place photo
copy($image_url, $local_image_name);// I want the function to first copy the image here
return $local_image_name;// <---this is the variable I want to pass on
}
function store_data ($local_image_name){
//simple PDO statement to insert newly created local image url into database
}
copy_photo ($image_url, $image_description);//copy photos to folder
store_data ($image_description);//store $image_description in database
What I would like to happen is for the copy_photo function to first copy the photo and then return $local_image_name and pass it to the store_data function for storage in a database. I keep getting an error that $image_description is null when store_data tries to store it into the database. How can I successfully pass $local_image_name from one function to the next?
Thanks!!

You assign the return value of the function to a variable, then pass that variable to the next function.
$image_name=copy_photo ($image_url, $image_description);//copy photos to folder
store_data ($image_name);//store $image_description in database

Related

laravel | How to replace a field in form's request?

I am using laravel 5.4 and I'm trying to replace the imagePath field in my request (renaming the uploaded image).
explanation:
when the form is submitted the request field(request->imagePath) contains the temporary location of the uploaded image, I am moving that tmp image to a dir while changing its name ($name). so now as the request->imagePath still has old tmp image location I want to change request->imagePath value to have the new location and then create the user.
Like so
if($request->hasFile('imagePath'))
{
$file = Input::file('imagePath');
$name = $request->name. '-'.$request->mobile_no.'.'.$file->getClientOriginalExtension();
echo $name."<br>";
//tried this didn't work
//$request->imagePath = $name;
$file->move(public_path().'/images/collectors', $name);
$request->merge(array('imagePath' => $name));
echo $request->imagePath."<br>";
}
But Its not working, Here is the output
mahela-7829899075.jpg
C:\xampp\tmp\php286A.tmp
Please Help
I believe merge() is the correct method, it will merge the provided array with the existing array in the ParameterBag.
However, you're accessing the input variables incorrectly. Try using $request->input('PARAMETER_NAME') instead...
Therefore, your code should look like this:
if ($request->hasFile('imagePath')) {
$file = Input::file('imagePath');
$name = "{$request->input('name')}-{$request->input('mobile_no')}.{$file->getClientOriginalExtension()}";
$file->move(public_path('/images/collectors'), $name);
$request->merge(['imagePath' => $name]);
echo $request->input('imagePath')."<br>";
}
Note: You can also pass your path into public_path() and it will concatenate it for you.
References
Retrieving Input:
https://laravel.com/docs/5.4/requests#retrieving-input
$request->merge():
https://github.com/laravel/framework/blob/5.4/src/Illuminate/Http/Request.php#L269
public_path: https://github.com/laravel/framework/blob/5.4/src/Illuminate/Foundation/helpers.php#L635

Using PHP how can you tell if the image already exists on your server regardless of name?

I have seen several websites where if you upload an image and an identical image already exists on there servers they will reject the submission. Using PNGs is there an easy way to check one image against a massive folder of images?
http://www.imagemagick.org/discourse-server/viewtopic.php?t=12618
I did find this with imagemagick, but I am looking for one vs many and not one to one a million
You can transform the file content into a sha1. That will give you a way to identify two pictures strictly identical.
see http://php.net/manual/fr/function.sha1-file.php
Then after you save it into a NFS, or use some kind of database to test if the hash already exists.
Details of the images are probably maintained in a database; while the images are stored in the filesystem. And that database probably has a hash column which is used to store an md5 hash of the image file itself, calculated when the image is first uploaded. When a new image is uploaded, it calculates the hash for that image, and then checks to see if any other image detail in the database has a matching hash. If not, it stores the newly uploaded image with that hash; otherwise it can respond with details of the previous upload. If the hash column is indexed in the table, then this check is pretty quick.
If I understood your question correctly. You want to find out if a specific image exists in a Directory with so many images, right? If so, take a look at the solution:
<?php
// CREATE A FUNCTION WHICH RETURNS AN ARRAY OF ALL IMAGES IN A SPECIFIC FOLDER
function getAllImagesInFolder($dir_full_path){
$returnable = array();
$files_in_dir = scandir($dir_full_path);
$reg_fx = '#(\.png|\.jpg|\.bmp|\.gif|\.jpeg)#';
foreach($files_in_dir as $key=>$val){
$temp_file_or_dir = $dir_full_path . DIRECTORY_SEPARATOR . $val;
if(is_file($temp_file_or_dir) && preg_match($reg_fx, $val) ){
$regx_dot_wateva = '/\.{2,4}$/';
$regx_dot = '/\./';
$regx_array = array($regx_dot_wateva, $regx_dot);
$replace_array = array("", "_");
$return_val = preg_replace($regx_array, $replace_array, $val);
$returnable[$return_val] = $temp_file_or_dir ;
}else if(is_dir($temp_file_or_dir) && !preg_match('/^\..*/', $val) ){
getFilesInFolder($temp_file_or_dir);
}
}
return $returnable;
}
// CREATE ANOTHER FUNCTION TO CHECK IF THE SPECIFIED IMAGE EXISTS IN THE GIVEN DIRECTORY.
// THE FIRST PARAMETER SHOULD BE THE RESULT OF CALLING THE PREVIOUS FUNCTION: getAllImagesInFolder(...)
// THE SECOND PARAMETER IS THE IMAGE YOU WANT TO SEARCH WHETHER IT EXISTS IN THE SAID FOLDER OR NOT
function imageExistsInFolder($arrImagesInFolder, $searchedImage){
if(!is_array($arrImagesInFolder) && count($arrImagesInFolder) < 1){
return false;
}
foreach($arrImagesInFolder as $strKey=>$imgPath){
if(stristr($imgPath, $searchedImage)){
return true;
}
}
return false;
}
// NOW GET ALL THE IMAGES IN A SPECIFIED FOLDER AND ASSIGN THE RESULTING ARRAY TO A VARIABLE: $imgFiles
$imgFolder = "/path/to/directory/where/there/are/images";
$arrImgFiles = getAllImagesInFolder($imgFolder);
$searchedImage = "sandwich.jpg"; //<== OR EVEN WITHOUT THE EXTENSION, JUST "sandwich"
// ASSUMING THE SPECIFIC IMAGE YOU WANT TO MATCH IS CALLED sandwich.jpg
// YOU CAN USE THE imageExistsInFolder(...) FUNCTION TO RETURN A BOOLEAN FLAG OF true OR false
// DEPENDING ON IF IT DOES OR NOT.
var_dump($arrImgFiles);
var_dump( imageExistsInFolder($arrImgFiles, $searchedImage) );

Grabbing data from SQL column and splitting it to populate function

If I grab data from a column in my database called image_store such as:
/web/images/data/firstImage.png
/web/images/data/secondImage.png
/web/images/data/thirdImage.png
And I want to populate a setImage function which takes the string after /data/ to set as the fileName and the string before /firstImage.png as the directory e.g:
$this->setImage('firstImage.png', '/web/images/data/')
Is there a way I can grab the needed information from the string I get back from the database?
Yes, simply use explode/implode functions and array_pop() to take image name itself:
<?php
$sqlArr = array('/web/images/data/firstImage.png', '/web/images/data/secondImage.png', '/web/images/data/thirdImage.png');
foreach($sqlArr as $fullPath){
$tmp = explode('/', $fullPath);
$imgName = array_pop($tmp);
$imgPath = implode('/', $tmp).'/';
$this->setImage($imgName, $imgPath);
}
?>
This will works with any depth of url paths.

mysql - php - remove first part of url upon INSERT

Im doing an image gallery CMS using Mysql database and PHP. Im a newbie.
Im having a path problem.
here is my file structure:
this php doc - root/php/upload_portrait.php.
My images are stored here - root/images/portrait_gallery/
So I added the ../ to save the images in root/images/portrait_gallery/
that works fine.
but in the db the url is stored with the ../ and that path is incorrect since they are being called from the root index file. So no images show up.
HOW can I remove the ../ upon INSERT INTO in the database??
I have tried with replace and update but cant figure out how.
Here Is my code
$portrait_url= $_FILES['upload'];
// 2. connect to database:
include 'connect.php';
// 4. handle moving image from temp location to images folder (using the function billedupload)
$billedurl = billedupload($portrait_url);
if($billedurl == false){
die("Something is wrong");
}
// 5. Insert imageupload in database:
$query = "INSERT INTO portrait (portrait_id, portrait_url) VALUES ('$portrait_id', '$billedurl')";
$result = mysqli_query($dblink, $query) or die( "Forespørgsel 2 kunne ikke udføres: " . mysqli_error($dblink) );
// 6. close connection
mysqli_close($dblink);
function billedupload($filearray){
if($filearray['type']=='image/jpeg' or $filearray['type']=='image/png'){
$tmp_navn = $filearray['tmp_name'];
$filnavn = $filearray['name'];
$url = '../images/portrait_gallery/' . time() . $filnavn;
move_uploaded_file($tmp_navn, $url);
return $url;
}
else{
return false;
}
}
I believe you have 2 choices.
Alter the $url line of billed upload() and remove the ../ there, since you know you won't need it when you go to read it.
Alter your function that reads from the database and remove the ../ there.
str_replace() is probably the function you need, as mentioned by previous poster.
If all you need to to remove '/..' -- then,
str_replace is a function in PHP that allows you to remove/change parts of strings on the fly, so, in your code,
replace
$billedurl = billedupload($portrait_url);
with
$billedurl = str_replace('/..','',billedupload($portrait_url));

i need to get the name of a variable from a file

As the title said i need a way to set the variable name depending of what the name of the picture is (i got over 100 different pictures)
Since i got custom classes in another php file for each picture (like tags) like for example:
$picture1 = "hillside sunset";
$picture2 = "beach cyprus";
and so on, so i need to fetch each variable for each picture
Heres the current loop where the div class is going to be each pictures name ($PICTURENAME is just to define where this code goes and is irelevant codewise):
<?php
foreach (glob("img/*.jpg") as $filename)
{
$path = $filename;
$file = basename($path);
$file = basename($path, ".jpg");
echo '<div class="'.$PICTURENAME.'" id="'.$file.'"><img src="'.$filename.'"> '.$file.' </div>';
}
?>
Don't use 100+ variables. Using a database would make far more sense, but if you don't want to get into learning that (you should, though), using a data structure would still make far more sense.
You could create one array (and use it as a map), and have the filename as the key, and the value would be the tags.
In PHP, you can address a variable using another variable:
$name = "foo";
${$name} = "bar";
echo $foo; // prints "bar"
echo ${$name}; // the same as above
However, as Kitsune already recommended, you are better off using something else, e.g., an array.

Categories