fwrite(): supplied argument is not a valid stream resource - php

I keep getting 3 errors when I use this code:
Warning: fopen() [function.fopen]: Filename cannot be empty
Warning: fwrite(): supplied argument is not a valid stream resource
Warning: fclose(): supplied argument is not a valid stream resource
I don't know what to do. I'm a php noob.
<?php
$random = rand(1, 9999999999);
$location = "saves/".$random;
while (file_exists($location)) {
$random = rand(1, 999999999999);
$location = "saves/".$random;
}
$content = "some text here";
$fp = fopen($location,"wb");
fwrite($fp,$content);
fclose($fp);
?>

As per your original question before your edit:
Since the file doesn't exist yet, your while condition won't work and that's why you're getting those error messages.
And since you're using a random number for the file, you will never know which file to open in the first place. Just remove the while loop.
Try this:
<?php
$random = rand(1, 999999999999);
$location = "saves/".$random;
$content = "some text here";
$fp = fopen($location,"wb");
fwrite($fp,$content);
fclose($fp);
?>

From the code you have, it looks like $location only exists inside the scope of the while loop. Try
<?php
$location = "";
while (file_exists($location)) {
$random = rand(1, 999999999999);
$location = "saves/".$random;
}
$content = "some text here";
$fp = fopen($location,"wb");
fwrite($fp,$content);
fclose($fp);
?>

first of all, you must set values to your $location variable or since the file is not yet created try this:
$random = rand(1, 999999999999);
$location = "saves/".$random;
$content = "some text here";
//if(file_exists($location)) $fp = fopen($location,"wb");
$fp = fopen($location, 'wb') or die('Cannot open file: '.$location); //implicitly creates file
fwrite($fp,$content);
fclose($fp);

Related

Bug fread in a txt file, read only one time

