move_uploaded_file() fails to open stream due to invalid argument - PHP - php

I have this code to move my uploaded file to a specific directory:
if (isset($_FILES["image"]["name"])){
if (!is_dir('pf/' . $uid)) {
mkdir('pf/' . $uid);
$large_image_location = "pf/" . $uid;
}else {
$large_image_location = "pf/" . $uid;
}
chmod ($large_image_location, 0777);
move_uploaded_file("$userfile_tmp", "$large_image_location/$userfile_tmp");
}
However that gives the following error:
( ! ) Warning: move_uploaded_file(pf/BfyhieniKJGGqTNm/C:\wamp\tmp\phpF08A.tmp) [function.move-uploaded-file]: failed to open stream: Invalid argument in C:\wamp\www\mingle\upload_dp.php on line 26
Any help on how to sort this out would be greatly appreciated!

This is 90% of your woes:
move_uploaded_file("$userfile_tmp", "$large_image_location/$userfile_tmp");
You using the moved to path at the beginning of the upload path. Try:
move_uploaded_file("$userfile_tmp", "$large_image_location/".$_FILES['image']['name']);
That should work better.

The error itself is pretty clear, pf/BfyhieniKJGGqTNm/C:\wamp\tmp\phpF08A.tmp is not a valid filename.
Don't change the contents of $_FILES[n]['tmp_name'] (or $userfile_tmp for that matter), since it will always contain the full path to the uploaded file.

Related

Error when running my php script

I have these errors when running my script.
failed to open dir: No such file or directory in /Applications/MAMP/htdocs/sites-store/word/word2.php on line 6
Warning: scandir(): (errno 2): No such file or directory in /Applications/MAMP/htdocs/sites-store/word/word2.php on line 6
Warning: array_diff(): Argument #1 is not an array in /Applications/MAMP/htdocs/sites-store/word/word2.php on line 6
Warning: Invalid argument supplied for foreach() in /Applications/MAMP/htdocs/sites-store/word/word2.php on line 7
Well this is my code below, I don't understand why it failed to open my dir when it's being declared below? Can someone help me with this.
Code of my word2.php
<?php
$numargs = count($argv);
if ($numargs > 1) {
$folder = $argv[1];
echo "Folder is: " . $folder . "\n";
$files = array_diff(scandir($folder), array('.', '..')); //line 6
foreach ($files as $file) { //line 7
$filename = str_replace("í»", "", $filename);
}
} else {
echo "You need to pass the folder absolute path";
exit();
}
Code for running my script using this command ./run.bat this is the filename with a code below.
php word2.php "/Applications/MAMP/htdocs/sites-store/word/images"
PAUSE
Try changing your .bat file to
php word2.php -- "/Applications/MAMP/htdocs/sites-store/word/images"
PAUSE
and you should also do var_dump($argv), to see how your script gets its parameter.
failed to open dir: No such file or directory in
/Applications/MAMP/htdocs/sites-store/word/word2.php on line 6
Make sure that your file in that directory.
Check the filename again means is there any spelling mistakes or duplicated.
Make sure if it's read that directory or not

PHP open txt file and echo its contents

The path of my .txt file is C:\Users\George\Desktop\test.txt
And I use:
$path = "C:\\Users\\George\\Desktop\\test.txt";
$fileContent = file_get_contents($path);
echo $fileContent;
But I get file_get_contents(C:\Users\George\Desktop\test.txt) [function.file-get-contents]: failed to open stream. But why?
Use this code:
$path = "C:/Users/George/Desktop/test.txt";
$fileContent = file_get_contents($path);
echo $fileContent;
as the error mentions, that path exists...
Wrong assertion, PHP is just telling you there was an error opening that path, it doesn't mean it exists, also, the error message should mention the reason for the error, i.e.: not found, permission denied, etc...
Answer:
Your code syntax is correct. The error is one of the following 3:
1 - The file doesn't exist.
2 - The path is wrong.
3 - Php doesn't have permission to access that file.
Maybe if YOU do not have the right to read this file as PHP, the system have it, try exec or system :
$path = 'C:\\Users\\George\\Desktop\\test.txt';
function getFile_exec($path)
{
if(file_exists($path))
{
return exec("cat $path");
}
else
{
return false;
}
}
function getFile_syst($path)
{
if(file_exists($path))
{
return system("cat $path");
}
else
{
return false;
}
}
var_dump(getFile_exec($path));
var_dump(getFile_syst($path));
But as you have this error : Warning: file_get_contents(C:/Users/George/Desktop/test.txt) [function.file-get-contents]: failed to open stream: No such file or directory in /home/a2133027/public_html/index.php on line 5 and like Pedro Lobito said, you must be on linux, so, the good way to access your files on desktop may be : ~/Desktop/test.txt or ~/test.txt if it's directly in your user files ... Are you sure, you are under windows ?

