so I am struggling with this bit of code for a project that I am working on. I do not understand why I am getting an array to string conversion error for my use of the Move_uploaded_file function below, since I implemented a foreach loop to work only with each individual element in the array. Also note that the issue- according to php's error handling- is specifically with the move_uploaded_file function, not with the other methods that get called.
Here's the relevant code. (Thanks all for the help).
public function relocate () {
foreach ($this->getFilename() as $name) {
$validate = $this->validatePhoto($name);
$size = $this->getSize($name);
if ($validate && $size) {
if (move_uploaded_file($name, $this->filepath . $this->getFilename())) {
echo "<p> upload complete </p>";
//rename file, redirect header, etc.
} //end if move_uploaded_file
else {
echo "<p> something's up. </p>";
}//end else
}//end if validate && size
}//end foreach
}//end relocate method
you should replace $this->getFilename() with $name, $this->getFilename() returns an array if I got it right...
public function relocate () {
foreach ($this->getFilename() as $name) {
$validate = $this->validatePhoto($name);
$size = $this->getSize($name);
if ($validate && $size) {
if (move_uploaded_file($name, $this->filepath . $name)) {
echo "<p> upload complete </p>";
//rename file, redirect header, etc.
} //end if move_uploaded_file
else {
echo "<p> something's up. </p>";
}//end else
}//end if validate && size
}//end foreach
}//end relocate method
It should be
public function relocate () {
foreach ($this->getFilename() as $name) {
$validate = $this->validatePhoto($name);
$size = $this->getSize($name);
if ($validate && $size) {
if (move_uploaded_file($name, $this->filepath . $name)) {
echo "<p> upload complete </p>";
//rename file, redirect header, etc.
} //end if move_uploaded_file
else {
echo "<p> something's up. </p>";
}//end else
}//end if validate && size
}//end foreach
}//end relocate method
You're passing in $this->getFileName() to move_uploaded_file(), when you should be passing in $name, as you're already iterating over the array that $this->getFileName() is returning
Related
I have form where I have three inputs for files. With code below, I try to move files from TMP localisation to ./uploads with some random hash and name of file.
I have issue with foreach because it is stopping, after first iteration and saving file to uploads directory. I do not know why it is not happening for other two elements in table. Whole function below, it is a little mess, but I hope it is understandable.
function saveFile(){
global $patchFile;
$fileArray = [ $_FILES['file_one']['name'], $_FILES['file_two']['name'], $_FILES['file_three']['name'] ];
$tmpArray = [ $_FILES['file_one']['tmp_name'], $_FILES['file_two']['tmp_name'], $_FILES['file_three']['tmp_name'] ];
$multiArray =
[
[$_FILES['file_one']['name'], $_FILES['file_one']['tmp_name']],
[$_FILES['file_two']['name'], $_FILES['file_two']['tmp_name']],
[$_FILES['file_three']['name'], $_FILES['file_three']['tmp_name']]
];
foreach ($multiArray as $key)
{
echo "<br />Key: ".$key[0]."\n";
echo "Key_tmp: ".$key[1]."\n";
$randomString = generateRandomString();
$patchFile = './uploads/'.$randomString.$key[0];
echo "<br />Check patchFile: $patchFile";
if(is_uploaded_file($key[1]))
{
echo "<br />Begin uploading to directory...<br />";
if(!move_uploaded_file($key[1], $patchFile))
{
echo 'Problem: Nie udało się skopiować pliku do katalogu.';
return false;
}
else {
echo "File was saved in uploads directory";
return true;
}
}
else
{
echo "Uploading to directory... FAILED!";
}
}
}
When you return something from a loop, the loop is always broken.
As per PHP manual:
If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call.
Trying to execute file upload through external function. It gives "Missing argument..." error but also returns the result correctly. What might be wrong?
This is form page:
<?php include '--formprocess.php'; ?>
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$upload = $_FILES['upload'];
if(formprocess($upload)) {
echo formprocess();
} else {
echo 'ERROR!';
}
}
?>
and process file:
<?php
function formprocess($upload) {
$name = $_FILES['upload']['tmp_name'];
return $name;
}
echo formprocess();
^---your missing argument
formprocess takes one argument, the first time you call it you passed an argument, the second time you did not.
$value = formprocess($upload);
if($value) {
echo $value;
}
i create this function for search resume file from directory, if resume is available then function return full path, problem is function return nothing if i use "return", if i use "echo" then it will print right path
function search_resume($resume,$dir="uploads/resumes")
{
$root = scandir($dir);
foreach($root as $value)
{
/* echo $value."<br/>"; */
if($value === '.' || $value === '..') {continue;}
if(is_file("$dir/$value"))
{
if($value==$resume)
{
$path="$dir/$value";
return $path;
}
}
else
{
search_resume($resume,"$dir/$value");
}
}
}
A very typical, basic problem with recursive functions: you need to return recursive calls as well, they're not going to return themselves.
...
else {
$path = search_resume($resume,"$dir/$value");
if ($path) {
return $path;
}
}
I am working on a prototype of an online storage with PHP and I got this problem. I call the delete_file() function from the client, the function checks if the item to be deleted is a file or a directory and deletes it accordingly. If the item is a directory then it will call another function that will delete all its' contents and the directory itself.
function delete_file (){
global $directory;
$rec_data = trim($_POST['selected']);
$selected_items = explode(";", $rec_data);
if (count($selected_items) < 1){
echo "0";
}
else {
foreach ($selected_items as $item){
if (is_dir("{$directory}/{$item}")){
recursiveRemoveDirectory("{$directory}/{$item}");
}
else {
unlink("{$directory}/{$item}");
}
}
echo "1";
}
}
function recursiveRemoveDirectory($rm_directory){
foreach(scandir($rm_directory) as $file){
if($file != "." && $file != ".."){
if(is_dir($file)) {
recursiveRemoveDirectory($file);
}
else {
unlink($file);
}
}
}
rmdir($rm_directory);
}
Problem: It works but, this also deletes the parent directory .e.g data > username > dir, if I want to delete dir, it will also delete username. I've tried with various other methods with no success.
function recursiveRemoveDirectory($rm_directory){
foreach(scandir($rm_directory) as $file){
if($file != "." && $file != ".."){
if(is_dir($file)) { <--- error starts here!
recursiveRemoveDirectory($file);
}
else {
unlink($file); <--- error ends here!
}
}
}
rmdir($rm_directory);
}
Replace the marked lines with
if(is_dir("$rm_directory/$file")) {
recursiveRemoveDirectory("$rm_directory/$file");
else {
unlink("$rm_directory/$file");
}
You got that right in your delete_file function, but missed it in the recursive one.
Try this:
function recursiveRemoveDirectory($dir) {
foreach(scandir($dir) as $file) {
if ('.' === $file || '..' === $file) continue;
if (is_dir("$dir/$file")) recursiveRemoveDirectory("$dir/$file");
else unlink("$dir/$file");
}
rmdir($dir);
}
I tried both answers, they did solve a problem I had with the code but it did not solve the issue I was having in which the parent directory was being deleted along with the selected items.
After looking and changing the code for some time I finally realized that the problem wasn't in the recursiveDeleteDirectory() function but in the delete_file() function itself.
The $selected_itemsvariable gets a concatenated string of the names of the items to be selected, it trims any unnecessary whitespaces and makes an array from the string. The problem was that somehow $selected_items got an additional empty entry which meant that I was then executing recursiveRemoveDirectory("{$directory}/"); instead of recursiveRemoveDirectory("{$directory}/{$item}");.
I solved all this by adding:
if (empty($item)){
continue;
}
Here is how the code looks like:
function delete_file (){
global $directory;
$selected_items = explode(";", trim($_POST['selected']));
if (count($selected_items) < 1){
echo "0";
}
else {
foreach ($selected_items as $item){
if (empty($item)){
continue;
}
if (is_dir("{$directory}/{$item}")){
recursiveRemoveDirectory("{$directory}/{$item}");
}
else if (is_file("{$directory}/{$item}")){
unlink("{$directory}/{$item}");
}
}
echo "1";
}
}
function recursiveRemoveDirectory($rm_directory){
$files = file_explore();
if(count($files) > 0){
foreach($files as $file){
if(is_dir("{$rm_directory}/{$file}")) {
recursiveRemoveDirectory("{$rm_directory}/{$file}");
}
else if (is_file("{$rm_directory}/{$file}")) {
unlink("{$rm_directory}/{$file}");
}
}
}
rmdir($rm_directory);
Now my problem, which isn't really a stack overflow problem is the naming conversions of php functions, I never used underscore on function names but recently that have changed and I feel that's a bad habit, if someone wants to comment about that, you are free to do so, I really want to know how things must be done in php.
Cheers!
I have foreach loop that looks like this:
foreach($wdata->query->pages->$wpageid->images as $iimages)
{
$name = $iimages->title;
$filename = str_replace(" ", "_",$name);
$filename = str_replace("File:","",$filename);
$digest = md5($filename);
$folder = $digest[0].'/'.$digest[0].$digest[1].'/'. $filename;
$url = 'http://upload.wikimedia.org/wikipedia/commons/'.$folder;
echo "<img style='height:100px;' src='$url'>";
}
It displayes images from a returned json array ($wdata)
However, some images have been moved, or don't exist anymore, and I get cracked images, does anyone know how to check if an image is real, exists and can be viewed before it is echoed
Use the file_get_cotents() function to check if it's there
if (file_get_contents("http://....") !== false) { //display image }
It is a remote file and file_exists() does not work for this circumstance. So I suggest you to use getimagesize() function which returns an array if the image exists.
<?php
$imageSize=getimagesize($url);
if(!is_array($imageSize))
{
echo "<img style='height:100px;' src='$url'>";
}
else
{
echo "no image";
}
?>
Another solution:
if (true === file_get_contents($url,0,null,0,1))
{
echo "<img style='height:100px;' src='$url'>";
}
This is faster because it tries to read only one byte of the file if exists.
Use a function as below and pass your url for test
if (image_exist($url)) {
echo "<img ...";
}
function image_exist($url) {
$file_headers = #get_headers($url);
if($file_headers[0] == 'HTTP/1.1 200 Found') {
return true;
}
return false;
}