edit to substr and strpos causes Error 500 - php

I'm trying to make some edits to a piece of code but I get an error 500 when I do.
For this example, lets say that
basename(__FILE__)
is my_filename.php
The code is:
$HTTP_GET_VARS['feed_file'] = $_GET['feed_file']
= substr(
basename(__FILE__),
3,
strpos( basename(__FILE__), '.php') -3
);
$HTTP_GET_VARS['feed_file'] would echo as "filename"
Now, if
basename(__FILE__)
is aaa_filename.php
the original code would give $HTTP_GET_VARS['feed_file'] as "_filename"
I changed the code to
$HTTP_GET_VARS['export_feed'] = $_GET['export_feed']
= substr(
basename(__FILE__),
4,
strpos( basename(__FILE__), '.php') -3
);
$HTTP_GET_VARS['export_feed']now echos as "filename."
Ok, so I need to lose one more character from the end of the string. I change the -3 to -4 so that I have
$HTTP_GET_VARS['export_feed'] = $_GET['export_feed']
= substr(
basename(__FILE__),
4,
strpos( basename(__FILE__), '.php') -4
);
Only now the Error 500 is thrown.
Confusing the hell out of me as I thought it was going to be a simple change. Any suggestions on why I'm having problems simply changing the number of chars to drop from the beginning and end of a string?

I would use preg_match to dynamically get "filename":
$basename = 'ab_filename.php';
if(preg_match('/_(.+)\.php$/',$basename,$matches)):
$name = $matches[1]; // 'filename'
endif;
Now $name is just "filename"
Live demo
That aside, the code snippet you shared by itself would not cause a 500 server error. There is probably a domino effect and the error gets triggered elsewhere. Learn how to look up error logs for details.
Finally, if you'll keep using your current approach, don't hardcode the offset (your -3 or -4). Rather compute it dynamically like so:
$basename = 'abcd_filename.php';
$pos_ = strpos($basename,'_') + 1;
$len = strpos( $basename, '.php') - $pos_;
$name = substr($basename, $pos_, $len);
Now $name is "filename"

Related

Trying to change all image file names in a folder to the date and time image was taken

I have a folder of images that I am trying to change to be the date and time the picture was taken. I managed to make it work for the most part, however if the image has the same DateTimeOriginal (to the second), the subsequent images are deleted and replaced with the last one. This is a problem when I use burst on my camera.
I am trying to have the code add "_1" after each file name, unless the file name exists, then I want the "_1" to increase by 1. So far, the code I have will catch the first duplicate name and work properly, but every other matching filename after just deletes the file before it that has the same name (which was just renamed by the code).
In case it makes a difference, I am using XAMPP to run the PHP code in a local directory on my windows 10 PC, but I do test it online as well and have the same outcome.
The following is the code I have come up with by piecing together other code that I have found, and then attempting to customize it. I have a general understanding of PHP through trial and error, but have no education. I feel like I should be using a "while" statement while(file_exists('pictures/'.$timestamp.'_'.$count.'.jpg')) instead of or in conjunction with the current if statement I have if (file_exists('pictures/'.$timestamp.'_'.$count.'.jpg'))
The entire code I am using is here:
<?php
$count=1;
$handle = opendir(dirname(realpath(__FILE__)).'/pictures/');
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
date_default_timezone_set('America/Edmonton');
$dirloc = "pictures/$file";
$newdirloc = "NewPictures/$file";
$exif_data = exif_read_data ($dirloc, $file, 0, true);
$exifString = $exif_data['DateTimeOriginal'];
$exifPieces = explode(":", $exifString);
$newExifString = $exifPieces[0] . "-" . $exifPieces[1] . "-" . $exifPieces[2] . ":" . $exifPieces[3] . ":" . $exifPieces[4];
$exifTimestamp = strtotime($newExifString);
$timestamp = date("y-m-d_H-i-s", $exifTimestamp);
if (file_exists('pictures/'.$timestamp.'_'.$count.'.jpg')) {
$ExistingFile = 'pictures/'.$timestamp.'_'.$count.'.jpg';
$delimiters = ['-', '_', '.'];
$newStr = str_replace($delimiters, $delimiters[0], $ExistingFile);
$NamePieces = explode("-", $newStr);
$count = $NamePieces[6];
++$count;
echo ($file.' has now been changed to '.$timestamp.'_'.$count.'.jpg (Increased count from existing file)<br>');
rename('pictures/'.$file, 'pictures/'.$timestamp.'_'.$count.'.jpg');
}
else {
echo ($file.' has now been changed to '.$timestamp.'_1.jpg (Unique File)<br>');
rename('pictures/'.$file, 'pictures/'.$timestamp.'_1.jpg');
}
}
}
?>
Thanks for helping this newbie figure this out!
Edit:
I think I've narrowed it down to a simpler question.
If it is possible to see if $ANY_NUMBER is in fact any number, what would I say $ANY_NUMBER is = to? With this change, I should be able to get rid of the count=1 at the start, and if it is true that it is any number in that [6] spot, than I should be able to say that count= that [6] spot. Does that make sense?
if (file_exists('pictures/'.$timestamp.'_'.$ANY_NUMBER.'.jpg')) {
$ExistingFile = 'pictures/'.$timestamp.'_'.$ANY_NUMBER.'.jpg';
$delimiters = ['-', '_', '.'];
$newStr = str_replace($delimiters, $delimiters[0], $ExistingFile);
$NamePieces = explode("-", $newStr);
$count = $NamePieces[6];
++$count;
echo ($count);
}