move_uploaded_file / No such file or directory in PHP

i have a problem with the move_uploaded_file function this is the problem:
Warning: move_uploaded_file(/imagenes/Icon.png) [function.move-uploaded-file]: failed to >open stream: No such file or directory in /home/decc98/public_html/php/insert.php on line 6
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpIBBh5U' >to '/imagenes/Icon.png' in /home/decc98/public_html/php/insert.php on line 6
Insercion exitosa
Other stuff, i speak spanish so part of my code is in spanish... Anyways, my code is:
<?php
include "conexion.php";
$ruta = "/imagenes";
$archivo = $_FILES['imagen']['tmp_name'];
$nombreArchivo = $_FILES['imagen']['name'];
move_uploaded_file($archivo,$ruta."/".$nombreArchivo);
$ruta=$ruta."/".$nombreArchivo;
$texto = $_POST['descripcion'];
$id = rand(1,200);
$insertar = mysql_query("INSERT INTO tablaUno VALUES('".$id."','".$ruta."','".$texto."')");
if ($insertar) {
echo "Inserción exitosa";
}else{
echo "Fallo en la inserción";
}
?>
Please if anyone can help me I would appreciate it!
You need to use a relative path instead of an absolute path.
For example:
$ruta = "imagenes";
leaving out the / at the beginning of your folder name, if you're using your script from the root.
Or, something like:
$ruta = "../imagenes";
depending on the script execution's location.
Note: Using / is mostly used for an (server) absolute path, something to the affect of:
/var/user/user123/public_html/imagenes

can someone help me fix my code?

