I am trying to open a file but for some reason I cannot even though the file is there and even has 777 permission. The code is the following:
$fileatt = "/opt/lampp/htdocs/a.pdf";
echo "File size is ".filesize($fileatt)."<br>";
if (file_exists($fileatt)) {
echo "The file ".$fileatt." exist <br>";
$file = fopen($fileatt, ‘rb’);
if ($file == false) {
echo "Could not open the file !";
}
} else {
echo "The file ".$fileatt." does NOT exist <br>";
}
The result is:
File size is 1252121
The file /opt/lampp/htdocs/a.pdf exist
Could not open the file !
Why can't I open the file ? Where is my mistake ?
Thanks
Where is my mistake ?
You don't have error reporting properly set. there are 2 things to remember.
error reporting level. set by error_reporting ini directive or error_reporting() function. should ALWAYS be at E_ALL or higher.
error messages destination.
on a development server it should be display
on a live server it should be a log file
Thus, for a quick solution, put these 2 lines at the top of your script
error_reporting(E_ALL);
ini_set('display_errors',1);
but later set up these settings as a permanent ones for the whole site (according to the server state)
once you done it, you will have an answer to your question.
Note that you will have not a mere guess from the fellow stackoverflowers, but exact explanation of the matter from the system itself.
Related
I made a php upload script that would be executed after a form with the upload was submitted.
$game_tmp = $game_file['tmp_name'];
$game_name = $game_file['name'];
$game_dest = "/games/" . game_name;
if (move_uploaded_file($game_tmp, $game_dest)) {
echo "<b>SUCCESS:</b><br />";
}
else {
echo "Error.";
}
It always output Error, so I checked my php.ini file and phpinfo(). my php.ini shows upload_tmp_dir with no value and so does the value in phpinfo(). I changed the calue of the directory to /upload, and changed the open_basedir to have a value of upload_tmp_dir. Yet, when I look into phpinfo(), it still shows upload_tmp_dir with a local and master value of no value. I believe this is the problem that is stopping my upload script from working. I created a /upload folder also and gave its permission value 777. Yet, this problem persists. I am not sure what is causing this problem.
Try this, you must use the $_FILE super global:
if($_FILES["game_file"]["error"] == UPLOAD_ERR_OK) {
$game_tmp = $_FILES['game_file']['tmp_name'];
$game_name = $_FILES['game_file']['name'];
$game_dest = "/games/" . $game_name;
if (move_uploaded_file($game_tmp, $game_dest)) {
echo "<b>SUCCESS:</b><br />";
}
else {
echo "Error.";
}
}
if upload_tmp_dir is not specified, php will use system's default tmp directory. You can use sys_get_temp_dir() function to identify temporary directory being used by PHP.
Have you tried printing $game_file var?
If not, try print_r($game_file) or var_dump($game_file) to view if its actually being set. You can also print $_FILE to see error message (http://php.net/manual/en/features.file-upload.errors.php)
move_uploaded_file could fail for many reason. Also, confirm if the destination directory exists and is writable.
Typos:
$game_dest = "/games/" . game_name;
^---you forgot a $ here
That's an undefined constant, so PHP will "politely" treat it as an unquoted string, and you're generating "/games/game_name" instead.
never EVER do devel/debug work in PHP with display_errors and error_reporting turned off. It's the equivalent of going "lalalalala can't hear you" with your fingers stuffed in your ears.
And you're also simply assuming your upload succeeded. There's a ['error'] parameter in $_FILES for a reason. Check it FIRST, before you start fiddling with a file that may not even be there.
I have some code that uploads a file, its the exact same code i had working on another server but its not working on this new server
// Move the file into the new folder
move_uploaded_file($_FILES["file"]["tmp_name"],'./img/myfolder/1/'. $_FILES["file"]["name"]);
I know i can use:
if(move_uploaded_file($_FILES["file"]["tmp_name"],'./img/myfolder/1/'. $_FILES["file"]["name"])){
echo "success";
} else{
echo "failure";
}
However i have 2 problems, the script is not ran directly from the page, another application which i dont have access to source code to calls that page and sends the image. So i cant do any in page errors i need to log the errors to a file.
The 2nd problem and the main issue is i am not sure how to find out what the error is. Is there an error code i can pull if the else statement is called. I have set it to 777 for the folders and subfolders just for testing purposes to rule out permission issues, ill fix that after getting the problem resolved before pushing to production.
Also i checked the apache server error.log file and it shows nothing
Here i would do something like this.
$debug_file = _DIR_.'/debug.txt';
$source = $_FILES["file"]["tmp_name"];
$dest = './img/myfolder/1/'. $_FILES["file"]["name"];
if(! #move_uploaded_file($source,$dest) ){
file_put_contents( $debug_file, "ERROR[ ".date('Y-m-d H:i:s')." ] Could not move[ $source ] to[ $dest ]\n", FILE_APPEND);
exit();
}
Then when you have the source and dest paths you can make sure they actually exist in the right places.
-note- the # sign will suppress the normal PHP warning for failing to move the file, but as we are logging it our self, this just prevents it from getting in the way.
Also I put an exit in, I'm assuming its a requirement of this script to have the file to work properly, and that way it's enough just to fail, no need to check for success.
Most likely, the file path is wrong
Also you could even output buffer the php error as well like this,
ob_start();
$moved = move_uploaded_file($source,$dest);
$message = ob_get_clean();
if(!$moved){
file_put_contents( $debug_file, "ERROR[ ".date('Y-m-d H:i:s')." ] Could not move[ $source ] to[ $dest ] PHP message[ $message ]", FILE_APPEND);
exit();
}
Output buffing works wonders on scripts ran in the background,
http://php.net/manual/en/function.ob-get-clean.php
I have a simple PHP script that writes errors to an error log file, and also prints part of the error to the screen.
I first developed it in my "sandbox" project inside Aptana Studio (but really, they're just directories) where it worked beautifully. However, when I copied it over to my "production project" (again, it's really just a different directory on the webserver), it no longer logs messages to the errorlog.log file. All permissions are the same, and in fact I made the script executable (it was not in the other directory), and gave the directory full permissions (chmod 777). The errorlog.log file already exists as an empty file and is writable, just as it was in the sandbox.
Here is the code:
<?php
/* logerrors.inc.php - Prints a "formatted" error message which will be displayed
* within a handler (i.e. the notification bar) on the front end and writes
* the error to a text log.
*/
date_default_timezone_set('America/New_York'); // Required to avoid errors.
define("LOG_LOCATION", "errorlog.log"); // The location of the log file
function writeError($error_string, $technical_info_string = ""){
$tech_log_entry = ""; // We should only log techinical information
// if it's provided
if($technical_info_string != ""){
$tech_log_entry = "\n- Technical Info Provided: ". $technical_info_string;
}
// Writes a log entry with full details.
error_log("[ERROR: ".date('Y-m-d H:i:s') . "]\n- Error Displayed: ". $error_string .
$tech_log_entry ."\n\n",
3, LOG_LOCATION);
echo "error: " . $error_string; // Emits the $error_string as output
exit();
}
?>
Interestingly, the echo command at the bottom of the script is working just fine, so it's obviously not erroring out on the error_log function. It just isn't working.
Any thoughts as to where to look next or what else could be causing this?
i try to upload files into my server also to my database.
However, i cannot upload them.
I can see my two files with below code,
echo $_FILES['file']['name'][0];
echo $_FILES['file']['name'][1];
$fileName = $_FILES['file']['name'][0];
$add = "img01.imgsinemalar.com/images/haber_anasayfa/" . $fileName;
if (move_uploaded_file($_FILES[file_up][tmp_name], $add)) {
NCore::db('NEWS')->insertAsArray(array('CONTENT' => $_POST['TvSpotdesc'], 'ADD_DATE' => $date, 'TITLE' => $_POST['newsTitle'],IMAGE_MAIN => $add))->execute();
echo "Haber başarıyla gönderildi.";
} else {
echo "Failed to upload file Contact Site admin to fix the problem";
}else {
echo $msg;
}
But above code does not upload my files, it goes directly to the else statement, why?
Failed to upload file Contact Site admin to fix the problem
Your code should be outputting two notices and a warning from this line:
if (move_uploaded_file($_FILES[file_up][tmp_name], $add)) {
The two notices would be because you have not quoted file_up and tmp_name and the warning to inform you of the reason move_uploaded_file has failed, as documented. You should check out the logs to see these for yourself (development without seeing any error messages is not fun).
The reason it fails is that you cannot move a file to a remote server -- $add is not a local path.
Rename $_FILES[file_up][tmp_name] to $_FILES['file']['tmp_name']
There is no such variable as file_up as per the code you pasted. Also, files can only be stored on the same server. so gove relative path like /home/www/myapp/images/ instead of server name.
I got this freely available php-script to track download statistics. Simple really, it just count downloads and pass it on to a log file and another script uses that log file to display a top 10 list. So it's exactly what I need so I would really like to make this script work. But it doesn't. Of course. I have limited knowledge in php (but have learned a lot since encountering this script!). According to the author, it has been tested on Apache- and php-versions similar to mine, without problems. So I have been hesitant to actually change any code. I have tried to chmod logfile and/or whole subdirectory to 666 and 777 with no success.
My own poor detective work leads nowhere and I have really tried. So I resort to the one thing I usually never do, to ask for help.
The link should have the form:
<a href=http://www.yoursite.com/downloader/download.php?number=1&file=filename.zip>
download.php follows below:
$number = $_GET['number'];
$file = $_GET['file'];
$logfile = "ROOT DIRECTORY PATH/logfile.txt";
$array[dir_1] = "URL PATH/DOWNLOADFILESFOLDER";
$download = "dir"."_"."$number";
if ($array[$download]) {
$fp = fopen($logfile,'r');
while (!feof($fp))
{
$data[] = chop(fgets($fp,4096));
}
fclose($fp);
$fp = fopen($logfile,"w");
if (flock($fp,LOCK_EX)) {
// list and split each filename and number of downloads
foreach ($data as $lines){
list($downloads,$filename,$realname) = split("\|",$lines);
// check if file already exists and add one more download if it does
if ($filename == $file){
$downloads++;
}
if ($filename <> ""){
fputs($fp,"$downloads|$filename|$realname\r\n");
}
}
flock($fp,LOCK_UN);
}
fclose($fp);
header("Location: $array[$download]/$file");
}
However one part of the script doesn't make sense to me; where does it obtain the filename and the realname so it can be put into the logfile if the file never has been downloaded before? The list() function and the array of the directory boggles my mind a bit. Though it seems logical.
If someone catches some fundamental error or have some tips on how I can continue, it would be highly appreciated.
PS. I am trying to track pdf-files if that helps.
UPDATE! By kind suggestion I ran error reporting and got an error. The faulty scripts had an error in it that I removed. I ran error checking again and only got "Notices" about undefined variables. I changed the error reporting to
error_reporting(E_ALL ^ E_NOTICE);
After that, no errors at all.
You have to change these:
$logfile = "ROOT DIRECTORY PATH/logfile.txt";
$array[dir_1] = "URL PATH/DOWNLOADFILESFOLDER";
To your actual paths.
Next time, turn on error reporting so you can know when stuff throw errors. One way to do this is adding the following line to the top of your script:
error_reporting(-1) // will show all errors
See: http://php.net/manual/en/function.error-reporting.php