I'm creating a code to display the name of a server with enterprise rules, So for don't use Mysql i try a new things (for me) use php to read and rewrite files, that work perfectly for one part of my code and work perfectly but for the second he only read one time, and when i do a f5 the code don't increment.
He rewrite correctly because my file was at 000 and become 001
I try to use file() but he is disable since 7.0, try to use SplFileObject but it don't want to display anything and i don't like it because i understand nothing when i use it so i come back to fopen(),fread() and fwrite() and that don't work. I'm inPHP 7.3.1
The code that works :
<?php
if ( isset($_POST) AND !empty($_POST) ) {
$nom = "./config.txt";
$filez = fopen($nom, "r") or die("Unable to open file!");
$i = fread($filez,filesize($nom));
$year = getdate();
$idy = substr($year[year], 2);
$fichier = fopen("./resultsrv.txt", "w") or die("Unable to write file!");
for ($z; $z<$_POST['nbr']+1 ; $z++) {
$id = sprintf("%04d", $i+$z);
$nome = $_POST['type'].$_POST['OS'].$idy.$id."<br>" ;
echo $nome;
$nomewout = str_replace("<br>", ";", $nome);
fwrite($fichier,$nomewout);
}
$handle = fopen("./config.txt", "w") or die("Unable to write file!");
fwrite($handle,$id);
fclose($fichier);
fclose($handle);
}
?>
and the one that doesn't work because he doesn't increment :
<?php
if ( isset($_POST) AND !empty($_POST) ) {
$fileName = 'confchass.txt';
$read = fopen($fileName,"r");
$fn = fopen($fileName,"w+");
$i = fread($read,filesize($fileName));
$id = sprintf("%03d", $i+1);
echo "<div align='center'><h1>Le Chassis</h1>";
echo $_POST['Marque'].$_POST['DC'].$id;
echo "</div>";
fwrite($fn,$id);
fclose($read);
fclose($fn);
}
?>
I want he output a thing like XXXXXX001 and when i refresh or do a new POST from my forms he output XXXXXX002 and XXXXXX003 .... But he actualy output only XXXXXX001
The problem is that you open the file for reading and then for writing. But from the manual...
'w+' Open for reading and writing; place the file pointer at the
beginning of the file and truncate the file to zero length. If the
file does not exist, attempt to create it.
So this will blank out the file before you read the value from it.
To fix this (using your current method, you should read the value, then open it for writing and write the new value...
$read = fopen($fileName,"r");
$i = fread($read,filesize($fileName));
fclose($read);
$id = sprintf("%03d", $i+1);
echo "<div align='center'><h1>Le Chassis</h1>";
echo $id;
echo "</div>";
$fn = fopen($fileName,"w+");
fwrite($fn,$id);
fclose($fn);
You could shorten this by using file_get_contents() and file_put_contents().

fopen says failed to open stream: Undefined error: 0 but the fileexist is passes

I am trying to find the WAV file duration using the following code.
if ( !file_exists($location_wmv.$name_wmv) ) {
echo "<BR> File Does not Exist<BR>";
} else {
echo "<BR> File Exist<BR>";
}
$file = $location_wmv.$name_wmv;
$fp = fopen($file, ‘r’);
$size_in_bytes = filesize($file);
fseek($fp, 20);
$rawheader = fread($fp, 16);
$header = unpack(‘vtype/vchannels/Vsamplerate/Vbytespersec/valignment/vbits’,
$rawheader);
$sec = ceil($size_in_bytes/$header['bytespersec']);
$duration_wmv = $sec;
echo "<BR> Raw Suration.". $duration_wmv . "<BR>";
$duration_wmv = gmdate("H:i:s", $demo_song_duration_sec);
echo "<BR>WAV Duration".$duration_wmv;
Here the file_exists function says that file Exist. But the fopen says failed to open stream: Undefined error: 0
The file is actually present in the folder. But still I get this error.
This:
$fp = fopen($file, ‘r’);
looks iffy. Are those backticks?
Maybe try:
$fp = fopen($file, 'r');
(simple quotes)

PHP file-writing problems

I have a file called "number.txt"(there is a number inside, e.g.: 0 )
And I want to read the number inside the number.txt and use fwrite to write the number plus 1
(number+1), so that each time anyone visit this webpage, the number will add 1.
but when i test it, it only works at first time(now number.txt is 1).
Then i try another time, the fread function read 0 but not 1.
<?php
$fgc = file_get_contents('number.txt');
settype($cont, "integer");
$cont = $cont + 1;
settype($cont, "string");
file_put_contents('number.txt', $cont);
$str = settype($cont, "string");
$fp = fopen( $str ,'w+');
if($fp==false) {
$str = $str + 1;
$fp = fopen( $str ,'w+');
}
if($fp==false) {
$str = $str + 1;
$fp = fopen( $str ,'w+');
}
if($fp==false) {
$str = $str + 1;
$fp = fopen( $str ,'w+');
}
if($fp==false) {
$str = $str + 1;
$fp = fopen( $str ,'w+');
}
$da = $_GET['data'];
fwrite($fp, $da);
fclose($fp);
?>
And why not to do simple like this:
file_put_contents('numbers.txt', is_writeable('numbers.txt')?((int)file_get_contents('numbers.txt'))+1:exit('Failed to open file'));
Borrowing on Eugene's great one-liner, came up with the following solution.
(Credit goes to go Eugene)
The following code will create the file if it does not exist, and increment by +1 each time it is reloaded.
(Tested)
<?php
$filename = "number.txt";
$filename = fopen($filename, 'a') or die("can't open file");
file_put_contents('number.txt', ((int)file_get_contents('number.txt'))+1);
// To show (echo) the contents of the file, you can use one of the following
// include("number.txt");
// echo file_get_contents('number.txt');
?>
It is because you are setting the write data to the old GET var and not the new set var.
fwrite($fp, $da);
Try using
fwrite($fp, $str);
And also you only need to fopen() once.
$filename = 'number.txt';
$content = (int) file_get_contents($filename);
$content++;
var_dump($content);
file_put_contents($filename, $content);
You have to create that file number.txt and insert there 0 as file content, then your script should work every time.
You are reading the contents into the variable $fgc, but you're trying to use $cont to represent that value, which is uninitialized. So your settype call is going to cast that to 0. Instead, try:
$fgc = file_get_contents('number.txt');
settype($fgc, "integer");

PHP Write and Read from Text File

I have an issue with writing and reading to text file.
I have to first write from a text file to another text file some values which I need to read again. Below are the code snippets:
Write to text file:
$fp = #fopen ("text1.txt", "r");
$fh = #fopen("text2.txt", 'a+');
if ($fp) {
//for each line in file
while(!feof($fp)) {
//push lines into array
$thisline = fgets($fp);
$thisline1 = trim($thisline);
$stringData = $thisline1. "\r\n";
fwrite($fh, $stringData);
fwrite($fh, "test");
}
}
fclose($fp);
fclose($fh);
Read from the written textfile
$page = join("",file("text2.txt"));
$kw = explode("\n", $page);
for($i=0;$i<count($kw);$i++){
echo rtrim($kw[$i]);
}
But, if I am not mistaken due to the "/r/n" I used to insert the newline, when I am reading back, there are issues and I need to pass the read values from only the even lines to a function to perform other operations.
How do I resolve this issue? Basically, I need to write certain values to a textfile and then read only the values from the even lines.
I'm not sure whether you have issues with the even line numbers or with reading the file back in.
Here is the solution for the even line numbers.
$page = join("",file("text2.txt"));
$kw = explode("\n", $page);
for($i=0;$i<count($kw);$i++){
$myValue = rtrim($kw[$i]);
if(i % 2 == 0)
{
echo $myValue;
}
}

repeated warnings while trying to upload images

Warning: fopen() expects parameter 1 to be string, array given in /home/speedycm/public_html/speedyautos/carphoto.php on line 42
Warning: filesize() [function.filesize]: stat failed for Array in /home/speedycm/public_html/speedyautos/carphoto.php on line 43
Warning: fread(): supplied argument is not a valid stream resource in /home/speedycm/public_html/speedyautos/carphoto.php on line 43
Warning: fclose(): supplied argument is not a valid stream resource in /home/speedycm/public_html/speedyautos/carphoto.php on line 44
i keep getting these error messages whenever trying to upload a picture on my website and i'm not sure how to sort them out. can anyone please help? lines 36-59 read:
$CarInfo->Load();
if ($hidaction == "addphoto")
{
$ctrP = 0;
foreach ($_FILES['pics'] as $pics)
{
if ($_FILES['pics']['name'][$ctrP] <> "")
{
if (is_uploaded_file($_FILES['pics']['tmp_name'][$ctrP]) or die("No Image: " . $_FILES['pics']['name'][$ctrP]))
{
$ext = substr(strrchr($_FILES['pics']['name'][$ctrP], "."), 1);
$fp = fopen($_FILES["pics"]["tmp_name"], 'rb');
$contents = fread($fp, filesize($_FILES["pics"]["tmp_name"]));
fclose($fp);
if (preg_match("/system/", $contents) OR preg_match("/<\?/", $contents))
{
$error .= "Invalid image: {$_FILES['pics']['name'][$ctrP]}<br />";
//$pieces = explode(".", $_FILES['pics']['name'][$ctrP]);
//$ext = $pieces[count($pieces) - 1];
} elseif ((in_array($ext, $types_array)) AND ($_FILES['pics']["size"][$ctrP] < (MAXFILE_SIZE * 1000000)))
{
$orgImageName = "cid" . $property_id . "_" . str_replace(" ", "_", $_FILES['pics']['name'][$ctrP]);
$thmImageName = "thumb_cid" . $property_id . "_" . str_replace(" ", "_", $_FILES['pics']['name'][$ctrP]);
$dtlImageName = "dtl_cid" . $property_id . "_" . str_replace(" ", "_", $_FILES['pics']['name'][$ctrP]);
many thanks in advance and sorry for the wild indentation btw :-)
I'm not a PHP guy, but it looks to me as if _FILES is a three-dimensional array of strings. Sometimes you use three indexes:
$_FILES['pics']['tmp_name'][$ctrP]
But in the fopen() call, you only use two; this means you're passing a 1D array of strings to fopen(), which is wrong. You need a third index on the array on this line:
$fp = fopen($_FILES["pics"]["tmp_name"], 'rb');
You're forgetting to properly reference the multiple images loaded into the $_FILES array you uploaded in the lines that are causing errors.
Where you have:
$fp = fopen($_FILES["pics"]["tmp_name"], 'rb');
$contents = fread($fp, filesize($_FILES["pics"]["tmp_name"]));
Should be this:
$fp = fopen($_FILES["pics"]["tmp_name"][$ctrP], 'rb');
$contents = fread($fp, filesize($_FILES["pics"]["tmp_name"][$ctrP]));
What you're sending is an array ($_FILES["pics"]["tmp_name"]) into a function that expects a string, which should be the value plucked from the array ($_FILES["pics"]["tmp_name"][$ctrP]).

Categories