I have this code I been working on but I'm having a hard time for it to work. I did one but it only works in php 5.3 and I realized my host only supports php 5.0! do I was trying to see if I could get it to work on my sever correctly, I'm just lost and tired lol
Ol, sorry stackoverflow is a new thing for me. Not sure how to think of it. As a forum or a place to post a question... hmmm, I'm sorry for being rude with my method of asking.
I was wondering i you could give me some guidance on how to properly insert directory structures with how i written this code. I wasn't sure how to tell the PHP where to upload my files and whatnot, I got some help from a friend who helped me sort out some of my bugs, but I'm still lost with dealing with the mkdir and link, unlink functions. Is this how I am suppose to refer to my diretories?
I know php 5.3 uses the _ DIR _ and php 5.0 use dirname(_ _ FILE_ _), I have tried both and I get the same errors. My files are set to 0777 for testing purposes. What could be the problem with it now wanting to write and move my uploaded file?
} elseif ( (file_exists("\\uploads\\{$username}\\images\\banner\\{$filename}")) || (file_exists("\\uploads\\{$username}\\images\\banner\\thumbs\\{$filename}")) ) {
$errors['img_fileexists'] = true;
}
if (! empty($errors)) {
unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
}
// Create thumbnail
if (empty($errors)) {
// Make directory if it doesn't exist
if (!is_dir("\\uploads\\{$username}\\images\\banner\\thumbs\\")) {
// Take directory and break it down into folders
$dir = "uploads\\{$username}\\images\\banner\\thumbs";
$folders = explode("\\", $dir);
// Create directory, adding folders as necessary as we go (ignore mkdir() errors, we'll check existance of full dir in a sec)
$dirTmp = '';
foreach ($folders as $fldr) {
if ($dirTmp != '') { $dirTmp .= "\\"; }
$dirTmp .= $fldr;
mkdir("\\".$dirTmp); //ignoring errors deliberately!
}
// Check again whether it exists
if (!is_dir("\\uploads\\$username\\images\\banner\\thumbs\\")) {
$errors['move_source'] = true;
unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
}
}
if (empty($errors)) {
// Move uploaded file to final destination
if (! move_uploaded_file($_FILES[IMG_FIELD_NAME]['tmp_name'], "/uploads/$username/images/banner/$filename")) {
$errors['move_source'] = true;
unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
} else {
// Create thumbnail in new dir
if (! make_thumb("/uploads/$username/images/banner/$filename", "/uploads/$username/images/banner/thumbs/$filename")) {
$errors['thumb'] = true;
unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
}
}
}
}
// Record in database
if (empty($errors)) {
// Find existing record and delete existing images
$sql = "SELECT `bannerORIGINAL`, `bannerTHUMB` FROM `agent_settings` WHERE (`agent_id`={$user_id}) LIMIT 1";
$result = mysql_query($sql);
if (!$result) {
unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
unlink("/uploads/$username/images/banner/thumbs/$filename"); //cleanup: delete thumbnail file
die("<div><b>Error: Problem occurred with Database Query!</b><br /><br /><b>File:</b> " . __FILE__ . "<br /><b>Line:</b> " . __LINE__ . "<br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "</div>");
}
$numResults = mysql_num_rows($result);
if ($numResults == 1) {
$row = mysql_fetch_assoc($result);
// Delete old files
unlink("/uploads/$username/images/banner/" . $row['bannerORIGINAL']); //delete OLD source file
unlink("/uploads/$username/images/banner/thumbs/" . $row['bannerTHUMB']); //delete OLD thumbnail file
}
// Update/create record with new images
if ($numResults == 1) {
$sql = "INSERT INTO `agent_settings` (`agent_id`, `bannerORIGINAL`, `bannerTHUMB`) VALUES ({$user_id}, '/uploads/$username/images/banner/$filename', '/uploads/$username/images/banner/thumbs/$filename')";
} else {
$sql = "UPDATE `agent_settings` SET `bannerORIGINAL`='/uploads/$username/images/banner/$filename', `bannerTHUMB`='/uploads/$username/images/banner/thumbs/$filename' WHERE (`agent_id`={$user_id})";
}
$result = mysql_query($sql);
if (!$result) {
unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
unlink("/uploads/$username/images/banner/thumbs/$filename"); //cleanup: delete thumbnail file
die("<div><b>Error: Problem occurred with Database Query!</b><br /><br /><b>File:</b> " . __FILE__ . "<br /><b>Line:</b> " . __LINE__ . "<br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "</div>");
}
}
// Print success message and how the thumbnail image created
if (empty($errors)) {
echo "<p>Thumbnail created Successfully!</p>\n";
echo "<img src=\"/uploads/$username/images/banner/thumbs/$filename\" alt=\"New image thumbnail\" />\n";
echo "<br />\n";
}
}
I get the following errors:
Warning: move_uploaded_file(./uploads/saiyanz2k/images/banner/azumanga-wall.jpg) [function.move-uploaded-file]: failed to open stream: Permission denied in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php on line 112
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/services/webdata/phpupload/phpVoIEQj' to './uploads/saiyanz2k/images/banner/azumanga-wall.jpg' in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php on line 112
One way is to check from within your code whether a certain command/function is available for use. You can use the function_exists function for that eg:
if (function_exists('date_default_timezone_set'))
{
date_default_timezone_set("GMT");
}
else
{
echo 'date_default_timezone_set is not supported....';
}
Ahh! I'm sorry, didn't mean to vent my frustration on you guys. But I have been at this for hours now it seems.
Like i mentioned this code works but since my server is picky I can't user the 5.3 syntax I coded. This is my attempt to make it work on the 5.0 php my server has.
In particular I think there is something wrong with the mkdir() and the unlink() functions.
if you go to www.helixagent.com log in with test/test then in the url go to /upload2.php then you will see the errors its throwing at me.
well, it works perfect if i use 5.3 and DIR but since I'm on 5.0 i tried a different method
the errors i get are
Warning: move_uploaded_file(./uploads/saiyanz2k/images/banner/azumanga-wall.jpg) [function.move-uploaded-file]: failed to open stream: Permission denied in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php on line 112
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/services/webdata/phpupload/phpVoIEQj' to './uploads/saiyanz2k/images/banner/azumanga-wall.jpg' in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php on line 112
It looks like you don't have access to the folder (or file)
/uploads/$username/images/banner/$filename
which could be because of a basedir restriction on the host (e.g. you may not leve the parent directory /services/webdata/) or just a missing permission in the os.
Try to (temporary) set permission of /uploads/ to 777 or execute the script from console to see if you have a basedir restriction.
Take a closer look at the paths in the error messages:
./uploads/saiyanz2k/images/banner/azumanga-wall.jpg
/services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php
The destination is a relative path, most likely relative to upload2.php's directory. The one relative path I see is the line:
// Take directory and break it down into folders
$dir = "uploads\\{$username}\\images\\banner\\thumbs";
Which should probably be:
// Take directory and break it down into folders
$dir = "\\uploads\\{$username}\\images\\banner\\thumbs";
Actually, it should be
$dir = "/uploads/{$username}/images/banner/thumbs";
since PHP supports using a forward slash as directory separator on all platforms, while the backslash is only supported on MS platforms.

The second argument to copy() function cannot be a directory

Anyone know why this:
<?PHP
$title = trim($_POST['title']);
$description = trim($_POST['description']);
// Array of allowed image file formats
$allowedExtensions = array('jpeg', 'jpg', 'jfif', 'png', 'gif', 'bmp');
foreach ($_FILES as $file) {
if ($file['tmp_name'] > '') {
if (!in_array(end(explode(".",
strtolower($file['name']))),
$allowedExtensions)) {
echo '<div class="error">Invalid file type.</div>';
}
}
}
if (strlen($title) < 3)
echo '<div class="error">Too short title</div>';
else if (strlen($description) > 70)
echo '<div class="error">Too long desccription.</div>';
else {
move_uploaded_file($_FILES['userfile']['tmp_name'], 'c:\wamp\www\uploads\images/');
}
Gives:
Warning: move_uploaded_file() [function.move-uploaded-file]: The second argument to copy() function cannot be a directory in C:\wamp\www\upload.php on line 41
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\wamp\tmp\php1AB.tmp' to 'c:\wamp\www\uploads\images/' in C:\wamp\www\upload.php on line 41
It's because you're moving a file and it thinks you're trying to rename that file to the second parameter (in this case a directory).
it should be:
move_uploaded_file($_FILES['userfile']['tmp_name'], 'c:/wamp/www/uploads/images/'.$file['name']);
You are specifying to move a file to a directory; neither PHP's move_uploaded_file nor its copy is as smart as a shell's copy -- you have to specify a filename, not a directory, for the destination.
So, one simple solution would be to take the basename of the source file and append that to the destination directory.
It sounds like the second argument to move_uploaded_file should be a full file name instead of just the directory name. Also, probably only a style issue, but you should use consistent slashes in 'c:\wamp\www\uploads\images/'
Because PHP is not a shell. You're trying to copy the file into the c:\wamp\www\uploads\images directory, but PHP doesn't know you mean that when you execute (within the move_uploaded_file function):
copy($_FILES['userfile']['tmp_name'], 'c:\wamp\www\uploads\images/');
This command tells it to rename the file to c:\wamp\www\uploads\images/, which it can't do because that's the name of an existing directory.
Instead, do this:
move_uploaded_file($_FILES['userfile']['tmp_name'],
'c:\wamp\www\uploads\images/' . basename($_FILES['userfile']['tmp_name']));
if you want just copy the file in two Dir different, try this :
if (move_uploaded_file($_FILES['photo']['tmp_name'], $target.$pic1))
{
copy("C:/Program Files (x86)/EasyPHP-5.3.9/www/.../images/".$pic1, "C:/Program Files (x86)/EasyPHP-5.3.9/www/.../images/thumbs/".$pic1)
}
You should write the complete path "C:/..."
Try adding the extension to the name file.
$filename = $_FILES['userfile']['tmp_name'].".jpg";
It will be like below in phalcon 3.42
if ($this->request->hasFiles() == true) {
// Print the real file names and sizes
foreach ($this->request->getUploadedFiles() as $file) {
//Print file details
echo $file->getName(), " ", $file->getSize(), "\n";
//Move the file into the application
$file->moveTo($this->config->application->uploadsDir.$file->getName());
}
}
FIRSTLY FIND YOUR CURRENT DIRECTORY echo getcwd(); IF YOU FIND THE CURRENT DIRECTORY SO MOVE THEM ANOTHER DIRECTORY
FOR EXAMPLE = echo getcwd(); these output is "your live directory name" like that -> /opt/lampp/htdocs/product and create new directory anywhere but your current directory help to go another directory ***
plz read carefully very thinking answer

Categories