PHP how can i hide part of url

I'm working on a project and need to hide part of a url on the output result of my php file, how can i do that?
the piece of code
if (!$foundPlaylist){
$playList=array(
['publishedAt'],
'thumbId' => $entry[$i]['snippet']['thumbnails']['medium']['url'],
'videosCount' => $videoCount,
'videos' => getVideos($entry[$i]['snippet']['resourceId']['videoId'])
);
array_push($MainFeed,$playList);
}
The result
{ "feed":[{"thumbId":"https://i.ytimg.com/vi/SEchOz24pd8/mqdefault.jpg","videosCount":20,"videoid":"SEchOz24pd8",}],"0":
I need to hide https://i.ytimg.com/vi/ and /mqdefault.jpg from thumbId.
Just use
substr($entry[$i]['snippet']['thumbnails']['medium']['url'], 23, 11);
to select only the part of the URL between position 23 and (23+11) = 34
This, of course, only works if you know the string length is going to be exactly the same for all users. If you know the string length will differ, Anthony's answer might help you out.
I find this most readable:
$path = parse_url(
$entry[$i]['snippet']['thumbnails']['medium']['url'],
PHP_URL_PATH
);
list($user, $code, $image) = explode('/', $path);
echo $code;

Get "at most" last n characters from string using PHP substr?

Answer of this question:
How can I get the last 7 characters of a PHP string? - Stack Overflow
How can I get the last 7 characters of a PHP string?
shows this statement:
substr($s, -7)
However, if length of $s is smaller than 7, it will return empty string(tested on PHP 5.2.6), e.g.
substr("abcd", -4) returns "abcd"
substr("bcd", -4) returns nothing
Currently, my workaround is
trim(substr(" $s",-4)) // prepend 3 blanks
Is there another elegant way to write substr() so it can be more perfect?
====
EDIT: Sorry for the typo of return value of substr("bcd", -4) in my post. It misguides people here. It should return nothing. I already correct it. (# 2016/1/29 17:03 GMT+8)
substr("abcd", -4) returns "abcd"
substr("bcd", -4) returns "bcd"
This is the correct behaviour of substr().
There was a bug in the substr() function in PHP versions 5.2.2-5.2.6 that made it return FALSE when its first argument (start) was negative and its absolute value was larger than the length of the string.
The behaviour is documented.
You should upgrade your PHP to a newer version (5.6 or 7.0). PHP 5.2 is dead and buried more than 5 years ago.
Or, at least, upgrade PHP 5.2 to its latest release (5.2.17)
An elegant solution to your request (assuming you are locked with a faulty PHP version):
function substr52($string, $start, $length)
{
$l = strlen($string);
// Clamp $start and $length to the range [-$l, $l]
// to circumvent the faulty behaviour in PHP 5.2.2-5.2.6
$start = min(max($start, -$l), $l);
$length = min(max($start, -$l), $l);
return substr($string, $start, $length);
}
However, it doesn't handle the cases when $length is 0, FALSE, NULL or when it is omitted.
In my haste with first comment I missed a parameter - I think it should have been more like this.
$s = 'look at all the thingymajigs';
echo trim( substr( $s, ( strlen( $s ) >= 7 ? -7 : -strlen( $s ) ), strlen( $s ) ) );

Check Files In Directory Are Modified

I need to deploy a PHP application written by CodeIgniter to client's web server (CentOS 5 or 6). As PHP is the scripting language, it does not need to compile to binary code for deployment. It has chances that client will modify the PHP program by themselves without a notice to me. If client has modified the program that made the application out of order, we need to take extra man power to find their modification and fix it.
So I would like to made something that can easy to let me know any files (php, css, html, etc.) of the application has been modification after my deployment. Is there any method suggested by anyone?
Thank you,
Use filemtime()
int filemtime ( string $filename )
This PHP function returns the time when the data blocks of a file were being written to, that is, the time when the content of the file was changed.
<?php
// outputs e.g. somefile.txt was last modified: December 12 2014 09:16:23.
$filename = 'somefile.txt';
if (file_exists($filename)) {
echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}
?>
To get the last modification time of a directory, you can use this:
<pre>
$getLastModDir = filemtime("/path/to/directory/.");
</pre>
Take note on the last dot which is needed to see the directory as a file and to actually get a last modification date of it.
This comes in handy when you want just one 'last updated' message on the frontpage of your website and still taking all files of your website into account.
To get the modification date of some remote file, you can use the fine function by notepad at codewalker dot com (with improvements by dma05 at web dot de and madsen at lillesvin dot net).
But you can achieve the same result more easily now with stream_get_meta_data (PHP>4.3.0).
However a problem may arise if some redirection occurs. In such a case, the server HTTP response contains no Last-Modified header, but there is a Location header indicating where to find the file. The function below takes care of any redirections, even multiple redirections, so that you reach the real file of which you want the last modification date.
<?php
// get remote file last modification date (returns unix timestamp)
function GetRemoteLastModified( $uri )
{
// default
$unixtime = 0;
$fp = fopen( $uri, "r" );
if( !$fp ) {return;}
$MetaData = stream_get_meta_data( $fp );
foreach( $MetaData['wrapper_data'] as $response )
{
// case: redirection
if( substr( strtolower($response), 0, 10 ) == 'location: ' )
{
$newUri = substr( $response, 10 );
fclose( $fp );
return GetRemoteLastModified( $newUri );
}
// case: last-modified
elseif( substr( strtolower($response), 0, 15 ) == 'last-modified: ' )
{
$unixtime = strtotime( substr($response, 15) );
break;
}
}
fclose( $fp );
return $unixtime;
}
?>

PHP Find Previous String Position

Is there a way that I can search a variable starting from a given position and find the start position of a string that is in the variable backwards from the given start position.
So for example if I initially do $getstart = strpos($contents, 'position', 0);
I then want to do $getprevpos = prevstrpos($contents, 'previous token', $getstart);
Obviously there is no such function as prevstrpos but I hope you get what I mean.
Example text area (terrible example I now):
Here is an example where I want to find the previous token once I have found the start position of a text string.
you can strrpos( substr($contents, 0, $getstart), 'previous token')
Is there something wrong with strrpos()? If 'offset' is negative: "Negative values will stop searching at the specified point prior to the end of the string."
you can try this. I think it should would for all cases but you should probly test it a bit. Might be a bug here and there but you get the idea. Reverse everything and do a strpos on the reversed string
prevstrpos( $contents, $token, $start )
{
$revToken = strrev($token);
$revStart = strlen($token) - $start;
$revContent = strrev($content);
$revFoundPos = strpos( $revContent, $revToken, $revStart );
if( $revFoundPos != -1 )
{
$foundPos = strlen($token) - $revFoundPos;
}
else
{
$foundPos = -1;
}
return $foundPos;
}

Categories